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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,931
|
keyframeview.cpp
|
olive-editor_olive/app/widget/keyframeview/keyframeview.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 "keyframeview.h"
#include <QMouseEvent>
#include <QToolTip>
#include <QVBoxLayout>
#include "common/qtutils.h"
#include "dialog/keyframeproperties/keyframeproperties.h"
#include "keyframeviewundo.h"
#include "node/group/group.h"
#include "node/node.h"
#include "node/nodeundo.h"
#include "node/project/serializer/serializer.h"
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
namespace olive {
#define super TimeBasedView
KeyframeView::KeyframeView(QWidget *parent) :
super(parent),
selection_manager_(this),
autoselect_siblings_(true),
max_scroll_(0),
first_chance_mouse_event_(false)
{
setAlignment(Qt::AlignLeft | Qt::AlignTop);
SetDefaultDragMode(RubberBandDrag);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &KeyframeView::customContextMenuRequested, this, &KeyframeView::ShowContextMenu);
}
void KeyframeView::DeleteSelected()
{
if (!selection_manager_.IsDragging()) {
MultiUndoCommand* command = new MultiUndoCommand();
foreach (NodeKeyframe *key, GetSelectedKeyframes()) {
command->add_child(new NodeParamRemoveKeyframeCommand(key));
}
Core::instance()->undo_stack()->push(command, tr("Deleted %1 Keyframe(s)").arg(GetSelectedKeyframes().size()));
}
}
KeyframeView::NodeConnections KeyframeView::AddKeyframesOfNode(Node *n)
{
NodeConnections map;
foreach (const QString& i, n->inputs()) {
map.insert(i, AddKeyframesOfInput(n, i));
}
return map;
}
KeyframeView::InputConnections KeyframeView::AddKeyframesOfInput(Node* on, const QString& oinput)
{
InputConnections vec;
NodeInput resolved = NodeGroup::ResolveInput(NodeInput(on, oinput));
Node *n = resolved.node();
const QString &input = resolved.input();
if (n->IsInputKeyframable(input)) {
int arr_sz = n->InputArraySize(input);
vec.resize(arr_sz + 1);
for (int i=-1; i<arr_sz; i++) {
vec[i+1] = AddKeyframesOfElement(NodeInput(n, input, i));
}
}
return vec;
}
KeyframeView::ElementConnections KeyframeView::AddKeyframesOfElement(const NodeInput& input)
{
const QVector<NodeKeyframeTrack>& tracks = input.node()->GetKeyframeTracks(input);
ElementConnections vec(tracks.size());
for (int i=0; i<tracks.size(); i++) {
vec[i] = AddKeyframesOfTrack(NodeKeyframeTrackReference(input, i));
}
return vec;
}
KeyframeViewInputConnection *KeyframeView::AddKeyframesOfTrack(const NodeKeyframeTrackReference& ref)
{
KeyframeViewInputConnection *track = new KeyframeViewInputConnection(ref, this);
connect(track, &KeyframeViewInputConnection::RequireUpdate, this, &KeyframeView::Redraw);
tracks_.append(track);
Redraw();
return track;
}
void KeyframeView::RemoveKeyframesOfTrack(KeyframeViewInputConnection *connection)
{
if (tracks_.removeOne(connection)) {
foreach (NodeKeyframe *key, connection->GetKeyframes()) {
selection_manager_.Deselect(key);
}
delete connection;
Redraw();
emit SelectionChanged();
}
}
void KeyframeView::SelectAll()
{
foreach (KeyframeViewInputConnection *track, tracks_) {
foreach (NodeKeyframe *key, track->GetKeyframes()) {
SelectKeyframe(key);
}
}
}
void KeyframeView::DeselectAll()
{
selection_manager_.ClearSelection();
Redraw();
}
void KeyframeView::Clear()
{
if (!tracks_.isEmpty()) {
qDeleteAll(tracks_);
tracks_.clear();
Redraw();
}
selection_manager_.ClearSelection();
}
void KeyframeView::SelectionManagerSelectEvent(void *obj)
{
if (autoselect_siblings_) {
NodeKeyframe *key = static_cast<NodeKeyframe*>(obj);
QVector<NodeKeyframe*> keys = key->parent()->GetKeyframesAtTime(key->input(), key->time(), key->element());
foreach (NodeKeyframe* k, keys) {
if (k != key) {
SelectKeyframe(k);
}
}
}
emit SelectionChanged();
}
void KeyframeView::SelectionManagerDeselectEvent(void *obj)
{
if (autoselect_siblings_) {
NodeKeyframe *key = static_cast<NodeKeyframe*>(obj);
QVector<NodeKeyframe*> keys = key->parent()->GetKeyframesAtTime(key->input(), key->time(), key->element());
foreach (NodeKeyframe* k, keys) {
if (k != key) {
DeselectKeyframe(k);
}
}
}
emit SelectionChanged();
}
bool KeyframeView::CopySelected(bool cut)
{
if (!selection_manager_.GetSelectedObjects().empty()) {
ProjectSerializer::SaveData sdata(ProjectSerializer::kOnlyKeyframes);
sdata.SetOnlySerializeKeyframes(selection_manager_.GetSelectedObjects());
ProjectSerializer::Copy(sdata);
if (cut) {
DeleteSelected();
}
return true;
}
return false;
}
bool KeyframeView::Paste(std::function<Node *(const QString &)> find_node_function)
{
if (!GetViewerNode()) {
return false;
}
ProjectSerializer::Result res = ProjectSerializer::Paste(ProjectSerializer::kOnlyKeyframes);
if (res == ProjectSerializer::kSuccess) {
const ProjectSerializer::SerializedKeyframes &keys = res.GetLoadData().keyframes;
MultiUndoCommand *command = new MultiUndoCommand();
rational min = RATIONAL_MAX;
for (auto it=keys.cbegin(); it!=keys.cend(); it++) {
for (NodeKeyframe *key : it.value()) {
min = std::min(min, key->time());
}
}
min -= GetViewerNode()->GetPlayhead();
for (auto it=keys.cbegin(); it!=keys.cend(); it++) {
const QString &paste_id = it.key();
// Find a node with this ID
Node *node_with_id = find_node_function(paste_id);
if (node_with_id) {
for (NodeKeyframe *key : it.value()) {
// Adjust sequence time to node's time
rational t = key->time() - min;
t = GetAdjustedTime(GetTimeTarget(), node_with_id, t, Node::kTransformTowardsInput);
key->set_time(t);
if (NodeKeyframe *existing = node_with_id->GetKeyframeAtTimeOnTrack(key->input(), key->time(), key->track(), key->element())) {
command->add_child(new NodeParamRemoveKeyframeCommand(existing));
}
command->add_child(new NodeParamInsertKeyframeCommand(node_with_id, key));
}
} else {
qDeleteAll(it.value());
}
}
Core::instance()->undo_stack()->push(command, tr("Pasted %1 Keyframe(s)").arg(keys.size()));
return true;
}
return false;
}
void KeyframeView::CatchUpScrollEvent()
{
super::CatchUpScrollEvent();
this->selection_manager_.ForceDragUpdate();
}
void KeyframeView::mousePressEvent(QMouseEvent *event)
{
NodeKeyframe *key_under_cursor = selection_manager_.GetObjectAtPoint(event->pos());
if (HandPress(event) || (!key_under_cursor && PlayheadPress(event))) {
return;
}
// Do mouse press things
if (FirstChanceMousePress(event)) {
first_chance_mouse_event_ = true;
} else if (NodeKeyframe *initial_key = selection_manager_.MousePress(event)) {
selection_manager_.DragStart(initial_key, event, this);
KeyframeDragStart(event);
} else {
selection_manager_.RubberBandStart(event);
}
// Update view
Redraw();
}
void KeyframeView::mouseMoveEvent(QMouseEvent *event)
{
if (HandMove(event) || PlayheadMove(event)) {
return;
}
if (first_chance_mouse_event_) {
FirstChanceMouseMove(event);
} else if (selection_manager_.IsDragging()) {
QString tip;
KeyframeDragMove(event, tip);
selection_manager_.DragMove(event->pos(), tip);
} else if (selection_manager_.IsRubberBanding()) {
selection_manager_.RubberBandMove(event->pos());
Redraw();
}
if (event->buttons()) {
// Signal cursor pos in case we should scroll to catch up to it
emit Dragged(event->pos().x(), event->pos().y());
}
}
void KeyframeView::mouseReleaseEvent(QMouseEvent *event)
{
if (HandRelease(event) || PlayheadRelease(event)) {
return;
}
if (first_chance_mouse_event_) {
FirstChanceMouseRelease(event);
first_chance_mouse_event_ = false;
} else if (selection_manager_.IsDragging()) {
MultiUndoCommand* command = new MultiUndoCommand();
selection_manager_.DragStop(command);
KeyframeDragRelease(event, command);
Core::instance()->undo_stack()->push(command, tr("Moved %1 Keyframe(s)").arg(selection_manager_.GetSelectedObjects().size()));
} else if (selection_manager_.IsRubberBanding()) {
selection_manager_.RubberBandStop();
Redraw();
emit SelectionChanged();
}
emit Released();
}
int BinarySearchFirstKeyframeAfterOrAt(const QVector<NodeKeyframe*> &keys, const rational &time)
{
int low = 0;
int high = keys.size()-1;
while (low <= high) {
int mid = low + (high-low)/2;
NodeKeyframe *test_key = keys.at(mid);
if (test_key->time() == time || (test_key->time() > time && (mid == 0 || keys.at(mid-1)->time() < time))) {
return mid;
} else if (test_key->time() < time) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return keys.size();
}
void KeyframeView::drawForeground(QPainter *painter, const QRectF &rect)
{
int key_sz = QtUtils::QFontMetricsWidth(fontMetrics(), "Oi");
int key_rad = key_sz/2;
selection_manager_.ClearDrawnObjects();
painter->setRenderHint(QPainter::Antialiasing);
foreach (KeyframeViewInputConnection *track, tracks_) {
const QVector<NodeKeyframe*> &keys = track->GetKeyframes();
if (keys.isEmpty()) {
continue;
}
if (!IsYAxisEnabled()) {
// Filter out if the keyframes are offscreen Y
qreal y = GetKeyframeSceneY(track, keys.first());
if (y + key_rad < rect.top() || y - key_rad >= rect.bottom()) {
continue;
}
}
// Find first keyframe to show with binary search
rational left_time = GetUnadjustedKeyframeTime(keys.first(), SceneToTime(rect.left() - key_sz));
int using_index = BinarySearchFirstKeyframeAfterOrAt(keys, left_time);
rational next_key = RATIONAL_MIN;
NodeKeyframe::Type last_type = NodeKeyframe::kInvalid;
for (int i=using_index; i<keys.size(); i++) {
NodeKeyframe *key = keys.at(i);
if (key->time() < next_key && key->type() == last_type) {
// This key will be drawn at exactly the same location as the last one and therefore
// doesn't need to be drawn. See if the next one will be drawn.
i++;
if (i == keys.size()) {
break;
}
key = keys.at(i);
if (key->time() < next_key) {
// Next key still won't be drawn, so we'll switch to a binary search
i = BinarySearchFirstKeyframeAfterOrAt(keys, next_key);
if (i == keys.size()) {
break;
}
key = keys.at(i);
}
}
QRectF key_rect(-key_rad, -key_rad, key_sz, key_sz);
qreal key_x = GetKeyframeSceneX(key);
key_rect.translate(key_x, GetKeyframeSceneY(track, key));
if (key_rect.left() >= rect.right()) {
// Break after last keyframe
break;
}
DrawKeyframe(painter, key, track, key_rect);
next_key = GetUnadjustedKeyframeTime(key, SceneToTime(key_x + 1));
last_type = key->type();
}
}
super::drawForeground(painter, rect);
}
void KeyframeView::DrawKeyframe(QPainter *painter, NodeKeyframe *key, KeyframeViewInputConnection *track, const QRectF &key_rect)
{
painter->setPen(Qt::black);
if (IsKeyframeSelected(key)) {
painter->setBrush(palette().highlight());
} else {
painter->setBrush(track->GetBrush());
}
selection_manager_.DeclareDrawnObject(key, key_rect);
switch (key->type()) {
case NodeKeyframe::kInvalid:
break;
case NodeKeyframe::kLinear:
{
QPointF points[] = {
QPointF(key_rect.center().x(), key_rect.top()),
QPointF(key_rect.right(), key_rect.center().y()),
QPointF(key_rect.center().x(), key_rect.bottom()),
QPointF(key_rect.left(), key_rect.center().y())
};
painter->drawPolygon(points, 4);
break;
}
case NodeKeyframe::kBezier:
painter->drawEllipse(key_rect);
break;
case NodeKeyframe::kHold:
painter->drawRect(key_rect);
break;
}
}
void KeyframeView::ScaleChangedEvent(const double &scale)
{
super::ScaleChangedEvent(scale);
Redraw();
}
void KeyframeView::TimeTargetChangedEvent(ViewerOutput *v)
{
Redraw();
}
void KeyframeView::TimebaseChangedEvent(const rational &timebase)
{
super::TimebaseChangedEvent(timebase);
selection_manager_.SetTimebase(timebase);
}
void KeyframeView::ContextMenuEvent(Menu& m)
{
Q_UNUSED(m)
}
void KeyframeView::SelectKeyframe(NodeKeyframe *key)
{
if (selection_manager_.Select(key)) {
Redraw();
emit SelectionChanged();
}
}
void KeyframeView::DeselectKeyframe(NodeKeyframe *key)
{
if (selection_manager_.Deselect(key)) {
Redraw();
emit SelectionChanged();
}
}
rational KeyframeView::GetUnadjustedKeyframeTime(NodeKeyframe *key, const rational &time)
{
return GetAdjustedTime(GetTimeTarget(), key->parent(), time, Node::kTransformTowardsInput);
}
rational KeyframeView::GetAdjustedKeyframeTime(NodeKeyframe *key)
{
return GetAdjustedTime(key->parent(), GetTimeTarget(), key->time(), Node::kTransformTowardsOutput);
}
double KeyframeView::GetKeyframeSceneX(NodeKeyframe *key)
{
return TimeToScene(GetAdjustedKeyframeTime(key));
}
qreal KeyframeView::GetKeyframeSceneY(KeyframeViewInputConnection *track, NodeKeyframe *key)
{
return mapFromGlobal(QPoint(0, track->GetKeyframeY())).y();
}
void KeyframeView::SceneRectUpdateEvent(QRectF &rect)
{
rect.setY(0);
rect.setHeight(max_scroll_);
}
rational KeyframeView::CalculateNewTimeFromScreen(const rational &old_time, double cursor_diff)
{
return rational::fromDouble(old_time.toDouble() + cursor_diff);
}
void KeyframeView::ShowContextMenu()
{
Menu m;
MenuShared::instance()->AddItemsForEditMenu(&m, false);
QAction* linear_key_action = nullptr;
QAction* bezier_key_action = nullptr;
QAction* hold_key_action = nullptr;
if (!GetSelectedKeyframes().empty()) {
bool all_keys_are_same_type = true;
NodeKeyframe::Type type = GetSelectedKeyframes().front()->type();
for (size_t i=1;i<GetSelectedKeyframes().size();i++) {
NodeKeyframe* key_item = GetSelectedKeyframes().at(i);
NodeKeyframe* prev_item = GetSelectedKeyframes().at(i-1);
if (key_item->type() != prev_item->type()) {
all_keys_are_same_type = false;
break;
}
}
m.addSeparator();
linear_key_action = m.addAction(tr("Linear"));
bezier_key_action = m.addAction(tr("Bezier"));
hold_key_action = m.addAction(tr("Hold"));
if (all_keys_are_same_type) {
switch (type) {
case NodeKeyframe::kInvalid:
break;
case NodeKeyframe::kLinear:
linear_key_action->setChecked(true);
break;
case NodeKeyframe::kBezier:
bezier_key_action->setChecked(true);
break;
case NodeKeyframe::kHold:
hold_key_action->setChecked(true);
break;
}
}
}
m.addSeparator();
ContextMenuEvent(m);
if (!GetSelectedKeyframes().empty()) {
m.addSeparator();
QAction* properties_action = m.addAction(tr("P&roperties"));
connect(properties_action, &QAction::triggered, this, &KeyframeView::ShowKeyframePropertiesDialog);
}
QAction* selected = m.exec(QCursor::pos());
// Process keyframe type changes
if (selected) {
if (selected == linear_key_action
|| selected == bezier_key_action
|| selected == hold_key_action) {
NodeKeyframe::Type new_type;
if (selected == hold_key_action) {
new_type = NodeKeyframe::kHold;
} else if (selected == bezier_key_action) {
new_type = NodeKeyframe::kBezier;
} else {
new_type = NodeKeyframe::kLinear;
}
MultiUndoCommand* command = new MultiUndoCommand();
foreach (NodeKeyframe* item, GetSelectedKeyframes()) {
command->add_child(new KeyframeSetTypeCommand(item, new_type));
}
Core::instance()->undo_stack()->push(command, tr("Set Type of %1 Keyframe(s)").arg(GetSelectedKeyframes().size()));
}
}
}
void KeyframeView::ShowKeyframePropertiesDialog()
{
if (!GetSelectedKeyframes().empty()) {
KeyframePropertiesDialog kd(GetSelectedKeyframes(), timebase(), this);
kd.exec();
}
}
void KeyframeView::UpdateRubberBandForScroll()
{
this->selection_manager_.ForceDragUpdate();
}
void KeyframeView::Redraw()
{
viewport()->update();
}
}
| 16,983
|
C++
|
.cpp
| 510
| 29.005882
| 137
| 0.693301
|
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
|
18,932
|
keyframeviewinputconnection.cpp
|
olive-editor_olive/app/widget/keyframeview/keyframeviewinputconnection.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 "keyframeviewinputconnection.h"
#include "keyframeview.h"
namespace olive {
KeyframeViewInputConnection::KeyframeViewInputConnection(const NodeKeyframeTrackReference &input, KeyframeView *parent) :
QObject(parent),
keyframe_view_(parent),
input_(input),
y_(0),
y_behavior_(kSingleRow),
brush_(Qt::white)
{
Node *n = input.input().node();
connect(n, &Node::KeyframeAdded, this, &KeyframeViewInputConnection::AddKeyframe);
connect(n, &Node::KeyframeRemoved, this, &KeyframeViewInputConnection::RemoveKeyframe);
connect(n, &Node::KeyframeTimeChanged, this, &KeyframeViewInputConnection::KeyframeChanged);
connect(n, &Node::KeyframeTypeChanged, this, &KeyframeViewInputConnection::KeyframeChanged);
connect(n, &Node::KeyframeTypeChanged, this, &KeyframeViewInputConnection::KeyframeTypeChanged);
connect(n, &Node::KeyframeValueChanged, this, &KeyframeViewInputConnection::KeyframeChanged);
}
void KeyframeViewInputConnection::SetKeyframeY(int y)
{
if (y_ != y) {
y_ = y;
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::SetYBehavior(YBehavior e)
{
if (y_behavior_ != e) {
y_behavior_ = e;
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::SetBrush(const QBrush &brush)
{
if (brush_ != brush) {
brush_ = brush;
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::AddKeyframe(NodeKeyframe *key)
{
if (key->key_track_ref() == input_) {
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::RemoveKeyframe(NodeKeyframe *key)
{
if (key->key_track_ref() == input_) {
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::KeyframeChanged(NodeKeyframe *key)
{
if (key->key_track_ref() == input_) {
emit RequireUpdate();
}
}
void KeyframeViewInputConnection::KeyframeTypeChanged(NodeKeyframe *key)
{
if (key->key_track_ref() == input_) {
emit TypeChanged();
}
}
}
| 2,622
|
C++
|
.cpp
| 79
| 30.43038
| 121
| 0.755353
|
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
|
18,933
|
nodeparamviewarraywidget.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewarraywidget.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 "nodeparamviewarraywidget.h"
#include <QEvent>
#include <QHBoxLayout>
#include "node/node.h"
namespace olive {
NodeParamViewArrayWidget::NodeParamViewArrayWidget(Node *node, const QString &input, QWidget* parent) :
QWidget(parent),
node_(node),
input_(input)
{
QHBoxLayout* layout = new QHBoxLayout(this);
count_lbl_ = new QLabel();
layout->addWidget(count_lbl_);
connect(node_, &Node::InputArraySizeChanged, this, &NodeParamViewArrayWidget::UpdateCounter);
UpdateCounter(input_, 0, node_->InputArraySize(input_));
}
void NodeParamViewArrayWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mouseDoubleClickEvent(event);
emit DoubleClicked();
}
void NodeParamViewArrayWidget::UpdateCounter(const QString& input, int old_size, int new_size)
{
Q_UNUSED(old_size)
if (input == input_) {
count_lbl_->setText(tr("%n element(s)", nullptr, new_size));
}
}
NodeParamViewArrayButton::NodeParamViewArrayButton(NodeParamViewArrayButton::Type type, QWidget *parent) :
QPushButton(parent),
type_(type)
{
Retranslate();
int sz = sizeHint().height() / 3 * 2;
setFixedSize(sz, sz);
}
void NodeParamViewArrayButton::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
Retranslate();
}
QPushButton::changeEvent(event);
}
void NodeParamViewArrayButton::Retranslate()
{
if (type_ == kAdd) {
setText(tr("+"));
} else {
setText(tr("-"));
}
}
}
| 2,157
|
C++
|
.cpp
| 66
| 30.015152
| 106
| 0.750604
|
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
|
18,934
|
nodeparamview.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamview.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 "nodeparamview.h"
#include <QApplication>
#include <QMessageBox>
#include <QScrollArea>
#include <QScrollBar>
#include <QSplitter>
#include "node/nodeundo.h"
#include "node/output/viewer/viewer.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
#define super TimeBasedWidget
NodeParamView::NodeParamView(bool create_keyframe_view, QWidget *parent) :
super(true, false, parent),
last_scroll_val_(0),
focused_node_(nullptr),
show_all_nodes_(false)
{
// Create horizontal layout to place scroll area in (and keyframe editing eventually)
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
QSplitter* splitter = new QSplitter(Qt::Horizontal);
layout->addWidget(splitter);
// Set up scroll area for params
param_scroll_area_ = new QScrollArea();
param_scroll_area_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
param_scroll_area_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
param_scroll_area_->setWidgetResizable(true);
splitter->addWidget(param_scroll_area_);
// Param widget
param_widget_container_ = new QWidget();
param_scroll_area_->setWidget(param_widget_container_);
param_widget_area_ = new NodeParamViewDockArea();
QVBoxLayout* param_widget_container_layout = new QVBoxLayout(param_widget_container_);
QMargins param_widget_margin = param_widget_container_layout->contentsMargins();
param_widget_margin.setTop(ruler()->height());
param_widget_container_layout->setContentsMargins(param_widget_margin);
param_widget_container_layout->setSpacing(0);
param_widget_container_layout->addWidget(param_widget_area_);
param_widget_container_layout->addStretch(INT_MAX);
// Create contexts for three different types
context_items_.resize(Track::kCount + 1);
for (int i=0; i<context_items_.size(); i++) {
NodeParamViewContext *c = new NodeParamViewContext(param_widget_area_);
c->setVisible(false);
connect(c, &NodeParamViewContext::AboutToDeleteItem, this, &NodeParamView::ItemAboutToBeRemoved, Qt::DirectConnection);
NodeParamViewItemTitleBar *title_bar = static_cast<NodeParamViewItemTitleBar*>(c->titleBarWidget());
if (i == Track::kVideo || i == Track::kAudio) {
c->SetEffectType(static_cast<Track::Type>(i));
title_bar->SetAddEffectButtonVisible(true);
title_bar->SetText(tr("%1 Nodes").arg(Footage::GetStreamTypeName(static_cast<Track::Type>(i))));
} else {
title_bar->SetText(tr("Other"));
}
context_items_[i] = c;
param_widget_area_->AddItem(c);
}
// Disable collapsing param view (but collapsing keyframe view is permitted)
splitter->setCollapsible(0, false);
// Create global vertical scrollbar on the right
vertical_scrollbar_ = new QScrollBar();
vertical_scrollbar_->setMaximum(0);
layout->addWidget(vertical_scrollbar_);
// Connect scrollbars together
connect(param_scroll_area_->verticalScrollBar(), &QScrollBar::valueChanged, vertical_scrollbar_, &QScrollBar::setValue);
connect(param_scroll_area_->verticalScrollBar(), &QScrollBar::rangeChanged, vertical_scrollbar_, &QScrollBar::setRange);
connect(param_scroll_area_->verticalScrollBar(), &QScrollBar::rangeChanged, this, &NodeParamView::UpdateGlobalScrollBar);
connect(vertical_scrollbar_, &QScrollBar::valueChanged, param_scroll_area_->verticalScrollBar(), &QScrollBar::setValue);
if (create_keyframe_view) {
// Set up keyframe view
QWidget* keyframe_area = new QWidget();
QVBoxLayout* keyframe_area_layout = new QVBoxLayout(keyframe_area);
keyframe_area_layout->setSpacing(0);
keyframe_area_layout->setContentsMargins(0, 0, 0, 0);
// Create ruler object
keyframe_area_layout->addWidget(ruler());
// Create keyframe view
keyframe_view_ = new KeyframeView();
keyframe_view_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
keyframe_view_->SetSnapService(this);
ConnectTimelineView(keyframe_view_);
keyframe_area_layout->addWidget(keyframe_view_);
// Connect ruler and keyframe view together
connect(keyframe_view_, &KeyframeView::Dragged, this, static_cast<void(NodeParamView::*)(int)>(&NodeParamView::SetCatchUpScrollValue));
connect(keyframe_view_, &KeyframeView::Released, this, static_cast<void(NodeParamView::*)()>(&NodeParamView::StopCatchUpScrollTimer));
splitter->addWidget(keyframe_area);
// Set both widgets to 50/50
splitter->setSizes({INT_MAX, INT_MAX});
connect(keyframe_view_->verticalScrollBar(), &QScrollBar::valueChanged, vertical_scrollbar_, &QScrollBar::setValue);
connect(keyframe_view_->verticalScrollBar(), &QScrollBar::valueChanged, param_scroll_area_->verticalScrollBar(), &QScrollBar::setValue);
connect(param_scroll_area_->verticalScrollBar(), &QScrollBar::valueChanged, keyframe_view_->verticalScrollBar(), &QScrollBar::setValue);
connect(vertical_scrollbar_, &QScrollBar::valueChanged, keyframe_view_->verticalScrollBar(), &QScrollBar::setValue);
// TimeBasedWidget's scrollbar has extra functionality that we can take advantage of
keyframe_view_->setHorizontalScrollBar(scrollbar());
keyframe_view_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
} else {
keyframe_view_ = nullptr;
}
// Set a default scale - FIXME: Hardcoded
SetScale(120);
// Pickup on widget focus changes
// DISABLED - we now just handle this with item/titlebar clicking (see ToggleSelect)
/*connect(qApp,
&QApplication::focusChanged,
this,
&NodeParamView::FocusChanged);*/
}
NodeParamView::~NodeParamView()
{
qDeleteAll(context_items_);
}
void NodeParamView::CloseContextsBelongingToProject(Project *p)
{
QVector<Node*> new_contexts = contexts_;
for (int i=0; i<new_contexts.size(); i++) {
if (new_contexts.at(i)->project() == p) {
new_contexts.removeAt(i);
i--;
}
}
SetContexts(new_contexts);
}
/*void NodeParamView::SelectNodes(const QVector<Node *> &nodes)
{
return;
int original_node_count = items_.size();
foreach (Node* n, nodes) {
// If we've already added this node (either a duplicate or a pinned node), don't add another
if (items_.contains(n)) {
continue;
}
// Add to "active" list to represent currently selected node
active_nodes_.append(n);
// Create node UI
AddNode(n, param_widget_area_);
}
if (items_.size() > original_node_count ) {
UpdateItemTime(GetTime());
// Re-arrange keyframes
QueueKeyframePositionUpdate();
SignalNodeOrder();
}
}
void NodeParamView::DeselectNodes(const QVector<Node *> &nodes)
{
return;
// Remove item from map and delete the widget
int original_node_count = items_.size();
foreach (Node* n, nodes) {
// Filter out duplicates
if (!items_.contains(n)) {
continue;
}
if (!pinned_nodes_.contains(n)) {
// Store expanded state
node_expanded_state_.insert(n, items_.value(n)->IsExpanded());
// Remove all keyframes from this node
RemoveNode(n);
}
active_nodes_.removeOne(n);
}
if (items_.size() < original_node_count) {
// Re-arrange keyframes
QueueKeyframePositionUpdate();
SignalNodeOrder();
}
}*/
void NodeParamView::UpdateContexts()
{
bool changes_made = false;
foreach (Node *ctx, current_contexts_) {
if (!contexts_.contains(ctx)) {
// Context is being removed
RemoveContext(ctx);
changes_made = true;
}
}
foreach (Node *ctx, contexts_) {
if (!current_contexts_.contains(ctx)) {
// Context is being added
AddContext(ctx);
changes_made = true;
}
}
if (changes_made) {
current_contexts_ = contexts_;
if (IsGroupMode()) {
// Check inputs that have been passed through
NodeGroup *group = static_cast<NodeGroup*>(contexts_.first());
for (auto it=group->GetInputPassthroughs().cbegin(); it!=group->GetInputPassthroughs().cend(); it++) {
GroupInputPassthroughAdded(group, it->second);
}
connect(group, &NodeGroup::InputPassthroughAdded, this, &NodeParamView::GroupInputPassthroughAdded);
connect(group, &NodeGroup::InputPassthroughRemoved, this, &NodeParamView::GroupInputPassthroughRemoved);
}
foreach (NodeParamViewContext *ctx, context_items_) {
SortItemsInContext(ctx);
}
if (keyframe_view_) {
QueueKeyframePositionUpdate();
}
}
}
void NodeParamView::ItemAboutToBeRemoved(NodeParamViewItem *item)
{
if (keyframe_view_) {
for (auto it=item->GetKeyframeConnections().begin(); it!=item->GetKeyframeConnections().end(); it++) {
for (auto jt=it->begin(); jt!=it->end(); jt++) {
for (auto kt=jt->begin(); kt!=jt->end(); kt++) {
keyframe_view_->RemoveKeyframesOfTrack(*kt);
}
}
}
}
QVector<NodeParamViewItem *> copy = selected_nodes_;
if (copy.removeOne(item)) {
SetSelectedNodes(copy);
}
}
void NodeParamView::ItemClicked()
{
ToggleSelect(static_cast<NodeParamViewItem*>(sender()));
}
void NodeParamView::SelectNodeFromConnectedLink(Node *node)
{
NodeParamViewItem *item = static_cast<NodeParamViewItem *>(sender());
Node::ContextPair p = {node, item->GetContext()};
SetSelectedNodes({p});
}
void NodeParamView::RequestEditTextInViewer()
{
NodeParamViewItem *item = static_cast<NodeParamViewItem *>(sender());
SetSelectedNodes({item});
emit RequestViewerToStartEditingText();
}
void NodeParamView::SetContexts(const QVector<Node *> &contexts)
{
// Setting contexts is expensive, so we queue it here to prevent multiple calls in a short timespan
contexts_ = contexts;
UpdateContexts();
}
void NodeParamView::resizeEvent(QResizeEvent *event)
{
super::resizeEvent(event);
vertical_scrollbar_->setPageStep(vertical_scrollbar_->height());
}
void NodeParamView::ScaleChangedEvent(const double &scale)
{
super::ScaleChangedEvent(scale);
if (keyframe_view_) {
keyframe_view_->SetScale(scale);
}
}
void NodeParamView::TimebaseChangedEvent(const rational &timebase)
{
super::TimebaseChangedEvent(timebase);
if (keyframe_view_) {
keyframe_view_->SetTimebase(timebase);
}
foreach (NodeParamViewContext* ctx, context_items_) {
ctx->SetTimebase(timebase);
}
}
void NodeParamView::ConnectedNodeChangeEvent(ViewerOutput *n)
{
if (keyframe_view_) {
// Set viewer as a time target
keyframe_view_->SetTimeTarget(n);
}
foreach (NodeParamViewContext* item, context_items_) {
item->SetTimeTarget(n);
}
}
void ReconnectOutputsIfNotDeletingNode(MultiUndoCommand *c, NodeViewDeleteCommand *dc, Node *output, Node *deleting, Node *context)
{
for (auto it=deleting->output_connections().cbegin(); it!=deleting->output_connections().cend(); it++) {
const NodeInput &proposed_reconnect = it->second;
if (dc->ContainsNode(proposed_reconnect.node(), context)) {
// Uh-oh we're deleting this node too, instead connect to its outputs
ReconnectOutputsIfNotDeletingNode(c, dc, output, proposed_reconnect.node(), context);
} else {
c->add_child(new NodeEdgeAddCommand(output, it->second));
}
}
}
void NodeParamView::DeleteSelected()
{
if (keyframe_view_ && keyframe_view_->hasFocus()) {
keyframe_view_->DeleteSelected();
} else if (!selected_nodes_.isEmpty()) {
MultiUndoCommand *c = new MultiUndoCommand();
// Create command to delete node from context and/or graph
NodeViewDeleteCommand *dc = new NodeViewDeleteCommand();
c->add_child(dc);
// Add all nodes
foreach (NodeParamViewItem *item, selected_nodes_) {
Node *n = item->GetNode();
dc->AddNode(n, item->GetContext());
}
// Make reconnections where possible
foreach (NodeParamViewItem *item, selected_nodes_) {
Node *n = item->GetNode();
Node *node_being_deleted = n;
Node *connected_to_effect_input = nullptr;
while (true) {
if (node_being_deleted->GetEffectInput().IsValid()) {
if ((connected_to_effect_input = node_being_deleted->GetEffectInput().GetConnectedOutput())) {
if (dc->ContainsNode(connected_to_effect_input, item->GetContext())) {
// Node's getting deleted, recurse
node_being_deleted = connected_to_effect_input;
continue;
}
}
}
break;
}
if (connected_to_effect_input) {
ReconnectOutputsIfNotDeletingNode(c, dc, connected_to_effect_input, n, item->GetContext());
}
}
Core::instance()->undo_stack()->push(c, tr("Deleted %1 Node(s)").arg(selected_nodes_.size()));
}
}
void NodeParamView::SetSelectedNodes(const QVector<NodeParamViewItem *> &nodes, bool handle_focused_node, bool emit_signal)
{
if (handle_focused_node) {
handle_focused_node = !focused_node_ || selected_nodes_.contains(focused_node_);
}
foreach (NodeParamViewItem *n, selected_nodes_) {
n->SetHighlighted(false);
}
selected_nodes_ = nodes;
QVector<Node::ContextPair> p;
if (emit_signal) {
p.resize(selected_nodes_.size());
}
for (int i=0; i<selected_nodes_.size(); i++) {
NodeParamViewItem *n = selected_nodes_.at(i);
n->SetHighlighted(true);
if (emit_signal) {
p[i] = {n->GetNode(), n->GetContext()};
}
}
if (handle_focused_node) {
focused_node_ = nullptr;
foreach (NodeParamViewItem *n, selected_nodes_) {
if (n->GetNode()->HasGizmos()) {
focused_node_ = n;
break;
}
}
Node *n = focused_node_ ? focused_node_->GetNode() : nullptr;
emit FocusedNodeChanged(n);
}
if (emit_signal) {
emit SelectedNodesChanged(p);
}
}
void NodeParamView::SetSelectedNodes(const QVector<Node::ContextPair> &nodes, bool emit_signal)
{
QVector<NodeParamViewItem*> items;
foreach (const Node::ContextPair &n, nodes) {
for (auto it=context_items_.cbegin(); it!=context_items_.cend(); it++) {
NodeParamViewContext *ctx = *it;
NodeParamViewItem *item = ctx->GetItem(n.node, n.context);
if (item) {
items.append(item);
}
}
}
SetSelectedNodes(items, true, emit_signal);
if (!selected_nodes_.empty()) {
NodeParamViewItem *scrolled_to = selected_nodes_.front();
param_scroll_area_->ensureWidgetVisible(scrolled_to, 0, 0);
QPoint viewport_pos = scrolled_to->mapTo(param_scroll_area_, scrolled_to->geometry().topLeft());
param_scroll_area_->verticalScrollBar()->setValue(viewport_pos.y());
}
}
Node *NodeParamView::GetNodeWithID(const QString &id)
{
return GetNodeWithIDAndIgnoreList(id, QVector<Node*>());
}
Node *NodeParamView::GetNodeWithIDAndIgnoreList(const QString &id, const QVector<Node *> &ignore)
{
for (NodeParamViewItem *item : selected_nodes_) {
if (item->GetNode()->id() == id && !ignore.contains(item->GetNode())) {
return item->GetNode();
}
}
for (NodeParamViewContext *ctx : context_items_) {
for (NodeParamViewItem *item : ctx->GetItems()) {
if (item->GetNode()->id() == id && !ignore.contains(item->GetNode())) {
return item->GetNode();
}
}
}
return nullptr;
}
bool NodeParamView::CopySelected(bool cut)
{
if (super::CopySelected(cut)) {
return true;
}
if (keyframe_view_ && keyframe_view_->hasFocus()) {
if (keyframe_view_->CopySelected(cut)) {
return true;
}
}
if (contexts_.empty()) {
return false;
}
ProjectSerializer::SaveData sdata(ProjectSerializer::kOnlyNodes);
ProjectSerializer::SerializedProperties properties;
QVector<Node*> nodes;
for (NodeParamViewItem *item : selected_nodes_) {
Node *n = item->GetNode();
if (!nodes.contains(n)) {
nodes.append(n);
Node::Position pos = item->GetContext()->GetNodePositionDataInContext(n);
properties[n][QStringLiteral("x")] = QString::number(pos.position.x());
properties[n][QStringLiteral("y")] = QString::number(pos.position.y());
properties[n][QStringLiteral("expanded")] = QString::number(pos.expanded);
}
}
sdata.SetOnlySerializeNodesAndResolveGroups(nodes);
sdata.SetProperties(properties);
ProjectSerializer::Copy(sdata);
if (cut) {
DeleteSelected();
}
return false;
}
bool NodeParamView::Paste()
{
if (keyframe_view_) {
if (keyframe_view_->Paste(std::bind(&NodeParamView::GetNodeWithID, this, std::placeholders::_1))) {
return true;
}
}
return Paste(this, std::bind(&NodeParamView::GenerateExistingPasteMap, this, std::placeholders::_1));
}
bool NodeParamView::Paste(QWidget *parent, std::function<QHash<Node *, Node*>(const ProjectSerializer::Result &)> get_existing_map_function)
{
ProjectSerializer::Result res = ProjectSerializer::Paste(ProjectSerializer::kOnlyNodes);
if (res.GetLoadData().nodes.isEmpty()) {
return false;
}
// Determine if any nodes of this type are already in the editor
QHash<Node*, Node*> existing_nodes = get_existing_map_function(res);
QVector<Node*> nodes_to_paste_as_new = res.GetLoadData().nodes;
MultiUndoCommand *command = new MultiUndoCommand();
if (!existing_nodes.empty()) {
QMessageBox b(parent);
b.setWindowTitle(tr("Paste Nodes"));
QStringList node_names;
for (auto it=existing_nodes.cbegin(); it!=existing_nodes.cend(); it++) {
node_names.append(it.key()->GetLabelAndName());
}
b.setText(tr("The following node types already exist in this context:\n\n"
"%1\n\n"
"Do you wish to paste values onto the existing nodes or paste new nodes?").arg(node_names.join('\n')));
auto as_vals = b.addButton(tr("Paste As Values"), QMessageBox::YesRole);
auto as_nodes = b.addButton(tr("Paste As Nodes"), QMessageBox::NoRole);
auto cancel_btn = b.addButton(QMessageBox::Cancel);
Q_UNUSED(as_nodes)
b.exec();
if (b.clickedButton() == cancel_btn) {
// Delete pasted nodes and clear array so no later code runs
qDeleteAll(nodes_to_paste_as_new);
nodes_to_paste_as_new.clear();
} else if (b.clickedButton() == as_vals) {
// Filter out existing nodes
for (auto it=existing_nodes.cbegin(); it!=existing_nodes.cend(); it++) {
Node::CopyInputs(it.value(), it.key(), false, command);
nodes_to_paste_as_new.removeOne(it.value());
}
}
}
if (!nodes_to_paste_as_new.isEmpty()) {
Node::PositionMap map;
for (auto it=res.GetLoadData().properties.cbegin(); it!=res.GetLoadData().properties.cend(); it++) {
if (nodes_to_paste_as_new.contains(it.key())) {
Node::Position pos;
const QMap<QString, QString> &node_props = it.value();
pos.position.setX(node_props.value(QStringLiteral("x")).toDouble());
pos.position.setY(node_props.value(QStringLiteral("y")).toDouble());
pos.expanded = node_props.value(QStringLiteral("expanded")).toDouble();
map.insert(it.key(), pos);
}
}
}
Core::instance()->undo_stack()->push(command, tr("Pasted %1 Node(s)").arg(nodes_to_paste_as_new.size()));
return true;
}
void NodeParamView::QueueKeyframePositionUpdate()
{
QMetaObject::invokeMethod(this, &NodeParamView::UpdateElementY, Qt::QueuedConnection);
}
void NodeParamView::AddContext(Node *ctx)
{
NodeParamViewContext *item = GetContextItemFromContext(ctx);
// TEMP: Creating many NPV items is EXTREMELY slow so limit to one item per context for now.
// I have a better solution in the works to use one UI for several nodes, but I haven't
// done it yet, and this can severely affect productivity.
if (item->GetContexts().size() == 1) {
return;
}
// Queued so that if any further work is done in connecting this node to the context, it'll be
// done before our sorting function is called
connect(ctx, &Node::NodeAddedToContext, this, &NodeParamView::NodeAddedToContext, Qt::QueuedConnection);
connect(ctx, &Node::NodeRemovedFromContext, this, &NodeParamView::NodeRemovedFromContext, Qt::QueuedConnection);
item->AddContext(ctx);
item->setVisible(true);
for (auto it=ctx->GetContextPositions().cbegin(); it!=ctx->GetContextPositions().cend(); it++) {
AddNode(it.key(), ctx, item);
}
}
void NodeParamView::RemoveContext(Node *ctx)
{
disconnect(ctx, &Node::NodeAddedToContext, this, &NodeParamView::NodeAddedToContext);
disconnect(ctx, &Node::NodeRemovedFromContext, this, &NodeParamView::NodeRemovedFromContext);
foreach (NodeParamViewContext *item, context_items_) {
item->RemoveContext(ctx);
item->RemoveNodesWithContext(ctx);
if (item->GetContexts().isEmpty()) {
item->setVisible(false);
}
}
}
void NodeParamView::AddNode(Node *n, Node *ctx, NodeParamViewContext *context)
{
if ((n->GetFlags() & Node::kDontShowInParamView) && !IsGroupMode() && !show_all_nodes_) {
return;
}
NodeParamViewItem* item = new NodeParamViewItem(n, IsGroupMode() ? kCheckBoxesOnNonConnected : kNoCheckBoxes, context->GetDockArea());
connect(item, &NodeParamViewItem::RequestSelectNode, this, &NodeParamView::SelectNodeFromConnectedLink);
connect(item, &NodeParamViewItem::PinToggled, this, &NodeParamView::PinNode);
connect(item, &NodeParamViewItem::InputCheckedChanged, this, &NodeParamView::InputCheckBoxChanged);
connect(item, &NodeParamViewItem::Clicked, this, &NodeParamView::ItemClicked);
connect(item, &NodeParamViewItem::RequestEditTextInViewer, this, &NodeParamView::RequestEditTextInViewer);
item->SetContext(ctx);
item->SetTimeTarget(GetConnectedNode());
item->SetTimebase(timebase());
context->AddNode(item);
if (!focused_node_ && n->HasGizmos()) {
// We'll focus this node now
SetSelectedNodes({item});
}
if (keyframe_view_) {
connect(item, &NodeParamViewItem::dockLocationChanged, this, &NodeParamView::QueueKeyframePositionUpdate);
connect(item, &NodeParamViewItem::ArrayExpandedChanged, this, &NodeParamView::QueueKeyframePositionUpdate);
connect(item, &NodeParamViewItem::ExpandedChanged, this, &NodeParamView::QueueKeyframePositionUpdate);
connect(item, &NodeParamViewItem::Moved, this, &NodeParamView::QueueKeyframePositionUpdate);
connect(item, &NodeParamViewItem::InputArraySizeChanged, this, &NodeParamView::InputArraySizeChanged);
item->SetKeyframeConnections(keyframe_view_->AddKeyframesOfNode(n));
}
}
int GetDistanceBetweenNodes(Node *start, Node *end)
{
if (start == end) {
return 0;
}
for (auto it=start->input_connections().cbegin(); it!=start->input_connections().cend(); it++) {
int this_node_dist = GetDistanceBetweenNodes(it->second, end);
if (this_node_dist != -1) {
return 1 + this_node_dist;
}
}
return -1;
}
void NodeParamView::SortItemsInContext(NodeParamViewContext *context_item)
{
QVector<QPair<NodeParamViewItem*, int> > distances;
for (auto it=context_item->GetItems().cbegin(); it!=context_item->GetItems().cend(); it++) {
NodeParamViewItem *item = *it;
int distance = -1;
foreach (Node *ctx, context_item->GetContexts()) {
distance = qMax(distance, GetDistanceBetweenNodes(ctx, item->GetNode()));
}
if (distance == -1) {
distance = INT_MAX;
}
bool inserted = false;
QPair<NodeParamViewItem*, int> dist(item, distance);
for (int i=0; i<distances.size(); i++) {
if (distances.at(i).second < distance) {
distances.insert(i, dist);
inserted = true;
break;
}
}
if (!inserted) {
distances.append(dist);
}
}
foreach (auto info, distances) {
context_item->GetDockArea()->AddItem(info.first);
}
}
NodeParamViewContext *NodeParamView::GetContextItemFromContext(Node *ctx)
{
Track::Type ctx_type = Track::kCount;
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(ctx)) {
if (clip->track()) {
if (clip->track()->type() != Track::kNone) {
ctx_type = clip->track()->type();
}
}
} else if (Track *track = dynamic_cast<Track*>(ctx)) {
if (track->type() != Track::kNone) {
ctx_type = track->type();
}
}
return context_items_.at(ctx_type);
}
void NodeParamView::ToggleSelect(NodeParamViewItem *item)
{
QVector<NodeParamViewItem*> new_sel;
if (qApp->keyboardModifiers() & Qt::ShiftModifier) {
new_sel = selected_nodes_;
}
if (selected_nodes_.contains(item)) {
// De-select this node
if (qApp->keyboardModifiers() & Qt::ShiftModifier) {
new_sel.removeOne(item);
SetSelectedNodes(new_sel, true);
}
} else {
new_sel.append(item);
SetSelectedNodes(new_sel, false);
if (!new_sel.contains(focused_node_)) {
// This node gets sent to both the curve editor and viewer, so we focus it even if it has
// no gizmos
focused_node_ = item;
emit FocusedNodeChanged(focused_node_ ? focused_node_->GetNode() : nullptr);
}
}
}
QHash<Node *, Node *> NodeParamView::GenerateExistingPasteMap(const ProjectSerializer::Result &r)
{
QVector<Node*> ignore_nodes;
QHash<Node*, Node*> existing_nodes;
for (Node *n : r.GetLoadData().nodes) {
if (Node *existing = GetNodeWithIDAndIgnoreList(n->id(), ignore_nodes)) {
existing_nodes.insert(existing, n);
ignore_nodes.append(existing);
}
}
return existing_nodes;
}
void NodeParamView::UpdateGlobalScrollBar()
{
if (keyframe_view_) {
keyframe_view_->SetMaxScroll(param_widget_container_->height() - ruler()->height());
}
}
void NodeParamView::PinNode(bool pin)
{
NodeParamViewItem* item = static_cast<NodeParamViewItem*>(sender());
Node* node = item->GetNode();
if (pin) {
pinned_nodes_.append(node);
} else {
pinned_nodes_.removeOne(node);
if (!active_nodes_.contains(node)) {
//RemoveNode(node);
}
}
}
/*void NodeParamView::FocusChanged(QWidget* old, QWidget* now)
{
Q_UNUSED(old)
QObject* parent = now;
while (parent) {
if (NodeParamViewItem* item = dynamic_cast<NodeParamViewItem*>(parent)) {
// Found a NodeParamViewItem that isn't already focused, see if it belongs to us
bool ours = false;
do {
parent = parent->parent();
if (parent == this) {
ours = true;
break;
}
} while (parent);
if (ours) {
//ToggleSelect(item);
Q_UNUSED(item)
}
break;
}
parent = parent->parent();
}
}*/
void NodeParamView::UpdateElementY()
{
for (NodeParamViewContext *ctx : context_items_) {
for (auto it=ctx->GetItems().cbegin(); it!=ctx->GetItems().cend(); it++) {
NodeParamViewItem *item = *it;
Node *node = item->GetNode();
const KeyframeView::NodeConnections &connections = item->GetKeyframeConnections();
if (!connections.isEmpty()) {
for (const QString& input : node->inputs()) {
if (!(node->GetInputFlags(input) & kInputFlagHidden)) {
int arr_sz = NodeGroup::ResolveInput(NodeInput(node, input)).GetArraySize();
for (int i=-1; i<arr_sz; i++) {
NodeInput ic = {node, input, i};
int y = item->GetElementY(ic);
// For some reason Qt's mapToGlobal doesn't seem to handle this, so we offset here
y += vertical_scrollbar_->value();
const KeyframeView::InputConnections &input_con = connections.value(input);
int use_index = i + 1;
if (use_index < input_con.size()) {
const KeyframeView::ElementConnections &ele_con = input_con.at(ic.element()+1);
for (KeyframeViewInputConnection *track : ele_con) {
track->SetKeyframeY(y);
}
}
}
}
}
}
}
}
}
void NodeParamView::NodeAddedToContext(Node *n)
{
Node *ctx = static_cast<Node*>(sender());
NodeParamViewContext *item = GetContextItemFromContext(ctx);
AddNode(n, ctx, item);
SortItemsInContext(item);
if (keyframe_view_) {
QueueKeyframePositionUpdate();
}
}
void NodeParamView::NodeRemovedFromContext(Node *n)
{
Node *ctx = static_cast<Node*>(sender());
foreach (NodeParamViewContext *ctx_item, context_items_) {
ctx_item->RemoveNode(n, ctx);
}
if (keyframe_view_) {
QueueKeyframePositionUpdate();
}
}
void NodeParamView::InputCheckBoxChanged(const NodeInput &input, bool e)
{
NodeGroup *group = static_cast<NodeGroup*>(contexts_.first());
if (e) {
group->AddInputPassthrough(input);
} else {
group->RemoveInputPassthrough(input);
}
}
void NodeParamView::GroupInputPassthroughAdded(NodeGroup *group, const NodeInput &input)
{
foreach (NodeParamViewContext *pvctx, context_items_) {
pvctx->SetInputChecked(input, true);
}
}
void NodeParamView::GroupInputPassthroughRemoved(NodeGroup *group, const NodeInput &input)
{
foreach (NodeParamViewContext *pvctx, context_items_) {
pvctx->SetInputChecked(input, false);
}
}
void NodeParamView::InputArraySizeChanged(const QString &input, int, int new_size)
{
NodeParamViewItem *sender = static_cast<NodeParamViewItem *>(this->sender());
KeyframeView::NodeConnections &connections = sender->GetKeyframeConnections();
KeyframeView::InputConnections &inputs = connections[input];
int adj_new_size = new_size + 1;
if (adj_new_size != inputs.size()) {
if (adj_new_size < inputs.size()) {
// Remove elements from keyframe view
for (int i = adj_new_size; i < inputs.size(); i++) {
const KeyframeView::ElementConnections &ec = inputs.at(i);
for (auto kc : ec) {
keyframe_view_->RemoveKeyframesOfTrack(kc);
}
}
// Resize vector to match new size
inputs.resize(adj_new_size);
} else {
// Add elements
int old_size = inputs.size();
// Resize vector to match
inputs.resize(adj_new_size);
// Fill in extra elements
for (int i = old_size; i < inputs.size(); i++) {
inputs[i] = keyframe_view_->AddKeyframesOfElement(NodeInput(sender->GetNode(), input, i - 1));
}
}
}
QueueKeyframePositionUpdate();
}
}
| 30,673
|
C++
|
.cpp
| 810
| 33.198765
| 140
| 0.69327
|
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
|
18,935
|
nodeparamviewitembase.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewitembase.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 "nodeparamviewitembase.h"
#include <QEvent>
#include <QPainter>
namespace olive {
#define super QDockWidget
NodeParamViewItemBase::NodeParamViewItemBase(QWidget *parent) :
super(parent),
highlighted_(false)
{
// Create title bar widget
title_bar_ = new NodeParamViewItemTitleBar(this);
// Add title bar to widget
this->setTitleBarWidget(title_bar_);
// Connect title bar to this
connect(title_bar_, &NodeParamViewItemTitleBar::ExpandedStateChanged, this, &NodeParamViewItemBase::SetExpanded);
connect(title_bar_, &NodeParamViewItemTitleBar::PinToggled, this, &NodeParamViewItemBase::PinToggled);
connect(title_bar_, &NodeParamViewItemTitleBar::Clicked, this, &NodeParamViewItemBase::Clicked);
// Use dummy QWidget to retain width when not expanded (QDockWidget seems to ignore the titlebar
// size hints and will shrink as small as possible if the body is hidden)
hidden_body_ = new QWidget(this);
// Default to hidden body, this also seems to fix an issue with clicks being intermittent
// on the titlebar
setWidget(hidden_body_);
setAutoFillBackground(true);
setFocusPolicy(Qt::ClickFocus);
}
bool NodeParamViewItemBase::IsExpanded() const
{
return title_bar_->IsExpanded();
}
QString NodeParamViewItemBase::GetTitleBarTextFromNode(Node *n)
{
if (n->GetLabel().isEmpty()) {
return n->Name();
} else {
return tr("%1 (%2)").arg(n->GetLabel(), n->Name());
}
}
void NodeParamViewItemBase::SetBody(QWidget *body)
{
body_ = body;
body_->setParent(this);
if (title_bar_->IsExpanded()) {
setWidget(body_);
}
}
void NodeParamViewItemBase::paintEvent(QPaintEvent *event)
{
super::paintEvent(event);
// Draw border if focused
if (highlighted_) {
QPainter p(this);
p.setBrush(Qt::NoBrush);
p.setPen(palette().highlight().color());
p.drawRect(rect().adjusted(0, 0, -1, -1));
}
}
void NodeParamViewItemBase::SetExpanded(bool e)
{
setWidget(e ? body_ : hidden_body_);
title_bar_->SetExpanded(e);
emit ExpandedChanged(e);
}
void NodeParamViewItemBase::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
Retranslate();
}
super::changeEvent(e);
}
void NodeParamViewItemBase::moveEvent(QMoveEvent *event)
{
super::moveEvent(event);
emit Moved();
}
void NodeParamViewItemBase::mousePressEvent(QMouseEvent *e)
{
super::mousePressEvent(e);
emit Clicked();
}
}
| 3,115
|
C++
|
.cpp
| 95
| 30.031579
| 115
| 0.750084
|
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
|
18,936
|
nodeparamviewitemtitlebar.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewitemtitlebar.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 "nodeparamviewitemtitlebar.h"
#include <QHBoxLayout>
#include <QPainter>
#include "ui/icons/icons.h"
namespace olive {
NodeParamViewItemTitleBar::NodeParamViewItemTitleBar(QWidget *parent) :
QWidget(parent),
draw_border_(true)
{
QHBoxLayout* layout = new QHBoxLayout(this);
collapse_btn_ = new CollapseButton(this);
connect(collapse_btn_, &QPushButton::clicked, this, &NodeParamViewItemTitleBar::ExpandedStateChanged);
layout->addWidget(collapse_btn_);
lbl_ = new QLabel(this);
layout->addWidget(lbl_);
// Place next buttons on the far side
layout->addStretch();
add_fx_btn_ = new QPushButton(this);
add_fx_btn_->setIcon(icon::AddEffect);
add_fx_btn_->setFixedSize(add_fx_btn_->sizeHint().height(), add_fx_btn_->sizeHint().height());
add_fx_btn_->setVisible(false);
layout->addWidget(add_fx_btn_);
connect(add_fx_btn_, &QPushButton::clicked, this, &NodeParamViewItemTitleBar::AddEffectButtonClicked);
pin_btn_ = new QPushButton(QStringLiteral("P"), this);
pin_btn_->setCheckable(true);
pin_btn_->setFixedSize(pin_btn_->sizeHint().height(), pin_btn_->sizeHint().height());
pin_btn_->setVisible(false);
layout->addWidget(pin_btn_);
connect(pin_btn_, &QPushButton::clicked, this, &NodeParamViewItemTitleBar::PinToggled);
enabled_checkbox_ = new QCheckBox(this);
enabled_checkbox_->setVisible(false);
layout->addWidget(enabled_checkbox_);
connect(enabled_checkbox_, &QCheckBox::clicked, this, &NodeParamViewItemTitleBar::EnabledCheckBoxClicked);
}
void NodeParamViewItemTitleBar::SetExpanded(bool e)
{
draw_border_ = e;
collapse_btn_->setChecked(e);
update();
}
void NodeParamViewItemTitleBar::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
if (draw_border_) {
QPainter p(this);
// Draw bottom border using text color
int bottom = height() - 1;
p.setPen(palette().text().color());
p.drawLine(0, bottom, width(), bottom);
}
}
void NodeParamViewItemTitleBar::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
emit Clicked();
}
void NodeParamViewItemTitleBar::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mouseDoubleClickEvent(event);
collapse_btn_->click();
}
}
| 2,932
|
C++
|
.cpp
| 76
| 35.710526
| 108
| 0.754064
|
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
|
18,937
|
nodeparamviewconnectedlabel.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewconnectedlabel.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 "nodeparamviewconnectedlabel.h"
#include <QHBoxLayout>
#include "common/qtutils.h"
#include "core.h"
#include "node/node.h"
#include "node/nodeundo.h"
#include "widget/collapsebutton/collapsebutton.h"
#include "widget/menu/menu.h"
namespace olive {
NodeParamViewConnectedLabel::NodeParamViewConnectedLabel(const NodeInput &input, QWidget *parent) :
QWidget(parent),
input_(input),
connected_node_(nullptr),
viewer_(nullptr)
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
QSizePolicy p = sizePolicy();
p.setHorizontalStretch(1);
p.setHorizontalPolicy(QSizePolicy::Expanding);
setSizePolicy(p);
// Set up label area
QHBoxLayout *label_layout = new QHBoxLayout();
label_layout->setSpacing(QtUtils::QFontMetricsWidth(fontMetrics(), QStringLiteral(" ")));
label_layout->setContentsMargins(0, 0, 0, 0);
layout->addLayout(label_layout);
CollapseButton *collapse_btn = new CollapseButton(this);
collapse_btn->setChecked(false);
label_layout->addWidget(collapse_btn);
label_layout->addWidget(new QLabel(tr("Connected to"), this));
connected_to_lbl_ = new ClickableLabel(this);
connected_to_lbl_->setCursor(Qt::PointingHandCursor);
connected_to_lbl_->setContextMenuPolicy(Qt::CustomContextMenu);
connect(connected_to_lbl_, &ClickableLabel::MouseClicked, this, &NodeParamViewConnectedLabel::ConnectionClicked);
connect(connected_to_lbl_, &ClickableLabel::customContextMenuRequested, this, &NodeParamViewConnectedLabel::ShowLabelContextMenu);
label_layout->addWidget(connected_to_lbl_);
label_layout->addStretch();
// Set up "link" font
QFont link_font = connected_to_lbl_->font();
link_font.setUnderline(true);
connected_to_lbl_->setForegroundRole(QPalette::Link);
connected_to_lbl_->setFont(link_font);
if (input_.IsConnected()) {
InputConnected(input_.GetConnectedOutput(), input_);
} else {
InputDisconnected(nullptr, input_);
}
connect(input_.node(), &Node::InputConnected, this, &NodeParamViewConnectedLabel::InputConnected);
connect(input_.node(), &Node::InputDisconnected, this, &NodeParamViewConnectedLabel::InputDisconnected);
// Creating the tree is expensive, hold off until the user specifically requests it
value_tree_ = nullptr;
connect(collapse_btn, &CollapseButton::toggled, this, &NodeParamViewConnectedLabel::SetValueTreeVisible);
}
void NodeParamViewConnectedLabel::SetViewerNode(ViewerOutput *viewer)
{
if (viewer_) {
disconnect(viewer_, &ViewerOutput::PlayheadChanged, this, &NodeParamViewConnectedLabel::UpdateValueTree);
}
viewer_ = viewer;
if (viewer_) {
connect(viewer_, &ViewerOutput::PlayheadChanged, this, &NodeParamViewConnectedLabel::UpdateValueTree);
UpdateValueTree();
}
}
void NodeParamViewConnectedLabel::CreateTree()
{
// Set up table area
value_tree_ = new NodeValueTree(this);
layout()->addWidget(value_tree_);
}
void NodeParamViewConnectedLabel::InputConnected(Node *output, const NodeInput& input)
{
if (input_ != input) {
return;
}
connected_node_ = output;
UpdateLabel();
}
void NodeParamViewConnectedLabel::InputDisconnected(Node *output, const NodeInput &input)
{
if (input_ != input) {
return;
}
Q_UNUSED(output)
connected_node_ = nullptr;
UpdateLabel();
}
void NodeParamViewConnectedLabel::ShowLabelContextMenu()
{
Menu m(this);
QAction* disconnect_action = m.addAction(tr("Disconnect"));
connect(disconnect_action, &QAction::triggered, this, [this](){
Core::instance()->undo_stack()->push(new NodeEdgeRemoveCommand(connected_node_, input_), Node::GetDisconnectCommandString(connected_node_, input_));
});
m.exec(QCursor::pos());
}
void NodeParamViewConnectedLabel::ConnectionClicked()
{
if (connected_node_) {
emit RequestSelectNode(connected_node_);
}
}
void NodeParamViewConnectedLabel::UpdateLabel()
{
QString s;
if (connected_node_) {
s = connected_node_->Name();
} else {
s = tr("Nothing");
}
connected_to_lbl_->setText(s);
}
void NodeParamViewConnectedLabel::UpdateValueTree()
{
if (value_tree_ && viewer_ && value_tree_->isVisible()) {
value_tree_->SetNode(input_, viewer_->GetPlayhead());
}
}
void NodeParamViewConnectedLabel::SetValueTreeVisible(bool e)
{
if (value_tree_) {
value_tree_->setVisible(e);
}
if (e) {
if (!value_tree_) {
CreateTree();
value_tree_->setVisible(true);
}
UpdateValueTree();
}
}
}
| 5,172
|
C++
|
.cpp
| 146
| 32.431507
| 152
| 0.750753
|
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
|
18,938
|
nodeparamviewtextedit.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewtextedit.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 "nodeparamviewtextedit.h"
#include <QHBoxLayout>
#include "dialog/text/text.h"
#include "ui/icons/icons.h"
namespace olive {
NodeParamViewTextEdit::NodeParamViewTextEdit(QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
line_edit_ = new QPlainTextEdit();
line_edit_->setUndoRedoEnabled(true);
connect(line_edit_, &QPlainTextEdit::textChanged, this, &NodeParamViewTextEdit::InnerWidgetTextChanged);
layout->addWidget(line_edit_);
edit_btn_ = new QPushButton();
edit_btn_->setIcon(icon::ToolEdit);
edit_btn_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding);
layout->addWidget(edit_btn_);
connect(edit_btn_, &QPushButton::clicked, this, &NodeParamViewTextEdit::ShowTextDialog);
edit_in_viewer_btn_ = new QPushButton(tr("Edit In Viewer"));
edit_in_viewer_btn_->setIcon(icon::Pencil);
layout->addWidget(edit_in_viewer_btn_);
connect(edit_in_viewer_btn_, &QPushButton::clicked, this, &NodeParamViewTextEdit::RequestEditInViewer);
SetEditInViewerOnlyMode(false);
}
void NodeParamViewTextEdit::SetEditInViewerOnlyMode(bool on)
{
line_edit_->setVisible(!on);
edit_btn_->setVisible(!on);
edit_in_viewer_btn_->setVisible(on);
}
void NodeParamViewTextEdit::ShowTextDialog()
{
TextDialog d(this->text(), this);
if (d.exec() == QDialog::Accepted) {
QString s = d.text();
line_edit_->setPlainText(s);
emit textEdited(s);
}
}
void NodeParamViewTextEdit::InnerWidgetTextChanged()
{
emit textEdited(this->text());
}
}
| 2,278
|
C++
|
.cpp
| 59
| 35.864407
| 106
| 0.759091
|
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
|
18,939
|
nodeparamviewdockarea.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewdockarea.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 "nodeparamviewdockarea.h"
#include <QDockWidget>
namespace olive {
NodeParamViewDockArea::NodeParamViewDockArea(QWidget *parent) :
QMainWindow(parent)
{
// Disable dock widgets from tabbing and disable glitchy animations
setDockOptions(static_cast<QMainWindow::DockOption>(0));
// HACK: Hide the main window separators (unfortunately the cursors still appear)
setStyleSheet(QStringLiteral("QMainWindow::separator {background: rgba(0, 0, 0, 0)}"));
}
QMenu *NodeParamViewDockArea::createPopupMenu()
{
return nullptr;
}
void NodeParamViewDockArea::AddItem(QDockWidget *item)
{
item->setAllowedAreas(Qt::LeftDockWidgetArea);
item->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable);
addDockWidget(Qt::LeftDockWidgetArea, item);
}
}
| 1,502
|
C++
|
.cpp
| 36
| 39.194444
| 89
| 0.790089
|
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
|
18,940
|
nodeparamviewkeyframecontrol.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewkeyframecontrol.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 "nodeparamviewkeyframecontrol.h"
#include <QHBoxLayout>
#include <QMessageBox>
#include "core.h"
#include "node/nodeundo.h"
#include "ui/icons/icons.h"
namespace olive {
NodeParamViewKeyframeControl::NodeParamViewKeyframeControl(bool right_align, QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
if (right_align) {
// Automatically right aligns all buttons
layout->addStretch();
}
prev_key_btn_ = CreateNewToolButton(icon::TriLeft);
prev_key_btn_->setIconSize(prev_key_btn_->iconSize() / 2);
layout->addWidget(prev_key_btn_);
toggle_key_btn_ = CreateNewToolButton(icon::Diamond);
toggle_key_btn_->setCheckable(true);
toggle_key_btn_->setIconSize(toggle_key_btn_->iconSize() / 2);
layout->addWidget(toggle_key_btn_);
next_key_btn_ = CreateNewToolButton(icon::TriRight);
next_key_btn_->setIconSize(next_key_btn_->iconSize() / 2);
layout->addWidget(next_key_btn_);
enable_key_btn_ = CreateNewToolButton(icon::Clock);
enable_key_btn_->setCheckable(true);
enable_key_btn_->setIconSize(enable_key_btn_->iconSize() / 4 * 3);
layout->addWidget(enable_key_btn_);
connect(prev_key_btn_, &QPushButton::clicked, this, &NodeParamViewKeyframeControl::GoToPreviousKey);
connect(next_key_btn_, &QPushButton::clicked, this, &NodeParamViewKeyframeControl::GoToNextKey);
connect(toggle_key_btn_, &QPushButton::clicked, this, &NodeParamViewKeyframeControl::ToggleKeyframe);
connect(enable_key_btn_, &QPushButton::toggled, this, &NodeParamViewKeyframeControl::ShowButtonsFromKeyframeEnable);
connect(enable_key_btn_, &QPushButton::clicked, this, &NodeParamViewKeyframeControl::KeyframeEnableBtnClicked);
// Set defaults
SetInput(NodeInput());
ShowButtonsFromKeyframeEnable(false);
}
void NodeParamViewKeyframeControl::SetInput(const NodeInput& input)
{
if (input_.IsValid()) {
disconnect(input_.node(), &Node::KeyframeEnableChanged, this, &NodeParamViewKeyframeControl::KeyframeEnableChanged);
disconnect(input_.node(), &Node::KeyframeAdded, this, &NodeParamViewKeyframeControl::UpdateState);
disconnect(input_.node(), &Node::KeyframeRemoved, this, &NodeParamViewKeyframeControl::UpdateState);
disconnect(input_.node(), &Node::KeyframeTimeChanged, this, &NodeParamViewKeyframeControl::UpdateState);
}
input_ = input;
SetButtonsEnabled(input_.IsValid());
// Pick up keyframing value
enable_key_btn_->setChecked(input_.IsValid() && input_.IsKeyframing());
// Update buttons
UpdateState();
if (input_.IsValid()) {
connect(input_.node(), &Node::KeyframeEnableChanged, this, &NodeParamViewKeyframeControl::KeyframeEnableChanged);
connect(input_.node(), &Node::KeyframeAdded, this, &NodeParamViewKeyframeControl::UpdateState);
connect(input_.node(), &Node::KeyframeRemoved, this, &NodeParamViewKeyframeControl::UpdateState);
connect(input_.node(), &Node::KeyframeTimeChanged, this, &NodeParamViewKeyframeControl::UpdateState);
}
}
void NodeParamViewKeyframeControl::TimeTargetDisconnectEvent(ViewerOutput *v)
{
disconnect(v, &ViewerOutput::PlayheadChanged, this, &NodeParamViewKeyframeControl::UpdateState);
}
void NodeParamViewKeyframeControl::TimeTargetConnectEvent(ViewerOutput *v)
{
connect(v, &ViewerOutput::PlayheadChanged, this, &NodeParamViewKeyframeControl::UpdateState);
UpdateState();
}
QPushButton *NodeParamViewKeyframeControl::CreateNewToolButton(const QIcon& icon) const
{
QPushButton* btn = new QPushButton();
btn->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
btn->setIcon(icon);
return btn;
}
void NodeParamViewKeyframeControl::SetButtonsEnabled(bool e)
{
prev_key_btn_->setEnabled(e);
toggle_key_btn_->setEnabled(e);
next_key_btn_->setEnabled(e);
enable_key_btn_->setEnabled(e);
}
rational NodeParamViewKeyframeControl::GetCurrentTimeAsNodeTime() const
{
return GetAdjustedTime(GetTimeTarget(), input_.node(), GetTimeTarget()->GetPlayhead(), Node::kTransformTowardsInput);
}
rational NodeParamViewKeyframeControl::ConvertToViewerTime(const rational &r) const
{
return GetAdjustedTime(input_.node(), GetTimeTarget(), r, Node::kTransformTowardsOutput);
}
void NodeParamViewKeyframeControl::ShowButtonsFromKeyframeEnable(bool e)
{
prev_key_btn_->setVisible(e);
toggle_key_btn_->setVisible(e);
next_key_btn_->setVisible(e);
}
void NodeParamViewKeyframeControl::ToggleKeyframe(bool e)
{
rational node_time = GetCurrentTimeAsNodeTime();
QVector<NodeKeyframe*> keys = input_.node()->GetKeyframesAtTime(input_, node_time);
MultiUndoCommand* command = new MultiUndoCommand();
int nb_tracks = input_.node()->GetNumberOfKeyframeTracks(input_);
if (e && keys.isEmpty()) {
// Add a keyframe here (one for each track)
for (int i=0;i<nb_tracks;i++) {
NodeKeyframe* key = new NodeKeyframe(node_time,
input_.node()->GetSplitValueAtTimeOnTrack(input_, node_time, i),
input_.node()->GetBestKeyframeTypeForTimeOnTrack(input_, node_time, i),
i,
input_.element(),
input_.input());
command->add_child(new NodeParamInsertKeyframeCommand(input_.node(), key));
}
} else if (!e && !keys.isEmpty()) {
// Remove all keyframes at this time
foreach (NodeKeyframe* key, keys) {
command->add_child(new NodeParamRemoveKeyframeCommand(key));
if (input_.node()->GetKeyframeTracks(input_).size() == 1) {
// If this was the last keyframe on this track, set the standard value to the value at this time too
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(input_, key->track()),
input_.node()->GetSplitValueAtTimeOnTrack(input_, node_time, key->track())));
}
}
}
Core::instance()->undo_stack()->push(command, tr("Toggled Keyframe"));
}
void NodeParamViewKeyframeControl::UpdateState()
{
if (!input_.IsValid() || !input_.IsKeyframing() || !GetTimeTarget()) {
return;
}
NodeKeyframe* earliest_key = input_.node()->GetEarliestKeyframe(input_);
NodeKeyframe* latest_key = input_.node()->GetLatestKeyframe(input_);
rational node_time = GetCurrentTimeAsNodeTime();
prev_key_btn_->setEnabled(earliest_key && node_time > earliest_key->time());
next_key_btn_->setEnabled(latest_key && node_time < latest_key->time());
toggle_key_btn_->setChecked(input_.node()->HasKeyframeAtTime(input_, node_time));
}
void NodeParamViewKeyframeControl::GoToPreviousKey()
{
rational node_time = GetCurrentTimeAsNodeTime();
NodeKeyframe* previous_key = input_.node()->GetClosestKeyframeBeforeTime(input_, node_time);
if (previous_key && GetTimeTarget()) {
rational key_time = ConvertToViewerTime(previous_key->time());
GetTimeTarget()->SetPlayhead(key_time);
}
}
void NodeParamViewKeyframeControl::GoToNextKey()
{
rational node_time = GetCurrentTimeAsNodeTime();
NodeKeyframe* next_key = input_.node()->GetClosestKeyframeAfterTime(input_, node_time);
if (next_key && GetTimeTarget()) {
rational key_time = ConvertToViewerTime(next_key->time());
GetTimeTarget()->SetPlayhead(key_time);
}
}
void NodeParamViewKeyframeControl::KeyframeEnableBtnClicked(bool e)
{
if (e == input_.IsKeyframing()) {
// No-op
return;
}
MultiUndoCommand* command = new MultiUndoCommand();
QString command_name;
if (e) {
// Enable keyframing
command->add_child(new NodeParamSetKeyframingCommand(input_, true));
// Create one keyframe across all tracks here
const QVector<QVariant>& key_vals = input_.node()->GetSplitStandardValue(input_);
for (int i=0;i<key_vals.size();i++) {
NodeKeyframe* key = new NodeKeyframe(GetCurrentTimeAsNodeTime(),
key_vals.at(i),
NodeKeyframe::kDefaultType,
i,
input_.element(),
input_.input());
command->add_child(new NodeParamInsertKeyframeCommand(input_.node(), key));
}
command_name = tr("Enabled Keyframing On %1 - %2").arg(input_.node()->GetLabelAndName(), input_.GetInputName());
} else {
// Confirm the user wants to clear all keyframes
if (QMessageBox::warning(this,
tr("Warning"),
tr("Are you sure you want to disable keyframing on this value? This will clear all existing keyframes."),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
// Store value at this time, we'll set this as the persistent value later
const QVector<QVariant>& stored_vals = input_.node()->GetSplitValueAtTime(input_, GetCurrentTimeAsNodeTime());
// Delete all keyframes
foreach (const NodeKeyframeTrack& track, input_.node()->GetKeyframeTracks(input_)) {
for (int i=track.size()-1;i>=0;i--) {
command->add_child(new NodeParamRemoveKeyframeCommand(track.at(i)));
}
}
// Update standard value
for (int i=0;i<stored_vals.size();i++) {
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(input_, i), stored_vals.at(i)));
}
// Disable keyframing
command->add_child(new NodeParamSetKeyframingCommand(input_, false));
command_name = tr("Disabled Keyframing On %1 - %2").arg(input_.node()->GetLabelAndName(), input_.GetInputName());
} else {
// Disable action has effectively been ignored
enable_key_btn_->setChecked(true);
}
}
Core::instance()->undo_stack()->push(command, command_name);
}
void NodeParamViewKeyframeControl::KeyframeEnableChanged(const NodeInput &input, bool e)
{
if (input_ == input) {
enable_key_btn_->setChecked(e);
}
}
}
| 10,778
|
C++
|
.cpp
| 230
| 40.83913
| 141
| 0.701164
|
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
|
18,941
|
nodeparamviewitem.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewitem.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 "nodeparamviewitem.h"
#include <QCheckBox>
#include <QDebug>
#include "common/qtutils.h"
#include "core.h"
#include "dialog/speedduration/speeddurationdialog.h"
#include "node/group/group.h"
#include "node/nodeundo.h"
#include "node/project/sequence/sequence.h"
namespace olive {
const int NodeParamViewItemBody::kKeyControlColumn = 10;
const int NodeParamViewItemBody::kArrayInsertColumn = kKeyControlColumn-1;
const int NodeParamViewItemBody::kArrayRemoveColumn = kArrayInsertColumn-1;
const int NodeParamViewItemBody::kExtraButtonColumn = kKeyControlColumn-1;
const int NodeParamViewItemBody::kOptionalCheckBox = 0;
const int NodeParamViewItemBody::kArrayCollapseBtnColumn = 1;
const int NodeParamViewItemBody::kLabelColumn = 2;
const int NodeParamViewItemBody::kWidgetStartColumn = 3;
const int NodeParamViewItemBody::kMaxWidgetColumn = kArrayRemoveColumn;
#define super NodeParamViewItemBase
NodeParamViewItem::NodeParamViewItem(Node *node, NodeParamViewCheckBoxBehavior create_checkboxes, QWidget *parent) :
super(parent),
body_(nullptr),
node_(node),
create_checkboxes_(create_checkboxes),
ctx_(nullptr),
time_target_(nullptr)
{
node_->Retranslate();
// Create and add contents widget
RecreateBody();
connect(node_, &Node::LabelChanged, this, &NodeParamViewItem::Retranslate);
connect(node_, &Node::InputArraySizeChanged, this, &NodeParamViewItem::InputArraySizeChanged);
// FIXME: Implemented to pick up when an input is set to hidden or not - DEFINITELY not a fast
// way of doing this, but "fine" for now.
connect(node_, &Node::InputFlagsChanged, this, &NodeParamViewItem::RecreateBody);
setBackgroundRole(QPalette::Window);
// Connect title bar enabled checkbox
//title_bar()->SetEnabledCheckBoxVisible(true);
//title_bar()->SetEnabledCheckBoxChecked(node_->IsEnabled());
//connect(title_bar(), &NodeParamViewItemTitleBar::EnabledCheckBoxClicked, node_, &Node::SetEnabled);
Retranslate();
}
void NodeParamViewItem::Retranslate()
{
node_->Retranslate();
title_bar()->SetText(GetTitleBarTextFromNode(node_));
body_->Retranslate();
}
void NodeParamViewItem::RecreateBody()
{
if (body_) {
body_->setParent(nullptr);
body_->deleteLater();
}
body_ = new NodeParamViewItemBody(node_, create_checkboxes_, this);
connect(body_, &NodeParamViewItemBody::RequestSelectNode, this, &NodeParamViewItem::RequestSelectNode);
connect(body_, &NodeParamViewItemBody::ArrayExpandedChanged, this, &NodeParamViewItem::ArrayExpandedChanged);
connect(body_, &NodeParamViewItemBody::InputCheckedChanged, this, &NodeParamViewItem::InputCheckedChanged);
connect(body_, &NodeParamViewItemBody::RequestEditTextInViewer, this, &NodeParamViewItem::RequestEditTextInViewer);
body_->Retranslate();
body_->SetTimebase(timebase_);
body_->SetTimeTarget(time_target_);
SetBody(body_);
}
int NodeParamViewItem::GetElementY(const NodeInput &c) const
{
if (IsExpanded()) {
return body_->GetElementY(c);
} else {
// Not expanded, put keyframes at the titlebar Y
return mapToGlobal(title_bar()->rect().center()).y();
}
}
void NodeParamViewItem::SetInputChecked(const NodeInput &input, bool e)
{
body_->SetInputChecked(input, e);
}
NodeParamViewItemBody::NodeParamViewItemBody(Node* node, NodeParamViewCheckBoxBehavior create_checkboxes, QWidget *parent) :
QWidget(parent),
node_(node),
time_target_(nullptr),
create_checkboxes_(create_checkboxes)
{
QGridLayout* root_layout = new QGridLayout(this);
int insert_row = 0;
QVector<Node*> connected_signals;
// Create widgets all root level components
foreach (QString input, node->inputs()) {
Node *n = node;
NodeInput resolved = NodeGroup::ResolveInput(NodeInput(n, input));
if (!connected_signals.contains(resolved.node())) {
connect(resolved.node(), &Node::InputArraySizeChanged, this, &NodeParamViewItemBody::InputArraySizeChanged);
connect(resolved.node(), &Node::InputConnected, this, &NodeParamViewItemBody::EdgeChanged);
connect(resolved.node(), &Node::InputDisconnected, this, &NodeParamViewItemBody::EdgeChanged);
connected_signals.append(resolved.node());
}
input_group_lookup_.insert({resolved.node(), resolved.input()}, {n, input});
if (!(n->GetInputFlags(input) & kInputFlagHidden)) {
CreateWidgets(root_layout, n, input, -1, insert_row);
insert_row++;
if (n->InputIsArray(input)) {
// Insert here
QWidget* array_widget = new QWidget(this);
QGridLayout* array_layout = new QGridLayout(array_widget);
array_layout->setContentsMargins(QtUtils::QFontMetricsWidth(fontMetrics(), QStringLiteral(" ")), 0, 0, 0);
root_layout->addWidget(array_widget, insert_row, 1, 1, 10);
// Start with zero elements for efficiency. We will make the widgets for them if the user
// requests the array UI to be expanded
int arr_sz = 0;
// Add one last add button for appending to the array
NodeParamViewArrayButton* append_btn = new NodeParamViewArrayButton(NodeParamViewArrayButton::kAdd, this);
connect(append_btn, &NodeParamViewArrayButton::clicked, this, &NodeParamViewItemBody::ArrayAppendClicked);
array_layout->addWidget(append_btn, arr_sz, kArrayInsertColumn);
array_widget->setVisible(false);
array_ui_.insert({n, input}, {array_widget, arr_sz, append_btn});
insert_row++;
}
}
}
}
void NodeParamViewItemBody::CreateWidgets(QGridLayout* layout, Node *node, const QString &input, int element, int row)
{
NodeInput input_ref(node, input, element);
InputUI ui_objects;
// Store layout and row
ui_objects.layout = layout;
ui_objects.row = row;
// Create optional checkbox if requested
if (create_checkboxes_) {
ui_objects.optional_checkbox = new QCheckBox(this);
connect(ui_objects.optional_checkbox, &QCheckBox::clicked, this, &NodeParamViewItemBody::OptionalCheckBoxClicked);
layout->addWidget(ui_objects.optional_checkbox, row, kOptionalCheckBox);
if (create_checkboxes_ == kCheckBoxesOnNonConnected && input_ref.IsConnected()) {
ui_objects.optional_checkbox->setVisible(false);
}
}
// Add descriptor label
ui_objects.main_label = new QLabel(this);
// Create input label
layout->addWidget(ui_objects.main_label, row, kLabelColumn);
if (node->InputIsArray(input)) {
if (element == -1) {
// Create a collapse toggle for expanding/collapsing the array
CollapseButton* array_collapse_btn = new CollapseButton(this);
// Default to collapsed
array_collapse_btn->setChecked(false);
// Add collapse button to layout
layout->addWidget(array_collapse_btn, row, kArrayCollapseBtnColumn);
// Connect signal to show/hide array params when toggled
connect(array_collapse_btn, &CollapseButton::toggled, this, &NodeParamViewItemBody::ArrayCollapseBtnPressed);
array_collapse_buttons_.insert({node, input}, array_collapse_btn);
} else {
NodeParamViewArrayButton* insert_element_btn = new NodeParamViewArrayButton(NodeParamViewArrayButton::kAdd, this);
NodeParamViewArrayButton* remove_element_btn = new NodeParamViewArrayButton(NodeParamViewArrayButton::kRemove, this);
layout->addWidget(insert_element_btn, row, kArrayInsertColumn);
layout->addWidget(remove_element_btn, row, kArrayRemoveColumn);
ui_objects.array_insert_btn = insert_element_btn;
ui_objects.array_remove_btn = remove_element_btn;
connect(insert_element_btn, &NodeParamViewArrayButton::clicked, this, &NodeParamViewItemBody::ArrayInsertClicked);
connect(remove_element_btn, &NodeParamViewArrayButton::clicked, this, &NodeParamViewItemBody::ArrayRemoveClicked);
}
}
// Create a widget/input bridge for this input
ui_objects.widget_bridge = new NodeParamViewWidgetBridge(NodeInput(node, input, element), this);
connect(ui_objects.widget_bridge, &NodeParamViewWidgetBridge::WidgetsRecreated, this, &NodeParamViewItemBody::ReplaceWidgets);
connect(ui_objects.widget_bridge, &NodeParamViewWidgetBridge::ArrayWidgetDoubleClicked, this, &NodeParamViewItemBody::ToggleArrayExpanded);
connect(ui_objects.widget_bridge, &NodeParamViewWidgetBridge::RequestEditTextInViewer, this, &NodeParamViewItemBody::RequestEditTextInViewer);
// Place widgets into layout
PlaceWidgetsFromBridge(layout, ui_objects.widget_bridge, row);
// In case this input is a group, resolve that actual input to use for connected labels
NodeInput resolved = NodeGroup::ResolveInput(input_ref);
if (node->IsInputConnectable(input)) {
// Create clickable label used when an input is connected
ui_objects.connected_label = new NodeParamViewConnectedLabel(resolved, this);
connect(ui_objects.connected_label, &NodeParamViewConnectedLabel::RequestSelectNode, this, &NodeParamViewItemBody::RequestSelectNode);
layout->addWidget(ui_objects.connected_label, row, kWidgetStartColumn, 1, kKeyControlColumn - kWidgetStartColumn);
}
// Add keyframe control to this layout if parameter is keyframable
if (node->IsInputKeyframable(input)) {
ui_objects.key_control = new NodeParamViewKeyframeControl(this);
ui_objects.key_control->SetInput(resolved);
layout->addWidget(ui_objects.key_control, row, kKeyControlColumn);
}
input_ui_map_.insert(input_ref, ui_objects);
if (node->IsInputConnectable(input)) {
UpdateUIForEdgeConnection(input_ref);
}
SetTimeTargetOnInputUI(ui_objects);
SetTimebaseOnInputUI(ui_objects);
}
void NodeParamViewItemBody::SetTimeTarget(ViewerOutput *target)
{
time_target_ = target;
foreach (const InputUI& ui_obj, input_ui_map_) {
SetTimeTargetOnInputUI(ui_obj);
}
}
void NodeParamViewItemBody::SetTimeTargetOnInputUI(const InputUI &ui_obj)
{
// Only keyframable inputs have a key control widget
if (ui_obj.key_control) {
ui_obj.key_control->SetTimeTarget(time_target_);
}
if (ui_obj.connected_label) {
ui_obj.connected_label->SetViewerNode(time_target_);
}
ui_obj.widget_bridge->SetTimeTarget(time_target_);
}
void NodeParamViewItemBody::Retranslate()
{
for (auto i=input_ui_map_.begin(); i!=input_ui_map_.end(); i++) {
const NodeInput& ic = i.key();
if (ic.IsArray() && ic.element() >= 0) {
// Make the label the array index
i.value().main_label->setText(tr("%1:").arg(ic.element() + ic.GetProperty(QStringLiteral("arraystart")).toInt()));
} else {
// Set to the input's name
i.value().main_label->setText(tr("%1:").arg(ic.name()));
}
}
}
int NodeParamViewItemBody::GetElementY(NodeInput c) const
{
if (c.IsArray() && !array_ui_.value(c.input_pair()).widget->isVisible()) {
// Array is collapsed, so we'll return the Y of its root
c.set_element(-1);
}
//c = NodeGroup::ResolveInput(c);
// Find its row in the parameters
QLabel* lbl = input_ui_map_.value(c).main_label;
// Find label's Y position
QPoint lbl_center = lbl->rect().center();
// Find global position
lbl_center = lbl->mapToGlobal(lbl_center);
// Return Y
return lbl_center.y();
}
void NodeParamViewItemBody::EdgeChanged(Node *output, const NodeInput& input)
{
Q_UNUSED(output)
const NodeInputPair &pair = input_group_lookup_.value({input.node(), input.input()});
NodeInput resolved(pair.node, pair.input, input.element());
UpdateUIForEdgeConnection(resolved);
}
void NodeParamViewItemBody::UpdateUIForEdgeConnection(const NodeInput& input)
{
// Show/hide bridge widgets
if (input_ui_map_.contains(input)) {
const InputUI& ui_objects = input_ui_map_[input];
bool is_connected = NodeGroup::ResolveInput(input).IsConnected();
foreach (QWidget* w, ui_objects.widget_bridge->widgets()) {
w->setVisible(!is_connected);
}
// Show/hide connection label
ui_objects.connected_label->setVisible(is_connected);
if (ui_objects.key_control) {
ui_objects.key_control->setVisible(!is_connected);
}
// Show/hide optional checkbox if requested
if (create_checkboxes_ == kCheckBoxesOnNonConnected) {
ui_objects.optional_checkbox->setVisible(!is_connected);
}
}
}
void NodeParamViewItemBody::PlaceWidgetsFromBridge(QGridLayout* layout, NodeParamViewWidgetBridge *bridge, int row)
{
// Add widgets for this parameter to the layout
for (int i=0; i<bridge->widgets().size(); i++) {
QWidget* w = bridge->widgets().at(i);
int col = i+kWidgetStartColumn;
int colspan;
if (i == bridge->widgets().size()-1) {
// Span this widget among remaining columns
colspan = kMaxWidgetColumn - col;
} else {
colspan = 1;
}
layout->addWidget(w, row, col, 1, colspan);
}
}
void NodeParamViewItemBody::InputArraySizeChangedInternal(Node *node, const QString &input, int size)
{
NodeInputPair nip = {node, input};
if (!array_ui_.contains(nip)) {
return;
}
ArrayUI& array_ui = array_ui_[nip];
if (size != array_ui.count) {
QGridLayout* grid = static_cast<QGridLayout*>(array_ui.widget->layout());
if (array_ui.count < size) {
// Our UI count is smaller than the size, create more
grid->addWidget(array_ui.append_btn, size, kArrayInsertColumn);
for (int i=array_ui.count; i<size; i++) {
CreateWidgets(grid, node, input, i, i);
}
} else {
for (int i=array_ui.count-1; i>=size; i--) {
// Our UI count is larger than the size, delete
InputUI input_ui = input_ui_map_.take({node, input, i});
delete input_ui.main_label;
qDeleteAll(input_ui.widget_bridge->widgets());
delete input_ui.widget_bridge;
delete input_ui.connected_label;
delete input_ui.key_control;
delete input_ui.array_insert_btn;
delete input_ui.array_remove_btn;
}
grid->addWidget(array_ui.append_btn, size, kArrayInsertColumn);
}
array_ui.count = size;
Retranslate();
}
}
void NodeParamViewItemBody::ArrayCollapseBtnPressed(bool checked)
{
const NodeInputPair& input = array_collapse_buttons_.key(static_cast<CollapseButton*>(sender()));
array_ui_.value(input).widget->setVisible(checked);
if (checked) {
// Ensure widgets are created (the signal will be ignored if they are)
NodeInput resolved = NodeGroup::ResolveInput(NodeInput(input.node, input.input));
InputArraySizeChangedInternal(input.node, input.input, resolved.GetArraySize());
}
emit ArrayExpandedChanged(checked);
}
void NodeParamViewItemBody::InputArraySizeChanged(const QString& input, int old_sz, int size)
{
Q_UNUSED(old_sz)
NodeInputPair nip = input_group_lookup_.value({static_cast<Node*>(sender()), input});
InputArraySizeChangedInternal(nip.node, nip.input, size);
}
void NodeParamViewItemBody::ArrayAppendClicked()
{
for (auto it=array_ui_.cbegin(); it!=array_ui_.cend(); it++) {
if (it.value().append_btn == sender()) {
NodeInput real_input = NodeGroup::ResolveInput(NodeInput(it.key().node, it.key().input));
Core::instance()->undo_stack()->push(new NodeArrayInsertCommand(real_input.node(), real_input.input(), real_input.GetArraySize()),
tr("Appended Array Element In %1 - %2").arg(real_input.node()->GetLabelAndName(), real_input.GetInputName()));
break;
}
}
}
void NodeParamViewItemBody::ArrayInsertClicked()
{
for (auto it=input_ui_map_.cbegin(); it!=input_ui_map_.cend(); it++) {
if (it.value().array_insert_btn == sender()) {
// Found our input and element
NodeInput ic = NodeGroup::ResolveInput(it.key());
Core::instance()->undo_stack()->push(new NodeArrayInsertCommand(ic.node(), ic.input(), ic.element()),
tr("Inserted Array Element In %1 - %2").arg(ic.node()->GetLabelAndName(), ic.GetInputName()));
break;
}
}
}
void NodeParamViewItemBody::ArrayRemoveClicked()
{
for (auto it=input_ui_map_.cbegin(); it!=input_ui_map_.cend(); it++) {
if (it.value().array_remove_btn == sender()) {
// Found our input and element
NodeInput ic = NodeGroup::ResolveInput(it.key());
Core::instance()->undo_stack()->push(new NodeArrayRemoveCommand(ic.node(), ic.input(), ic.element()),
tr("Removed Array Element In %1 - %2").arg(ic.node()->GetLabelAndName(), ic.GetInputName()));
break;
}
}
}
void NodeParamViewItemBody::ToggleArrayExpanded()
{
NodeParamViewWidgetBridge* bridge = static_cast<NodeParamViewWidgetBridge*>(sender());
for (auto it=input_ui_map_.cbegin(); it!=input_ui_map_.cend(); it++) {
if (it.value().widget_bridge == bridge) {
CollapseButton* b = array_collapse_buttons_.value(it.key().input_pair());
b->setChecked(!b->isChecked());
return;
}
}
}
void NodeParamViewItemBody::SetTimebase(const rational& timebase)
{
timebase_ = timebase;
foreach (const InputUI& ui_obj, input_ui_map_) {
SetTimebaseOnInputUI(ui_obj);
}
}
void NodeParamViewItemBody::SetTimebaseOnInputUI(const InputUI& ui_obj)
{
ui_obj.widget_bridge->SetTimebase(timebase_);
}
void NodeParamViewItemBody::SetInputChecked(const NodeInput &input, bool e)
{
if (input_ui_map_.contains(input)) {
QCheckBox *cb = input_ui_map_.value(input).optional_checkbox;
if (cb) {
cb->setChecked(e);
}
}
}
void NodeParamViewItemBody::ReplaceWidgets(const NodeInput &input)
{
InputUI ui = input_ui_map_.value(input);
PlaceWidgetsFromBridge(ui.layout, ui.widget_bridge, ui.row);
}
void NodeParamViewItemBody::ShowSpeedDurationDialogForNode()
{
// We should only get there if the node is a clip, determined by the dynamic_cast in CreateWidgets
SpeedDurationDialog sdd({static_cast<ClipBlock*>(node_)}, timebase_, this);
sdd.exec();
}
void NodeParamViewItemBody::OptionalCheckBoxClicked(bool e)
{
QCheckBox *cb = static_cast<QCheckBox*>(sender());
for (auto it=input_ui_map_.cbegin(); it!=input_ui_map_.cend(); it++) {
if (it.value().optional_checkbox == cb) {
emit InputCheckedChanged(it.key(), e);
break;
}
}
}
NodeParamViewItemBody::InputUI::InputUI() :
main_label(nullptr),
widget_bridge(nullptr),
connected_label(nullptr),
key_control(nullptr),
extra_btn(nullptr),
optional_checkbox(nullptr),
array_insert_btn(nullptr),
array_remove_btn(nullptr)
{
}
}
| 19,065
|
C++
|
.cpp
| 444
| 38.630631
| 153
| 0.725631
|
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
|
18,942
|
nodeparamviewwidgetbridge.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewwidgetbridge.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 "nodeparamviewwidgetbridge.h"
#include <QCheckBox>
#include <QFontComboBox>
#include <QVector2D>
#include <QVector3D>
#include <QVector4D>
#include "common/qtutils.h"
#include "core.h"
#include "node/group/group.h"
#include "node/node.h"
#include "node/nodeundo.h"
#include "node/project/sequence/sequence.h"
#include "nodeparamviewarraywidget.h"
#include "nodeparamviewtextedit.h"
#include "undo/undostack.h"
#include "widget/bezier/bezierwidget.h"
#include "widget/colorbutton/colorbutton.h"
#include "widget/filefield/filefield.h"
#include "widget/slider/floatslider.h"
#include "widget/slider/integerslider.h"
#include "widget/slider/rationalslider.h"
namespace olive {
NodeParamViewWidgetBridge::NodeParamViewWidgetBridge(NodeInput input, QObject *parent) :
QObject(parent)
{
do {
input_hierarchy_.append(input);
connect(input.node(), &Node::ValueChanged, this, &NodeParamViewWidgetBridge::InputValueChanged);
connect(input.node(), &Node::InputPropertyChanged, this, &NodeParamViewWidgetBridge::PropertyChanged);
connect(input.node(), &Node::InputDataTypeChanged, this, &NodeParamViewWidgetBridge::InputDataTypeChanged);
} while (NodeGroup::GetInner(&input));
CreateWidgets();
}
int GetSliderCount(NodeValue::Type type)
{
return NodeValue::get_number_of_keyframe_tracks(type);
}
void NodeParamViewWidgetBridge::CreateWidgets()
{
QWidget *parent = dynamic_cast<QWidget*>(this->parent());
if (GetInnerInput().IsArray() && GetInnerInput().element() == -1) {
NodeParamViewArrayWidget* w = new NodeParamViewArrayWidget(GetInnerInput().node(), GetInnerInput().input(), parent);
connect(w, &NodeParamViewArrayWidget::DoubleClicked, this, &NodeParamViewWidgetBridge::ArrayWidgetDoubleClicked);
widgets_.append(w);
} else {
// We assume the first data type is the "primary" type
NodeValue::Type t = GetDataType();
switch (t) {
// None of these inputs have applicable UI widgets
case NodeValue::kNone:
case NodeValue::kTexture:
case NodeValue::kMatrix:
case NodeValue::kSamples:
case NodeValue::kVideoParams:
case NodeValue::kAudioParams:
case NodeValue::kSubtitleParams:
case NodeValue::kBinary:
case NodeValue::kDataTypeCount:
break;
case NodeValue::kInt:
{
CreateSliders<IntegerSlider>(1, parent);
break;
}
case NodeValue::kRational:
{
CreateSliders<RationalSlider>(1, parent);
break;
}
case NodeValue::kFloat:
case NodeValue::kVec2:
case NodeValue::kVec3:
case NodeValue::kVec4:
{
CreateSliders<FloatSlider>(GetSliderCount(t), parent);
break;
}
case NodeValue::kCombo:
{
QComboBox* combobox = new QComboBox(parent);
QStringList items = GetInnerInput().GetComboBoxStrings();
foreach (const QString& s, items) {
combobox->addItem(s);
}
widgets_.append(combobox);
connect(combobox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
case NodeValue::kFile:
{
FileField* file_field = new FileField(parent);
widgets_.append(file_field);
connect(file_field, &FileField::FilenameChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
case NodeValue::kColor:
{
ColorButton* color_button = new ColorButton(GetInnerInput().node()->project()->color_manager(), parent);
widgets_.append(color_button);
connect(color_button, &ColorButton::ColorChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
case NodeValue::kText:
{
NodeParamViewTextEdit* line_edit = new NodeParamViewTextEdit(parent);
widgets_.append(line_edit);
connect(line_edit, &NodeParamViewTextEdit::textEdited, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(line_edit, &NodeParamViewTextEdit::RequestEditInViewer, this, &NodeParamViewWidgetBridge::RequestEditTextInViewer);
break;
}
case NodeValue::kBoolean:
{
QCheckBox* check_box = new QCheckBox(parent);
widgets_.append(check_box);
connect(check_box, &QCheckBox::clicked, this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
case NodeValue::kFont:
{
QFontComboBox* font_combobox = new QFontComboBox(parent);
widgets_.append(font_combobox);
connect(font_combobox, &QFontComboBox::currentFontChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
case NodeValue::kBezier:
{
BezierWidget *bezier = new BezierWidget(parent);
widgets_.append(bezier);
connect(bezier->x_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(bezier->y_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(bezier->cp1_x_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(bezier->cp1_y_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(bezier->cp2_x_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
connect(bezier->cp2_y_slider(), &FloatSlider::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
break;
}
}
// Check all properties
UpdateProperties();
UpdateWidgetValues();
// Install event filter to disable widgets picking up scroll events
foreach (QWidget* w, widgets_) {
w->installEventFilter(&scroll_filter_);
}
}
}
void NodeParamViewWidgetBridge::SetInputValue(const QVariant &value, int track)
{
MultiUndoCommand* command = new MultiUndoCommand();
SetInputValueInternal(value, track, command, true);
Core::instance()->undo_stack()->push(command, GetCommandName());
}
void NodeParamViewWidgetBridge::SetInputValueInternal(const QVariant &value, int track, MultiUndoCommand *command, bool insert_on_all_tracks_if_no_key)
{
Node::SetValueAtTime(GetInnerInput(), GetCurrentTimeAsNodeTime(), value, track, command, insert_on_all_tracks_if_no_key);
}
void NodeParamViewWidgetBridge::ProcessSlider(NumericSliderBase *slider, int slider_track, const QVariant &value)
{
if (slider->IsDragging()) {
// While we're dragging, we block the input's normal signalling and create our own
if (!dragger_.IsStarted()) {
rational node_time = GetCurrentTimeAsNodeTime();
dragger_.Start(NodeKeyframeTrackReference(GetInnerInput(), slider_track), node_time);
}
dragger_.Drag(value);
} else if (dragger_.IsStarted()) {
// We were dragging and just stopped
dragger_.Drag(value);
MultiUndoCommand *command = new MultiUndoCommand();
dragger_.End(command);
Core::instance()->undo_stack()->push(command, GetCommandName());
} else {
// No drag was involved, we can just push the value
SetInputValue(value, slider_track);
}
}
void NodeParamViewWidgetBridge::WidgetCallback()
{
switch (GetDataType()) {
// None of these inputs have applicable UI widgets
case NodeValue::kNone:
case NodeValue::kTexture:
case NodeValue::kMatrix:
case NodeValue::kSamples:
case NodeValue::kVideoParams:
case NodeValue::kAudioParams:
case NodeValue::kSubtitleParams:
case NodeValue::kBinary:
case NodeValue::kDataTypeCount:
break;
case NodeValue::kInt:
{
// Widget is a IntegerSlider
IntegerSlider* slider = static_cast<IntegerSlider*>(sender());
ProcessSlider(slider, QVariant::fromValue(slider->GetValue()));
break;
}
case NodeValue::kFloat:
{
// Widget is a FloatSlider
FloatSlider* slider = static_cast<FloatSlider*>(sender());
ProcessSlider(slider, slider->GetValue());
break;
}
case NodeValue::kRational:
{
// Widget is a RationalSlider
RationalSlider* slider = static_cast<RationalSlider*>(sender());
ProcessSlider(slider, QVariant::fromValue(slider->GetValue()));
break;
}
case NodeValue::kVec2:
{
// Widget is a FloatSlider
FloatSlider* slider = static_cast<FloatSlider*>(sender());
ProcessSlider(slider, slider->GetValue());
break;
}
case NodeValue::kVec3:
{
// Widget is a FloatSlider
FloatSlider* slider = static_cast<FloatSlider*>(sender());
ProcessSlider(slider, slider->GetValue());
break;
}
case NodeValue::kVec4:
{
// Widget is a FloatSlider
FloatSlider* slider = static_cast<FloatSlider*>(sender());
ProcessSlider(slider, slider->GetValue());
break;
}
case NodeValue::kFile:
{
SetInputValue(static_cast<FileField*>(sender())->GetFilename(), 0);
break;
}
case NodeValue::kColor:
{
// Sender is a ColorButton
ManagedColor c = static_cast<ColorButton*>(sender())->GetColor();
MultiUndoCommand* command = new MultiUndoCommand();
SetInputValueInternal(c.red(), 0, command, false);
SetInputValueInternal(c.green(), 1, command, false);
SetInputValueInternal(c.blue(), 2, command, false);
SetInputValueInternal(c.alpha(), 3, command, false);
Node* n = GetInnerInput().node();
n->blockSignals(true);
n->SetInputProperty(GetInnerInput().input(), QStringLiteral("col_input"), c.color_input());
n->SetInputProperty(GetInnerInput().input(), QStringLiteral("col_display"), c.color_output().display());
n->SetInputProperty(GetInnerInput().input(), QStringLiteral("col_view"), c.color_output().view());
n->SetInputProperty(GetInnerInput().input(), QStringLiteral("col_look"), c.color_output().look());
n->blockSignals(false);
Core::instance()->undo_stack()->push(command, GetCommandName());
break;
}
case NodeValue::kText:
{
// Sender is a NodeParamViewRichText
SetInputValue(static_cast<NodeParamViewTextEdit*>(sender())->text(), 0);
break;
}
case NodeValue::kBoolean:
{
// Widget is a QCheckBox
SetInputValue(static_cast<QCheckBox*>(sender())->isChecked(), 0);
break;
}
case NodeValue::kFont:
{
// Widget is a QFontComboBox
SetInputValue(static_cast<QFontComboBox*>(sender())->currentFont().family(), 0);
break;
}
case NodeValue::kCombo:
{
// Widget is a QComboBox
QComboBox* cb = static_cast<QComboBox*>(widgets_.first());
int index = cb->currentIndex();
// Subtract any splitters up until this point
for (int i=index-1; i>=0; i--) {
if (cb->itemData(i, Qt::AccessibleDescriptionRole).toString() == QStringLiteral("separator")) {
index--;
}
}
SetInputValue(index, 0);
break;
}
case NodeValue::kBezier:
{
// Widget is a FloatSlider (child of BezierWidget)
BezierWidget *bw = static_cast<BezierWidget*>(widgets_.first());
FloatSlider *fs = static_cast<FloatSlider*>(sender());
int index = -1;
if (fs == bw->x_slider()) {
index = 0;
} else if (fs == bw->y_slider()) {
index = 1;
} else if (fs == bw->cp1_x_slider()) {
index = 2;
} else if (fs == bw->cp1_y_slider()) {
index = 3;
} else if (fs == bw->cp2_x_slider()) {
index = 4;
} else if (fs == bw->cp2_y_slider()) {
index = 5;
}
if (index != -1) {
ProcessSlider(fs, index, fs->GetValue());
}
break;
}
}
}
template <typename T>
void NodeParamViewWidgetBridge::CreateSliders(int count, QWidget *parent)
{
for (int i=0;i<count;i++) {
T* fs = new T(parent);
fs->SliderBase::SetDefaultValue(GetInnerInput().GetSplitDefaultValueForTrack(i));
fs->SetLadderElementCount(2);
// HACK: Force some spacing between sliders
fs->setContentsMargins(0, 0, QtUtils::QFontMetricsWidth(fs->fontMetrics(), QStringLiteral(" ")), 0);
widgets_.append(fs);
connect(fs, &T::ValueChanged, this, &NodeParamViewWidgetBridge::WidgetCallback);
}
}
void NodeParamViewWidgetBridge::UpdateWidgetValues()
{
if (GetInnerInput().IsArray() && GetInnerInput().element() == -1) {
return;
}
rational node_time;
if (GetInnerInput().IsKeyframing()) {
node_time = GetCurrentTimeAsNodeTime();
}
// We assume the first data type is the "primary" type
switch (GetDataType()) {
// None of these inputs have applicable UI widgets
case NodeValue::kNone:
case NodeValue::kTexture:
case NodeValue::kMatrix:
case NodeValue::kSamples:
case NodeValue::kVideoParams:
case NodeValue::kAudioParams:
case NodeValue::kSubtitleParams:
case NodeValue::kBinary:
case NodeValue::kDataTypeCount:
break;
case NodeValue::kInt:
{
static_cast<IntegerSlider*>(widgets_.first())->SetValue(GetInnerInput().GetValueAtTime(node_time).toLongLong());
break;
}
case NodeValue::kFloat:
{
static_cast<FloatSlider*>(widgets_.first())->SetValue(GetInnerInput().GetValueAtTime(node_time).toDouble());
break;
}
case NodeValue::kRational:
{
static_cast<RationalSlider*>(widgets_.first())->SetValue(GetInnerInput().GetValueAtTime(node_time).value<rational>());
break;
}
case NodeValue::kVec2:
{
QVector2D vec2 = GetInnerInput().GetValueAtTime(node_time).value<QVector2D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetValue(static_cast<double>(vec2.x()));
static_cast<FloatSlider*>(widgets_.at(1))->SetValue(static_cast<double>(vec2.y()));
break;
}
case NodeValue::kVec3:
{
QVector3D vec3 = GetInnerInput().GetValueAtTime(node_time).value<QVector3D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetValue(static_cast<double>(vec3.x()));
static_cast<FloatSlider*>(widgets_.at(1))->SetValue(static_cast<double>(vec3.y()));
static_cast<FloatSlider*>(widgets_.at(2))->SetValue(static_cast<double>(vec3.z()));
break;
}
case NodeValue::kVec4:
{
QVector4D vec4 = GetInnerInput().GetValueAtTime(node_time).value<QVector4D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetValue(static_cast<double>(vec4.x()));
static_cast<FloatSlider*>(widgets_.at(1))->SetValue(static_cast<double>(vec4.y()));
static_cast<FloatSlider*>(widgets_.at(2))->SetValue(static_cast<double>(vec4.z()));
static_cast<FloatSlider*>(widgets_.at(3))->SetValue(static_cast<double>(vec4.w()));
break;
}
case NodeValue::kFile:
{
FileField* ff = static_cast<FileField*>(widgets_.first());
ff->SetFilename(GetInnerInput().GetValueAtTime(node_time).toString());
break;
}
case NodeValue::kColor:
{
ManagedColor mc = GetInnerInput().GetValueAtTime(node_time).value<Color>();
mc.set_color_input(GetInnerInput().GetProperty("col_input").toString());
QString d = GetInnerInput().GetProperty("col_display").toString();
QString v = GetInnerInput().GetProperty("col_view").toString();
QString l = GetInnerInput().GetProperty("col_look").toString();
mc.set_color_output(ColorTransform(d, v, l));
static_cast<ColorButton*>(widgets_.first())->SetColor(mc);
break;
}
case NodeValue::kText:
{
NodeParamViewTextEdit* e = static_cast<NodeParamViewTextEdit*>(widgets_.first());
e->setTextPreservingCursor(GetInnerInput().GetValueAtTime(node_time).toString());
break;
}
case NodeValue::kBoolean:
static_cast<QCheckBox*>(widgets_.first())->setChecked(GetInnerInput().GetValueAtTime(node_time).toBool());
break;
case NodeValue::kFont:
{
QFontComboBox* fc = static_cast<QFontComboBox*>(widgets_.first());
fc->blockSignals(true);
fc->setCurrentFont(GetInnerInput().GetValueAtTime(node_time).toString());
fc->blockSignals(false);
break;
}
case NodeValue::kCombo:
{
QComboBox* cb = static_cast<QComboBox*>(widgets_.first());
cb->blockSignals(true);
int index = GetInnerInput().GetValueAtTime(node_time).toInt();
for (int i=0; i<cb->count(); i++) {
if (cb->itemData(i).toInt() == index) {
cb->setCurrentIndex(i);
}
}
cb->blockSignals(false);
break;
}
case NodeValue::kBezier:
{
BezierWidget* bw = static_cast<BezierWidget*>(widgets_.first());
bw->SetValue(GetInnerInput().GetValueAtTime(node_time).value<Bezier>());
break;
}
}
}
rational NodeParamViewWidgetBridge::GetCurrentTimeAsNodeTime() const
{
if (GetTimeTarget()) {
return GetAdjustedTime(GetTimeTarget(), GetInnerInput().node(), GetTimeTarget()->GetPlayhead(), Node::kTransformTowardsInput);
} else {
return 0;
}
}
QString NodeParamViewWidgetBridge::GetCommandName() const
{
NodeInput i = GetInnerInput();
return tr("Edited Value Of %1 - %2").arg(i.node()->GetLabelAndName(), i.node()->GetInputName(i.input()));
}
void NodeParamViewWidgetBridge::SetTimebase(const rational& timebase)
{
if (GetDataType() == NodeValue::kRational) {
static_cast<RationalSlider*>(widgets_.first())->SetTimebase(timebase);
}
}
void NodeParamViewWidgetBridge::TimeTargetDisconnectEvent(ViewerOutput *v)
{
disconnect(v, &ViewerOutput::PlayheadChanged, this, &NodeParamViewWidgetBridge::UpdateWidgetValues);
}
void NodeParamViewWidgetBridge::TimeTargetConnectEvent(ViewerOutput *v)
{
connect(v, &ViewerOutput::PlayheadChanged, this, &NodeParamViewWidgetBridge::UpdateWidgetValues);
}
void NodeParamViewWidgetBridge::InputValueChanged(const NodeInput &input, const TimeRange &range)
{
if (GetTimeTarget()
&& GetInnerInput() == input
&& !dragger_.IsStarted()
&& range.in() <= GetTimeTarget()->GetPlayhead() && range.out() >= GetTimeTarget()->GetPlayhead()) {
// We'll need to update the widgets because the values have changed on our current time
UpdateWidgetValues();
}
}
void NodeParamViewWidgetBridge::SetProperty(const QString &key, const QVariant &value)
{
NodeValue::Type data_type = GetDataType();
// Parameters for all types
bool key_is_disable = key.startsWith(QStringLiteral("disable"));
if (key_is_disable || key.startsWith(QStringLiteral("enabled"))) {
bool e = value.toBool();
if (key_is_disable) {
e = !e;
}
if (key.size() == 7) { // just the word "disable" or "enabled"
for (int i=0; i<widgets_.size(); i++) {
widgets_.at(i)->setEnabled(e);
}
} else { // set specific track/widget
bool ok;
int element = key.mid(7).toInt(&ok);
int tracks = NodeValue::get_number_of_keyframe_tracks(data_type);
if (ok && element >= 0 && element < tracks) {
widgets_.at(element)->setEnabled(e);
}
}
}
if (key == QStringLiteral("tooltip")) {
for (int i = 0; i < widgets_.size(); i++) {
widgets_.at(i)->setToolTip(value.toString());
}
}
// Parameters for integers, floats, and vectors
if (NodeValue::type_is_numeric(data_type) || NodeValue::type_is_vector(data_type)) {
if (key == QStringLiteral("min")) {
switch (data_type) {
case NodeValue::kInt:
static_cast<IntegerSlider*>(widgets_.first())->SetMinimum(value.value<int64_t>());
break;
case NodeValue::kFloat:
static_cast<FloatSlider*>(widgets_.first())->SetMinimum(value.toDouble());
break;
case NodeValue::kRational:
static_cast<RationalSlider*>(widgets_.first())->SetMinimum(value.value<rational>());
break;
case NodeValue::kVec2:
{
QVector2D min = value.value<QVector2D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMinimum(min.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMinimum(min.y());
break;
}
case NodeValue::kVec3:
{
QVector3D min = value.value<QVector3D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMinimum(min.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMinimum(min.y());
static_cast<FloatSlider*>(widgets_.at(2))->SetMinimum(min.z());
break;
}
case NodeValue::kVec4:
{
QVector4D min = value.value<QVector4D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMinimum(min.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMinimum(min.y());
static_cast<FloatSlider*>(widgets_.at(2))->SetMinimum(min.z());
static_cast<FloatSlider*>(widgets_.at(3))->SetMinimum(min.w());
break;
}
default:
break;
}
} else if (key == QStringLiteral("max")) {
switch (data_type) {
case NodeValue::kInt:
static_cast<IntegerSlider*>(widgets_.first())->SetMaximum(value.value<int64_t>());
break;
case NodeValue::kFloat:
static_cast<FloatSlider*>(widgets_.first())->SetMaximum(value.toDouble());
break;
case NodeValue::kRational:
static_cast<RationalSlider*>(widgets_.first())->SetMaximum(value.value<rational>());
break;
case NodeValue::kVec2:
{
QVector2D max = value.value<QVector2D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMaximum(max.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMaximum(max.y());
break;
}
case NodeValue::kVec3:
{
QVector3D max = value.value<QVector3D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMaximum(max.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMaximum(max.y());
static_cast<FloatSlider*>(widgets_.at(2))->SetMaximum(max.z());
break;
}
case NodeValue::kVec4:
{
QVector4D max = value.value<QVector4D>();
static_cast<FloatSlider*>(widgets_.at(0))->SetMaximum(max.x());
static_cast<FloatSlider*>(widgets_.at(1))->SetMaximum(max.y());
static_cast<FloatSlider*>(widgets_.at(2))->SetMaximum(max.z());
static_cast<FloatSlider*>(widgets_.at(3))->SetMaximum(max.w());
break;
}
default:
break;
}
} else if (key == QStringLiteral("offset")) {
int tracks = NodeValue::get_number_of_keyframe_tracks(data_type);
QVector<QVariant> offsets = NodeValue::split_normal_value_into_track_values(data_type, value);
for (int i=0; i<tracks; i++) {
static_cast<NumericSliderBase*>(widgets_.at(i))->SetOffset(offsets.at(i));
}
UpdateWidgetValues();
} else if (key.startsWith(QStringLiteral("color"))) {
QColor c(value.toString());
int tracks = NodeValue::get_number_of_keyframe_tracks(data_type);
if (key.size() == 5) {
// Set for all tracks
for (int i=0; i<tracks; i++) {
static_cast<SliderBase*>(widgets_.at(i))->SetColor(c);
}
} else {
bool ok;
int element = key.mid(5).toInt(&ok);
if (ok && element >= 0 && element < tracks) {
static_cast<SliderBase*>(widgets_.at(element))->SetColor(c);
}
}
} else if (key == QStringLiteral("base")) {
double d = value.toDouble();
for (int i=0; i<widgets_.size(); i++) {
static_cast<NumericSliderBase*>(widgets_.at(i))->SetDragMultiplier(d);
}
}
}
// ComboBox strings changing
if (data_type == NodeValue::kCombo) {
if (key == QStringLiteral("combo_str")) {
QComboBox* cb = static_cast<QComboBox*>(widgets_.first());
int old_index = cb->currentIndex();
// Block the combobox changed signals since we anticipate the index will be the same and not require a re-render
cb->blockSignals(true);
cb->clear();
QStringList items = value.toStringList();
int index = 0;
foreach (const QString& s, items) {
if (s.isEmpty()) {
cb->insertSeparator(cb->count());
cb->setItemData(cb->count()-1, -1);
} else {
cb->addItem(s, index);
index++;
}
}
cb->setCurrentIndex(old_index);
cb->blockSignals(false);
// In case the amount of items is LESS and the previous index cannot be set, NOW we trigger a re-cache since the
// value has changed
if (cb->currentIndex() != old_index) {
WidgetCallback();
}
}
}
// Parameters for floats and vectors only
if (data_type == NodeValue::kFloat || NodeValue::type_is_vector(data_type)) {
if (key == QStringLiteral("view")) {
FloatSlider::DisplayType display_type = static_cast<FloatSlider::DisplayType>(value.toInt());
foreach (QWidget* w, widgets_) {
static_cast<FloatSlider*>(w)->SetDisplayType(display_type);
}
} else if (key == QStringLiteral("decimalplaces")) {
int dec_places = value.toInt();
foreach (QWidget* w, widgets_) {
static_cast<FloatSlider*>(w)->SetDecimalPlaces(dec_places);
}
} else if (key == QStringLiteral("autotrim")) {
bool autotrim = value.toBool();
foreach (QWidget* w, widgets_) {
static_cast<FloatSlider*>(w)->SetAutoTrimDecimalPlaces(autotrim);
}
}
}
if (data_type == NodeValue::kRational) {
if (key == QStringLiteral("view")) {
RationalSlider::DisplayType display_type = static_cast<RationalSlider::DisplayType>(value.toInt());
foreach (QWidget* w, widgets_) {
static_cast<RationalSlider*>(w)->SetDisplayType(display_type);
}
} else if (key == QStringLiteral("viewlock")) {
bool locked = value.toBool();
foreach (QWidget* w, widgets_) {
static_cast<RationalSlider*>(w)->SetLockDisplayType(locked);
}
}
}
// Parameters for files
if (data_type == NodeValue::kFile) {
FileField* ff = static_cast<FileField*>(widgets_.first());
if (key == QStringLiteral("placeholder")) {
ff->SetPlaceholder(value.toString());
} else if (key == QStringLiteral("directory")) {
ff->SetDirectoryMode(value.toBool());
}
}
// Parameters for text
if (data_type == NodeValue::kText) {
NodeParamViewTextEdit *tex = static_cast<NodeParamViewTextEdit *>(widgets_.first());
if (key == QStringLiteral("vieweronly")) {
tex->SetEditInViewerOnlyMode(value.toBool());
}
}
}
void NodeParamViewWidgetBridge::InputDataTypeChanged(const QString &input, NodeValue::Type type)
{
if (sender() == GetOuterInput().node() && input == GetOuterInput().input()) {
// Delete all widgets
qDeleteAll(widgets_);
widgets_.clear();
// Create new widgets
CreateWidgets();
// Signal that widgets are new
emit WidgetsRecreated(GetOuterInput());
}
}
void NodeParamViewWidgetBridge::PropertyChanged(const QString &input, const QString &key, const QVariant &value)
{
bool found = false;
for (auto it=input_hierarchy_.cbegin(); it!=input_hierarchy_.cend(); it++) {
if (it->input() == input) {
found = true;
break;
}
}
if (found) {
UpdateProperties();
}
}
void NodeParamViewWidgetBridge::UpdateProperties()
{
// Set properties from the last entry (the innermost input) to the first (the outermost)
for (auto it=input_hierarchy_.crbegin(); it!=input_hierarchy_.crend(); it++) {
auto input_properties = it->node()->GetInputProperties(it->input());
for (auto jt=input_properties.cbegin(); jt!=input_properties.cend(); jt++) {
SetProperty(jt.key(), jt.value());
}
}
}
bool NodeParamViewScrollBlocker::eventFilter(QObject *watched, QEvent *event)
{
Q_UNUSED(watched)
if (event->type() == QEvent::Wheel) {
// Block this event
return true;
}
return false;
}
}
| 27,813
|
C++
|
.cpp
| 751
| 32.023968
| 151
| 0.680624
|
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
|
18,943
|
nodeparamviewcontext.cpp
|
olive-editor_olive/app/widget/nodeparamview/nodeparamviewcontext.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 "nodeparamviewcontext.h"
#include <QMessageBox>
#include "node/block/clip/clip.h"
#include "node/factory.h"
#include "node/nodeundo.h"
namespace olive {
#define super NodeParamViewItemBase
NodeParamViewContext::NodeParamViewContext(QWidget *parent) :
super(parent),
type_(Track::kNone)
{
QWidget *body = new QWidget();
QHBoxLayout *body_layout = new QHBoxLayout(body);
SetBody(body);
dock_area_ = new NodeParamViewDockArea();
body_layout->addWidget(dock_area_);
setBackgroundRole(QPalette::Base);
Retranslate();
connect(title_bar(), &NodeParamViewItemTitleBar::AddEffectButtonClicked, this, &NodeParamViewContext::AddEffectButtonClicked);
}
NodeParamViewItem *NodeParamViewContext::GetItem(Node *node, Node *ctx)
{
for (auto it=items_.begin(); it!=items_.end(); it++) {
NodeParamViewItem *item = *it;
if (item->GetNode() == node && item->GetContext() == ctx) {
return item;
}
}
return nullptr;
}
void NodeParamViewContext::AddNode(NodeParamViewItem *item)
{
items_.append(item);
dock_area_->AddItem(item);
}
void NodeParamViewContext::RemoveNode(Node *node, Node *ctx)
{
for (auto it=items_.begin(); it!=items_.end(); ) {
NodeParamViewItem *item = *it;
if (item->GetNode() == node && item->GetContext() == ctx) {
emit AboutToDeleteItem(item);
delete item;
it = items_.erase(it);
} else {
it++;
}
}
}
void NodeParamViewContext::RemoveNodesWithContext(Node *ctx)
{
for (auto it=items_.begin(); it!=items_.end(); ) {
NodeParamViewItem *item = *it;
if (item->GetContext() == ctx) {
emit AboutToDeleteItem(item);
delete item;
it = items_.erase(it);
} else {
it++;
}
}
}
void NodeParamViewContext::SetInputChecked(const NodeInput &input, bool e)
{
foreach (NodeParamViewItem *item, items_) {
if (item->GetNode() == input.node()) {
item->SetInputChecked(input, e);
}
}
}
void NodeParamViewContext::SetTimebase(const rational &timebase)
{
foreach (NodeParamViewItem* item, items_) {
item->SetTimebase(timebase);
}
}
void NodeParamViewContext::SetTimeTarget(ViewerOutput *n)
{
foreach (NodeParamViewItem* item, items_) {
item->SetTimeTarget(n);
}
}
void NodeParamViewContext::SetEffectType(Track::Type type)
{
type_ = type;
}
void NodeParamViewContext::Retranslate()
{
}
void NodeParamViewContext::AddEffectButtonClicked()
{
Node::Flag flag = Node::kNone;
if (type_ == Track::kVideo) {
flag = Node::kVideoEffect;
} else {
flag = Node::kAudioEffect;
}
if (flag == Node::kNone) {
return;
}
Menu *m = NodeFactory::CreateMenu(this, false, Node::kCategoryUnknown, flag);
connect(m, &Menu::triggered, this, &NodeParamViewContext::AddEffectMenuItemTriggered);
m->exec(QCursor::pos());
delete m;
}
void NodeParamViewContext::AddEffectMenuItemTriggered(QAction *a)
{
Node *n = NodeFactory::CreateFromMenuAction(a);
if (n) {
NodeInput new_node_input = n->GetEffectInput();
MultiUndoCommand *command = new MultiUndoCommand();
QVector<Project*> graphs_added_to;
foreach (Node *ctx, contexts_) {
NodeInput ctx_input = ctx->GetEffectInput();
if (!graphs_added_to.contains(ctx->parent())) {
command->add_child(new NodeAddCommand(ctx->parent(), n));
graphs_added_to.append(ctx->parent());
}
command->add_child(new NodeSetPositionCommand(n, ctx, ctx->GetNodePositionInContext(ctx)));
command->add_child(new NodeSetPositionCommand(ctx, ctx, ctx->GetNodePositionInContext(ctx) + QPointF(1, 0)));
if (ctx_input.IsConnected()) {
Node *prev_output = ctx_input.GetConnectedOutput();
command->add_child(new NodeEdgeRemoveCommand(prev_output, ctx_input));
command->add_child(new NodeEdgeAddCommand(prev_output, new_node_input));
}
command->add_child(new NodeEdgeAddCommand(n, ctx_input));
}
Core::instance()->undo_stack()->push(command, tr("Added %1 to Node Chain").arg(n->Name()));
}
}
}
| 4,735
|
C++
|
.cpp
| 144
| 29.180556
| 128
| 0.708223
|
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
|
18,944
|
columnedgridlayout.cpp
|
olive-editor_olive/app/widget/columnedgridlayout/columnedgridlayout.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 "columnedgridlayout.h"
namespace olive {
ColumnedGridLayout::ColumnedGridLayout(QWidget* parent,
int maximum_columns) :
QGridLayout (parent),
maximum_columns_(maximum_columns)
{
}
void ColumnedGridLayout::Add(QWidget *widget)
{
if (maximum_columns_ > 0) {
int row = count() / maximum_columns_;
int column = count() % maximum_columns_;
addWidget(widget, row, column);
} else {
addWidget(widget);
}
}
int ColumnedGridLayout::MaximumColumns() const
{
return maximum_columns_;
}
void ColumnedGridLayout::SetMaximumColumns(int maximum_columns)
{
maximum_columns_ = maximum_columns;
}
}
| 1,382
|
C++
|
.cpp
| 41
| 30.02439
| 71
| 0.740181
|
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
|
18,945
|
playbackcontrols.cpp
|
olive-editor_olive/app/widget/playbackcontrols/playbackcontrols.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 "playbackcontrols.h"
#include <QDebug>
#include <QEvent>
#include <QHBoxLayout>
#include "core.h"
#include "config/config.h"
#include "ui/icons/icons.h"
namespace olive {
PlaybackControls::PlaybackControls(QWidget *parent) :
QWidget(parent),
time_base_(0)
{
// Create lower controls
QHBoxLayout* lower_control_layout = new QHBoxLayout(this);
lower_control_layout->setSpacing(0);
lower_control_layout->setContentsMargins(0, 0, 0, 0);
QSizePolicy lower_container_size_policy(QSizePolicy::Maximum, QSizePolicy::Expanding);
lower_container_size_policy.setHorizontalStretch(1);
// In the lower-left, we create a current timecode label wrapped in a QWidget for fixed sizing
lower_left_container_ = new QWidget();
lower_left_container_->setVisible(false);
lower_left_container_->setSizePolicy(lower_container_size_policy);
lower_control_layout->addWidget(lower_left_container_);
QHBoxLayout* lower_left_layout = new QHBoxLayout(lower_left_container_);
lower_left_layout->setSpacing(0);
lower_left_layout->setContentsMargins(0, 0, 0, 0);
cur_tc_lbl_ = new RationalSlider();
cur_tc_lbl_->SetDisplayType(RationalSlider::kTime);
cur_tc_lbl_->SetMinimum(0);
connect(cur_tc_lbl_, &RationalSlider::ValueChanged, this, &PlaybackControls::TimeChanged);
lower_left_layout->addWidget(cur_tc_lbl_);
lower_left_layout->addStretch();
// This is only here
QWidget* blank_widget = new QWidget();
//new QHBoxLayout(blank_widget);
blank_widget->setSizePolicy(lower_container_size_policy);
lower_control_layout->addWidget(blank_widget);
// In the lower-middle, we create playback control buttons
QWidget* lower_middle_container = new QWidget();
lower_middle_container->setSizePolicy(lower_container_size_policy);
lower_control_layout->addWidget(lower_middle_container);
QHBoxLayout* lower_middle_layout = new QHBoxLayout(lower_middle_container);
lower_middle_layout->setSpacing(0);
lower_middle_layout->setContentsMargins(0, 0, 0, 0);
lower_middle_layout->addStretch();
QSizePolicy btn_sz_policy(QSizePolicy::Maximum, QSizePolicy::Preferred);
// Go To Start Button
go_to_start_btn_ = new QPushButton();
go_to_start_btn_->setSizePolicy(btn_sz_policy);
lower_middle_layout->addWidget(go_to_start_btn_);
connect(go_to_start_btn_, &QPushButton::clicked, this, &PlaybackControls::BeginClicked);
// Prev Frame Button
prev_frame_btn_ = new QPushButton();
prev_frame_btn_->setSizePolicy(btn_sz_policy);
lower_middle_layout->addWidget(prev_frame_btn_);
connect(prev_frame_btn_, &QPushButton::clicked, this, &PlaybackControls::PrevFrameClicked);
// Play/Pause Button
playpause_stack_ = new QStackedWidget();
playpause_stack_->setSizePolicy(btn_sz_policy);
lower_middle_layout->addWidget(playpause_stack_);
play_btn_ = new QPushButton();
playpause_stack_->addWidget(play_btn_);
connect(play_btn_, &QPushButton::clicked, this, &PlaybackControls::PlayClicked);
pause_btn_ = new QPushButton();
playpause_stack_->addWidget(pause_btn_);
connect(pause_btn_, &QPushButton::clicked, this, &PlaybackControls::PauseClicked);
// Default to showing play button
playpause_stack_->setCurrentWidget(play_btn_);
// Next Frame Button
next_frame_btn_ = new QPushButton();
next_frame_btn_->setSizePolicy(btn_sz_policy);
lower_middle_layout->addWidget(next_frame_btn_);
connect(next_frame_btn_, &QPushButton::clicked, this, &PlaybackControls::NextFrameClicked);
// Go To End Button
go_to_end_btn_ = new QPushButton();
go_to_end_btn_->setSizePolicy(btn_sz_policy);
lower_middle_layout->addWidget(go_to_end_btn_);
connect(go_to_end_btn_, &QPushButton::clicked, this, &PlaybackControls::EndClicked);
lower_middle_layout->addStretch();
QWidget* av_btn_widget = new QWidget();
av_btn_widget->setSizePolicy(lower_container_size_policy);
QHBoxLayout* av_btn_layout = new QHBoxLayout(av_btn_widget);
av_btn_layout->setSpacing(0);
av_btn_layout->setContentsMargins(0, 0, 0, 0);
video_drag_btn_ = new DragButton();
connect(video_drag_btn_, &QPushButton::clicked, this, &PlaybackControls::VideoClicked);
connect(video_drag_btn_, &DragButton::DragStarted, this, &PlaybackControls::VideoDragged);
av_btn_layout->addWidget(video_drag_btn_);
audio_drag_btn_ = new DragButton();
connect(audio_drag_btn_, &QPushButton::clicked, this, &PlaybackControls::AudioClicked);
connect(audio_drag_btn_, &DragButton::DragStarted, this, &PlaybackControls::AudioDragged);
av_btn_layout->addWidget(audio_drag_btn_);
lower_control_layout->addWidget(av_btn_widget);
// The lower-right, we create another timecode label, this time to show the end timecode
lower_right_container_ = new QWidget();
lower_right_container_->setVisible(false);
lower_right_container_->setSizePolicy(lower_container_size_policy);
lower_control_layout->addWidget(lower_right_container_);
QHBoxLayout* lower_right_layout = new QHBoxLayout(lower_right_container_);
lower_right_layout->setSpacing(0);
lower_right_layout->setContentsMargins(0, 0, 0, 0);
lower_right_layout->addStretch();
end_tc_lbl_ = new QLabel();
lower_right_layout->addWidget(end_tc_lbl_);
UpdateIcons();
SetTimebase(0);
SetAudioVideoDragButtonsVisible(false);
connect(Core::instance(), &Core::TimecodeDisplayChanged, this, &PlaybackControls::TimecodeChanged);
play_blink_timer_ = new QTimer(this);
play_blink_timer_->setInterval(500);
connect(play_blink_timer_, &QTimer::timeout, this, &PlaybackControls::PlayBlink);
}
void PlaybackControls::SetTimecodeEnabled(bool enabled)
{
lower_left_container_->setVisible(enabled);
lower_right_container_->setVisible(enabled);
}
void PlaybackControls::SetTimebase(const rational &r)
{
time_base_ = r;
cur_tc_lbl_->SetTimebase(r);
cur_tc_lbl_->setVisible(!r.isNull());
end_tc_lbl_->setVisible(!r.isNull());
setEnabled(!r.isNull());
}
void PlaybackControls::SetAudioVideoDragButtonsVisible(bool e)
{
video_drag_btn_->setVisible(e);
audio_drag_btn_->setVisible(e);
}
void PlaybackControls::SetTime(const rational &r)
{
cur_tc_lbl_->SetValue(r);
}
void PlaybackControls::SetEndTime(const rational &r)
{
if (time_base_.isNull()) {
return;
}
end_time_ = r;
end_tc_lbl_->setText(QString::fromStdString(Timecode::time_to_timecode(end_time_,
time_base_,
Core::instance()->GetTimecodeDisplay())));
}
void PlaybackControls::ShowPauseButton()
{
// Play was clicked, toggle to pause
playpause_stack_->setCurrentWidget(pause_btn_);
}
void PlaybackControls::ShowPlayButton()
{
playpause_stack_->setCurrentWidget(play_btn_);
}
void PlaybackControls::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
if (e->type() == QEvent::StyleChange) {
UpdateIcons();
}
}
void PlaybackControls::UpdateIcons()
{
go_to_start_btn_->setIcon(icon::GoToStart);
prev_frame_btn_->setIcon(icon::PrevFrame);
play_btn_->setIcon(icon::Play);
pause_btn_->setIcon(icon::Pause);
next_frame_btn_->setIcon(icon::NextFrame);
go_to_end_btn_->setIcon(icon::GoToEnd);
video_drag_btn_->setIcon(icon::Video);
audio_drag_btn_->setIcon(icon::Audio);
}
void PlaybackControls::SetButtonRecordingState(QPushButton *btn, bool on)
{
btn->setStyleSheet(on ? QStringLiteral("background: red;") : QString());
}
void PlaybackControls::TimecodeChanged()
{
// Update end time
SetEndTime(end_time_);
}
void PlaybackControls::PlayBlink()
{
SetButtonRecordingState(play_btn_, play_btn_->styleSheet().isEmpty());
}
}
| 8,329
|
C++
|
.cpp
| 199
| 38.346734
| 115
| 0.740062
|
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
|
18,946
|
dragbutton.cpp
|
olive-editor_olive/app/widget/playbackcontrols/dragbutton.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 Olive Studios LLC
This program is free software: you can 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 "dragbutton.h"
#include <QMouseEvent>
namespace olive {
DragButton::DragButton(QWidget *parent) :
QPushButton(parent)
{
setCursor(Qt::OpenHandCursor);
dragging_ = false;
}
void DragButton::mousePressEvent(QMouseEvent *event)
{
QPushButton::mousePressEvent(event);
}
void DragButton::mouseMoveEvent(QMouseEvent *event)
{
QPushButton::mouseMoveEvent(event);
if (event->buttons() && !dragging_) {
emit DragStarted();
dragging_ = true;
}
}
void DragButton::mouseReleaseEvent(QMouseEvent *event)
{
QPushButton::mouseReleaseEvent(event);
dragging_ = false;
}
}
| 1,318
|
C++
|
.cpp
| 41
| 29.560976
| 71
| 0.768621
|
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
|
18,948
|
nodecombobox.cpp
|
olive-editor_olive/app/widget/nodecombobox/nodecombobox.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 "nodecombobox.h"
#include <QAction>
#include <QEvent>
#include <QDebug>
#include "node/factory.h"
#include "ui/icons/icons.h"
#include "widget/menu/menu.h"
namespace olive {
NodeComboBox::NodeComboBox(QWidget *parent) :
QComboBox(parent)
{
}
void NodeComboBox::showPopup()
{
Menu* m = NodeFactory::CreateMenu(this, true);
QAction* selected = m->exec(parentWidget()->mapToGlobal(pos()));
if (selected) {
QString new_id = NodeFactory::GetIDFromMenuAction(selected);
SetNodeInternal(new_id, true);
}
delete m;
}
const QString &NodeComboBox::GetSelectedNode() const
{
return selected_id_;
}
void NodeComboBox::SetNode(const QString &id)
{
SetNodeInternal(id, false);
}
void NodeComboBox::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
UpdateText();
}
QComboBox::changeEvent(e);
}
void NodeComboBox::UpdateText()
{
clear();
if (!selected_id_.isEmpty()) {
addItem(NodeFactory::GetNameFromID(selected_id_));
}
}
void NodeComboBox::SetNodeInternal(const QString &id, bool emit_signal)
{
if (selected_id_ != id) {
selected_id_ = id;
UpdateText();
if (emit_signal) {
emit NodeChanged(selected_id_);
}
}
}
}
| 1,928
|
C++
|
.cpp
| 69
| 25.217391
| 71
| 0.736641
|
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
|
18,949
|
planarfiledevice.cpp
|
olive-editor_olive/app/codec/planarfiledevice.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 "planarfiledevice.h"
namespace olive {
PlanarFileDevice::PlanarFileDevice(QObject *parent) :
QObject(parent)
{
}
PlanarFileDevice::~PlanarFileDevice()
{
close();
}
bool PlanarFileDevice::open(const QVector<QString> &filenames, QIODevice::OpenMode mode)
{
if (isOpen()) {
// Already open
return false;
}
files_.resize(filenames.size());
files_.fill(nullptr);
for (int i=0; i<files_.size(); i++) {
files_[i] = new QFile(filenames.at(i));
if (!files_[i]->open(mode)) {
close();
return false;
}
}
return true;
}
qint64 PlanarFileDevice::read(char **data, qint64 bytes_per_channel, qint64 offset)
{
qint64 ret = -1;
if (isOpen()) {
for (int i=0; i<files_.size(); i++) {
// Kind of clunky but should be largely fine
ret = files_[i]->read(data[i] + offset, bytes_per_channel);
}
}
return ret;
}
qint64 PlanarFileDevice::write(const char **data, qint64 bytes_per_channel, qint64 offset)
{
qint64 ret = -1;
if (isOpen()) {
for (int i=0; i<files_.size(); i++) {
// Kind of clunky but should be largely fine
ret = files_[i]->write(data[i] + offset, bytes_per_channel);
}
}
return ret;
}
qint64 PlanarFileDevice::size() const
{
if (isOpen()) {
return files_.first()->size();
} else {
return 0;
}
}
bool PlanarFileDevice::seek(qint64 pos)
{
bool ret = true;
for (int i=0; i<files_.size(); i++) {
ret = files_[i]->seek(pos) & ret;
}
return ret;
}
void PlanarFileDevice::close()
{
for (int i=0; i<files_.size(); i++) {
QFile *f = files_.at(i);
if (f) {
if (f->isOpen()) {
f->close();
}
delete f;
}
}
files_.clear();
}
}
| 2,422
|
C++
|
.cpp
| 93
| 22.612903
| 90
| 0.664351
|
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
|
18,950
|
exportcodec.cpp
|
olive-editor_olive/app/codec/exportcodec.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 "exportcodec.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/pixdesc.h>
}
namespace olive {
QString ExportCodec::GetCodecName(ExportCodec::Codec c)
{
switch (c) {
case kCodecDNxHD:
return tr("DNxHD");
case kCodecH264:
return tr("H.264");
case kCodecH264rgb:
return tr("H.264 RGB");
case kCodecH265:
return tr("H.265");
case kCodecOpenEXR:
return tr("OpenEXR");
case kCodecPNG:
return tr("PNG");
case kCodecProRes:
return tr("ProRes");
case kCodecCineform:
return tr("Cineform");
case kCodecTIFF:
return tr("TIFF");
case kCodecMP2:
return tr("MP2");
case kCodecMP3:
return tr("MP3");
case kCodecAAC:
return tr("AAC");
case kCodecPCM:
return tr("PCM (Uncompressed)");
case kCodecFLAC:
return tr("FLAC");
case kCodecOpus:
return tr("Opus");
case kCodecVorbis:
return tr("Vorbis");
case kCodecVP9:
return tr("VP9");
case kCodecAV1:
return tr("AV1");
case kCodecSRT:
return tr("SubRip SRT");
case kCodecCount:
break;
}
return tr("Unknown");
}
bool ExportCodec::IsCodecAStillImage(ExportCodec::Codec c)
{
switch (c) {
case kCodecDNxHD:
case kCodecH264:
case kCodecH264rgb:
case kCodecH265:
case kCodecProRes:
case kCodecCineform:
case kCodecMP2:
case kCodecMP3:
case kCodecAAC:
case kCodecPCM:
case kCodecVorbis:
case kCodecOpus:
case kCodecFLAC:
case kCodecVP9:
case kCodecAV1:
case kCodecSRT:
return false;
case kCodecOpenEXR:
case kCodecPNG:
case kCodecTIFF:
return true;
case kCodecCount:
break;
}
return false;
}
bool ExportCodec::IsCodecLossless(Codec c)
{
switch (c) {
case kCodecPCM:
case kCodecFLAC:
return true;
case kCodecDNxHD:
case kCodecH264:
case kCodecH264rgb:
case kCodecH265:
case kCodecProRes:
case kCodecCineform:
case kCodecMP2:
case kCodecMP3:
case kCodecAAC:
case kCodecVorbis:
case kCodecOpus:
case kCodecVP9:
case kCodecAV1:
case kCodecSRT:
case kCodecOpenEXR:
case kCodecPNG:
case kCodecTIFF:
case kCodecCount:
break;
}
return false;
}
}
| 2,848
|
C++
|
.cpp
| 124
| 19.717742
| 71
| 0.72979
|
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
|
18,951
|
exportformat.cpp
|
olive-editor_olive/app/codec/exportformat.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 "exportformat.h"
#include "encoder.h"
namespace olive {
QString ExportFormat::GetName(olive::ExportFormat::Format f)
{
switch (f) {
case kFormatDNxHD:
return tr("DNxHD");
case kFormatMatroska:
return tr("Matroska Video");
case kFormatMPEG4Video:
return tr("MPEG-4 Video");
case kFormatMPEG4Audio:
return tr("MPEG-4 Audio");
case kFormatOpenEXR:
return tr("OpenEXR");
case kFormatPNG:
return tr("PNG");
case kFormatTIFF:
return tr("TIFF");
case kFormatQuickTime:
return tr("QuickTime");
case kFormatWAV:
return tr("Wave Audio");
case kFormatAIFF:
return tr("AIFF");
case kFormatMP3:
return tr("MP3");
case kFormatFLAC:
return tr("FLAC");
case kFormatOgg:
return tr("Ogg");
case kFormatWebM:
return tr("WebM");
case kFormatSRT:
return tr("SubRip SRT");
case kFormatCount:
break;
}
return tr("Unknown");
}
QString ExportFormat::GetExtension(ExportFormat::Format f)
{
switch (f) {
case kFormatDNxHD:
return QStringLiteral("mxf");
case kFormatMatroska:
return QStringLiteral("mkv");
case kFormatMPEG4Video:
return QStringLiteral("mp4");
case kFormatMPEG4Audio:
return QStringLiteral("m4a");
case kFormatOpenEXR:
return QStringLiteral("exr");
case kFormatPNG:
return QStringLiteral("png");
case kFormatTIFF:
return QStringLiteral("tiff");
case kFormatQuickTime:
return QStringLiteral("mov");
case kFormatWAV:
return QStringLiteral("wav");
case kFormatAIFF:
return QStringLiteral("aiff");
case kFormatMP3:
return QStringLiteral("mp3");
case kFormatFLAC:
return QStringLiteral("flac");
case kFormatOgg:
return QStringLiteral("ogg");
case kFormatWebM:
return QStringLiteral("webm");
case kFormatSRT:
return QStringLiteral("srt");
case kFormatCount:
break;
}
return QString();
}
QList<ExportCodec::Codec> ExportFormat::GetVideoCodecs(ExportFormat::Format f)
{
switch (f) {
case kFormatDNxHD:
return {ExportCodec::kCodecDNxHD};
case kFormatMatroska:
return {ExportCodec::kCodecH264, ExportCodec::kCodecH264rgb, ExportCodec::kCodecH265, ExportCodec::kCodecVP9};
case kFormatMPEG4Video:
return {ExportCodec::kCodecH264, ExportCodec::kCodecH264rgb, ExportCodec::kCodecH265};
case kFormatOpenEXR:
return {ExportCodec::kCodecOpenEXR};
case kFormatPNG:
return {ExportCodec::kCodecPNG};
case kFormatTIFF:
return {ExportCodec::kCodecTIFF};
case kFormatQuickTime:
return {ExportCodec::kCodecH264, ExportCodec::kCodecH264rgb, ExportCodec::kCodecH265, ExportCodec::kCodecProRes, ExportCodec::kCodecCineform};
case kFormatWebM:
return {ExportCodec::kCodecAV1, ExportCodec::kCodecVP9};
case kFormatOgg:
case kFormatWAV:
case kFormatMPEG4Audio:
case kFormatAIFF:
case kFormatMP3:
case kFormatFLAC:
case kFormatSRT:
case kFormatCount:
break;
}
return {};
}
QList<ExportCodec::Codec> ExportFormat::GetAudioCodecs(ExportFormat::Format f)
{
switch (f) {
// Video/audio formats
case kFormatDNxHD:
return {ExportCodec::kCodecPCM};
case kFormatMatroska:
return {ExportCodec::kCodecAAC, ExportCodec::kCodecMP2, ExportCodec::kCodecMP3, ExportCodec::kCodecPCM, ExportCodec::kCodecVorbis, ExportCodec::kCodecOpus, ExportCodec::kCodecFLAC};
case kFormatMPEG4Video:
case kFormatMPEG4Audio:
return {ExportCodec::kCodecAAC, ExportCodec::kCodecMP2, ExportCodec::kCodecMP3};
case kFormatQuickTime:
return {ExportCodec::kCodecAAC, ExportCodec::kCodecMP2, ExportCodec::kCodecMP3, ExportCodec::kCodecPCM};
case kFormatWebM:
return {ExportCodec::kCodecOpus, ExportCodec::kCodecAAC, ExportCodec::kCodecMP2, ExportCodec::kCodecMP3, ExportCodec::kCodecPCM, ExportCodec::kCodecVorbis};
// Audio only formats
case kFormatWAV:
return {ExportCodec::kCodecPCM};
case kFormatAIFF:
return {ExportCodec::kCodecPCM};
case kFormatMP3:
return {ExportCodec::kCodecMP3};
case kFormatFLAC:
return {ExportCodec::kCodecFLAC};
case kFormatOgg:
return {ExportCodec::kCodecOpus, ExportCodec::kCodecVorbis, ExportCodec::kCodecPCM};
// Video only formats
case kFormatOpenEXR:
case kFormatPNG:
case kFormatTIFF:
case kFormatSRT:
case kFormatCount:
break;
}
return {};
}
QList<ExportCodec::Codec> ExportFormat::GetSubtitleCodecs(Format f)
{
switch (f) {
case kFormatDNxHD:
case kFormatMPEG4Video:
case kFormatMPEG4Audio:
case kFormatOpenEXR:
case kFormatQuickTime:
case kFormatPNG:
case kFormatTIFF:
case kFormatWAV:
case kFormatAIFF:
case kFormatMP3:
case kFormatFLAC:
case kFormatOgg:
case kFormatWebM:
case kFormatCount:
break;
case kFormatMatroska:
case kFormatSRT:
return {ExportCodec::kCodecSRT};
}
return {};
}
QStringList ExportFormat::GetPixelFormatsForCodec(ExportFormat::Format f, ExportCodec::Codec c)
{
Encoder* e = Encoder::CreateFromFormat(f, EncodingParams());
QStringList list;
if (e) {
list = e->GetPixelFormatsForCodec(c);
delete e;
}
return list;
}
std::vector<SampleFormat> ExportFormat::GetSampleFormatsForCodec(Format format, ExportCodec::Codec c)
{
std::vector<SampleFormat> f;
Encoder *e = Encoder::CreateFromFormat(format, EncodingParams());
if (e) {
f = e->GetSampleFormatsForCodec(c);
delete e;
}
return f;
}
}
| 6,060
|
C++
|
.cpp
| 205
| 26.112195
| 185
| 0.754335
|
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
|
18,952
|
encoder.cpp
|
olive-editor_olive/app/codec/encoder.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 "encoder.h"
#include <QFile>
#include "common/xmlutils.h"
#include "ffmpeg/ffmpegencoder.h"
#include "oiio/oiioencoder.h"
namespace olive {
const QRegularExpression Encoder::kImageSequenceContainsDigits = QRegularExpression(QStringLiteral("\\[[#]+\\]"));
const QRegularExpression Encoder::kImageSequenceRemoveDigits = QRegularExpression(QStringLiteral("[\\-\\.\\ \\_]?\\[[#]+\\]"));
Encoder::Encoder(const EncodingParams ¶ms) :
params_(params)
{
}
const EncodingParams &Encoder::params() const
{
return params_;
}
QString Encoder::GetFilenameForFrame(const rational &frame)
{
if (params().video_is_image_sequence()) {
// Transform!
int64_t frame_index = Timecode::time_to_timestamp(frame, params().video_params().frame_rate_as_time_base());
int digits = GetImageSequencePlaceholderDigitCount(params().filename());
QString frame_index_str = QStringLiteral("%1").arg(frame_index, digits, 10, QChar('0'));
QString f = params_.filename();
f.replace(kImageSequenceContainsDigits, frame_index_str);
return f;
} else {
// Keep filename
return params_.filename();
}
}
int Encoder::GetImageSequencePlaceholderDigitCount(const QString &filename)
{
int start = filename.indexOf(kImageSequenceContainsDigits);
int digit_count = 0;
for (int i=start+1; i<filename.size(); i++) {
if (filename.at(i) == '#') {
digit_count++;
} else {
break;
}
}
return digit_count;
}
bool Encoder::FilenameContainsDigitPlaceholder(const QString& filename)
{
return filename.contains(kImageSequenceContainsDigits);
}
QString Encoder::FilenameRemoveDigitPlaceholder(QString filename)
{
return filename.remove(kImageSequenceRemoveDigits);
}
EncodingParams::EncodingParams() :
video_enabled_(false),
video_bit_rate_(0),
video_min_bit_rate_(0),
video_max_bit_rate_(0),
video_buffer_size_(0),
video_threads_(0),
video_is_image_sequence_(false),
audio_enabled_(false),
audio_bit_rate_(0),
subtitles_enabled_(false),
subtitles_are_sidecar_(false),
video_scaling_method_(kStretch),
has_custom_range_(false)
{
}
QDir EncodingParams::GetPresetPath()
{
return QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("exportpresets"));
}
QStringList EncodingParams::GetListOfPresets()
{
QDir d = EncodingParams::GetPresetPath();
return d.entryList(QDir::Files);
}
void EncodingParams::EnableVideo(const VideoParams &video_params, const ExportCodec::Codec &vcodec)
{
video_enabled_ = true;
video_params_ = video_params;
video_codec_ = vcodec;
}
void EncodingParams::EnableAudio(const AudioParams &audio_params, const ExportCodec::Codec &acodec)
{
audio_enabled_ = true;
audio_params_ = audio_params;
audio_codec_ = acodec;
}
void EncodingParams::EnableSubtitles(const ExportCodec::Codec &scodec)
{
subtitles_enabled_ = true;
subtitles_codec_ = scodec;
}
void EncodingParams::EnableSidecarSubtitles(const ExportFormat::Format &sfmt, const ExportCodec::Codec &scodec)
{
subtitles_enabled_ = true;
subtitles_are_sidecar_ = true;
subtitle_sidecar_fmt_ = sfmt;
subtitles_codec_ = scodec;
}
void EncodingParams::DisableVideo()
{
video_enabled_ = false;
}
void EncodingParams::DisableAudio()
{
audio_enabled_ = false;
}
void EncodingParams::DisableSubtitles()
{
subtitles_enabled_ = false;
}
bool EncodingParams::Load(QXmlStreamReader *reader)
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("export")) {
int version = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("version")) {
version = attr.value().toInt();
}
}
switch (version) {
case 1:
return LoadV1(reader);
}
} else {
reader->skipCurrentElement();
}
}
return false;
}
bool EncodingParams::Load(QIODevice *device)
{
QXmlStreamReader reader(device);
return Load(&reader);
}
void EncodingParams::Save(QIODevice *device) const
{
QXmlStreamWriter writer(device);
Save(&writer);
}
void EncodingParams::Save(QXmlStreamWriter *writer) const
{
writer->writeStartDocument();
writer->writeStartElement(QStringLiteral("export"));
writer->writeAttribute(QStringLiteral("version"), QString::number(kEncoderParamsVersion));
writer->writeTextElement(QStringLiteral("filename"), filename_);
writer->writeTextElement(QStringLiteral("format"), QString::number(format_));
writer->writeTextElement(QStringLiteral("range"), QString::number(has_custom_range_));
writer->writeTextElement(QStringLiteral("customrangein"), QString::fromStdString(custom_range_.in().toString()));
writer->writeTextElement(QStringLiteral("customrangeout"), QString::fromStdString(custom_range_.out().toString()));
writer->writeStartElement(QStringLiteral("video"));
writer->writeAttribute(QStringLiteral("enabled"), QString::number(video_enabled_));
if (video_enabled_) {
writer->writeTextElement(QStringLiteral("codec"), QString::number(video_codec_));
writer->writeTextElement(QStringLiteral("width"), QString::number(video_params_.width()));
writer->writeTextElement(QStringLiteral("height"), QString::number(video_params_.height()));
writer->writeTextElement(QStringLiteral("format"), QString::number(video_params_.format()));
writer->writeTextElement(QStringLiteral("pixelaspect"), QString::fromStdString(video_params_.pixel_aspect_ratio().toString()));
writer->writeTextElement(QStringLiteral("timebase"), QString::fromStdString(video_params_.time_base().toString()));
writer->writeTextElement(QStringLiteral("divider"), QString::number(video_params_.divider()));
writer->writeTextElement(QStringLiteral("bitrate"), QString::number(video_bit_rate_));
writer->writeTextElement(QStringLiteral("minbitrate"), QString::number(video_min_bit_rate_));
writer->writeTextElement(QStringLiteral("maxbitrate"), QString::number(video_max_bit_rate_));
writer->writeTextElement(QStringLiteral("bufsize"), QString::number(video_buffer_size_));
writer->writeTextElement(QStringLiteral("threads"), QString::number(video_threads_));
writer->writeTextElement(QStringLiteral("pixfmt"), video_pix_fmt_);
writer->writeTextElement(QStringLiteral("imgseq"), QString::number(video_is_image_sequence_));
writer->writeStartElement(QStringLiteral("color"));
writer->writeTextElement(QStringLiteral("output"), color_transform_.output());
writer->writeEndElement(); // colortransform
writer->writeTextElement(QStringLiteral("vscale"), QString::number(video_scaling_method_));
if (!video_opts_.isEmpty()) {
writer->writeStartElement(QStringLiteral("opts"));
QHash<QString, QString>::const_iterator i;
for (i=video_opts_.constBegin(); i!=video_opts_.constEnd(); i++) {
writer->writeStartElement(QStringLiteral("entry"));
writer->writeTextElement(QStringLiteral("key"), i.key());
writer->writeTextElement(QStringLiteral("value"), i.value());
writer->writeEndElement(); // entry
}
writer->writeEndElement(); // opts
}
}
writer->writeEndElement(); // video
writer->writeStartElement(QStringLiteral("audio"));
writer->writeAttribute(QStringLiteral("enabled"), QString::number(audio_enabled_));
if (audio_enabled_) {
writer->writeTextElement(QStringLiteral("codec"), QString::number(audio_codec_));
writer->writeTextElement(QStringLiteral("samplerate"), QString::number(audio_params_.sample_rate()));
writer->writeTextElement(QStringLiteral("channellayout"), QString::number(audio_params_.channel_layout()));
writer->writeTextElement(QStringLiteral("format"), QString::fromStdString(audio_params_.format().to_string()));
writer->writeTextElement(QStringLiteral("bitrate"), QString::number(audio_bit_rate_));
}
writer->writeStartElement(QStringLiteral("subtitles"));
writer->writeAttribute(QStringLiteral("enabled"), QString::number(subtitles_enabled_));
if (subtitles_enabled_) {
writer->writeTextElement(QStringLiteral("sidecar"), QString::number(subtitles_are_sidecar_));
writer->writeTextElement(QStringLiteral("sidecarformat"), QString::number(subtitle_sidecar_fmt_));
writer->writeTextElement(QStringLiteral("codec"), QString::number(subtitles_codec_));
}
writer->writeEndElement(); // subtitles
writer->writeEndElement(); // audio
writer->writeEndElement(); // export
writer->writeEndDocument();
}
Encoder* Encoder::CreateFromID(Type id, const EncodingParams& params)
{
switch (id) {
case kEncoderTypeNone:
break;
case kEncoderTypeFFmpeg:
return new FFmpegEncoder(params);
case kEncoderTypeOIIO:
return new OIIOEncoder(params);
}
return nullptr;
}
Encoder::Type Encoder::GetTypeFromFormat(ExportFormat::Format f)
{
switch (f) {
case ExportFormat::kFormatDNxHD:
case ExportFormat::kFormatMatroska:
case ExportFormat::kFormatQuickTime:
case ExportFormat::kFormatMPEG4Video:
case ExportFormat::kFormatMPEG4Audio:
case ExportFormat::kFormatWAV:
case ExportFormat::kFormatAIFF:
case ExportFormat::kFormatMP3:
case ExportFormat::kFormatFLAC:
case ExportFormat::kFormatOgg:
case ExportFormat::kFormatWebM:
case ExportFormat::kFormatSRT:
return kEncoderTypeFFmpeg;
case ExportFormat::kFormatOpenEXR:
case ExportFormat::kFormatPNG:
case ExportFormat::kFormatTIFF:
return kEncoderTypeOIIO;
case ExportFormat::kFormatCount:
break;
}
return kEncoderTypeNone;
}
Encoder *Encoder::CreateFromFormat(ExportFormat::Format f, const EncodingParams ¶ms)
{
return CreateFromID(GetTypeFromFormat(f), params);
}
Encoder *Encoder::CreateFromParams(const EncodingParams ¶ms)
{
return CreateFromFormat(params.format(), params);
}
QStringList Encoder::GetPixelFormatsForCodec(ExportCodec::Codec c) const
{
return QStringList();
}
std::vector<SampleFormat> Encoder::GetSampleFormatsForCodec(ExportCodec::Codec c) const
{
return std::vector<SampleFormat>();
}
QMatrix4x4 EncodingParams::GenerateMatrix(EncodingParams::VideoScalingMethod method,
int source_width, int source_height,
int dest_width, int dest_height)
{
QMatrix4x4 preview_matrix;
if (method == EncodingParams::kStretch) {
return preview_matrix;
}
float export_ar = static_cast<float>(dest_width) / static_cast<float>(dest_height);
float source_ar = static_cast<float>(source_width) / static_cast<float>(source_height);
if (qFuzzyCompare(export_ar, source_ar)) {
return preview_matrix;
}
if ((export_ar > source_ar) == (method == EncodingParams::kFit)) {
preview_matrix.scale(source_ar / export_ar, 1.0F);
} else {
preview_matrix.scale(1.0F, export_ar / source_ar);
}
return preview_matrix;
}
bool EncodingParams::LoadV1(QXmlStreamReader *reader)
{
rational custom_range_in, custom_range_out;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("filename")) {
filename_ = reader->readElementText();
} else if (reader->name() == QStringLiteral("format")) {
format_ = static_cast<ExportFormat::Format>(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("range")) {
has_custom_range_ = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("customrangein")) {
custom_range_in = rational::fromString(reader->readElementText().toStdString());
} else if (reader->name() == QStringLiteral("customrangeout")) {
custom_range_out = rational::fromString(reader->readElementText().toStdString());
} else if (reader->name() == QStringLiteral("video")) {
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
video_enabled_ = attr.value().toInt();
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("codec")) {
video_codec_ = static_cast<ExportCodec::Codec>(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("width")) {
video_params_.set_width(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("height")) {
video_params_.set_height(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("format")) {
video_params_.set_format(static_cast<PixelFormat::Format>(reader->readElementText().toInt()));
} else if (reader->name() == QStringLiteral("pixelaspect")) {
video_params_.set_pixel_aspect_ratio(rational::fromString(reader->readElementText().toStdString()));
} else if (reader->name() == QStringLiteral("timebase")) {
video_params_.set_time_base(rational::fromString(reader->readElementText().toStdString()));
} else if (reader->name() == QStringLiteral("divider")) {
video_params_.set_divider(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("bitrate")) {
video_bit_rate_ = reader->readElementText().toLongLong();
} else if (reader->name() == QStringLiteral("minbitrate")) {
video_min_bit_rate_ = reader->readElementText().toLongLong();
} else if (reader->name() == QStringLiteral("maxbitrate")) {
video_max_bit_rate_ = reader->readElementText().toLongLong();
} else if (reader->name() == QStringLiteral("bufsize")) {
video_buffer_size_ = reader->readElementText().toLongLong();
} else if (reader->name() == QStringLiteral("threads")) {
video_threads_ = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("pixfmt")) {
video_pix_fmt_ = reader->readElementText();
} else if (reader->name() == QStringLiteral("imgseq")) {
video_is_image_sequence_ = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("color")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("output")) {
color_transform_ = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("vscale")) {
video_scaling_method_ = static_cast<VideoScalingMethod>(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("opts")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("entry")) {
QString key, value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
key = reader->readElementText();
} else if (reader->name() == QStringLiteral("value")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
set_video_option(key, value);
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
// HACK: Resolve bug where I forgot to serialize pixel aspect ratio
if (video_params_.pixel_aspect_ratio().isNull()) {
video_params_.set_pixel_aspect_ratio(1);
}
} else if (reader->name() == QStringLiteral("audio")) {
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
audio_enabled_ = attr.value().toInt();
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("codec")) {
audio_codec_ = static_cast<ExportCodec::Codec>(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("samplerate")) {
audio_params_.set_sample_rate(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("channellayout")) {
audio_params_.set_channel_layout(reader->readElementText().toULongLong());
} else if (reader->name() == QStringLiteral("format")) {
audio_params_.set_format(SampleFormat::from_string(reader->readElementText().toStdString()));
} else if (reader->name() == QStringLiteral("bitrate")) {
audio_bit_rate_ = reader->readElementText().toLongLong();
} else {
reader->skipCurrentElement();
}
}
// HACK: Resolve bug where I forgot to serialize the audio bit rate
if (!audio_bit_rate_) {
audio_bit_rate_ = 320000;
}
} else if (reader->name() == QStringLiteral("subtitles")) {
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
subtitles_enabled_ = attr.value().toInt();
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("sidecar")) {
subtitles_are_sidecar_ = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("sidecarformat")) {
subtitle_sidecar_fmt_ = static_cast<ExportFormat::Format>(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("codec")) {
subtitles_codec_ = static_cast<ExportCodec::Codec>(reader->readElementText().toInt());
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
return true;
}
}
| 18,283
|
C++
|
.cpp
| 429
| 37.172494
| 131
| 0.690057
|
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
|
18,953
|
conformmanager.cpp
|
olive-editor_olive/app/codec/conformmanager.cpp
|
#include "conformmanager.h"
#include <QDir>
#include "task/taskmanager.h"
namespace olive {
ConformManager *ConformManager::instance_ = nullptr;
ConformManager::Conform ConformManager::GetConformState(const QString &decoder_id, const QString &cache_path, const Decoder::CodecStream &stream, const AudioParams ¶ms, bool wait)
{
// Mutex because we'll need to check the status of a conform task
QMutexLocker locker(&mutex_);
// Return existing conform if exists
QVector<QString> filenames = GetConformedFilename(cache_path, stream, params);
if (AllConformsExist(filenames)) {
return {kConformExists, filenames, nullptr};
}
ConformTask *conforming_task = nullptr;
foreach (const ConformData &data, conforming_) {
if (data.stream == stream && data.params == params) {
// Already creating conform in a task
conforming_task = data.task;
break;
}
}
if (!conforming_task) {
// Not conforming yet, create a task to do so
// We conform to a different filename until it's done to make it clear even across sessions
// whether this conform is ready or not
QVector<QString> working_filenames = filenames;
for (int i=0; i<working_filenames.size(); i++) {
working_filenames[i].append(QStringLiteral(".working"));
}
conforming_task = new ConformTask(decoder_id, stream, params, working_filenames);
connect(conforming_task, &ConformTask::Finished, this, &ConformManager::ConformTaskFinished);
conforming_task->moveToThread(TaskManager::instance()->thread());
QMetaObject::invokeMethod(TaskManager::instance(), "AddTask", Qt::QueuedConnection, Q_ARG(Task *, conforming_task));
conforming_.append({stream, params, conforming_task, working_filenames, filenames});
}
if (wait) {
do {
conform_done_condition_.wait(&mutex_);
} while (!AllConformsExist(filenames));
return {kConformExists, filenames, nullptr};
}
return {kConformGenerating, QVector<QString>(), conforming_task};
}
QVector<QString> ConformManager::GetConformedFilename(const QString &cache_path, const Decoder::CodecStream &stream, const AudioParams ¶ms)
{
QVector<QString> filenames(params.channel_count());
for (int i=0; i<filenames.size(); i++) {
QString index_fn = QStringLiteral("%1-%2.%3.%4.%5.%6.pcm").arg(FileFunctions::GetUniqueFileIdentifier(stream.filename()),
QString::number(stream.stream()),
QString::number(params.sample_rate()),
QString::number(params.format()),
QString::number(params.channel_layout()),
QString::number(i));
filenames[i] = QDir(cache_path).filePath(index_fn);
}
return filenames;
}
bool ConformManager::AllConformsExist(const QVector<QString> &filenames)
{
foreach (const QString &fn, filenames) {
if (!QFileInfo::exists(fn)) {
return false;
}
}
return true;
}
void ConformManager::ConformTaskFinished(Task *task, bool succeeded)
{
QMutexLocker locker(&mutex_);
ConformData data;
// Remove conform data from list
for (int i=0; i<conforming_.size(); i++) {
const ConformData &c = conforming_.at(i);
if (c.task == task) {
data = c;
conforming_.removeAt(i);
break;
}
}
if (succeeded) {
// Move file to standard conform name, making it clear this conform is ready for use
for (int i=0; i<data.finished_filename.size(); i++) {
const QString &finished = data.finished_filename.at(i);
const QString &working = data.working_filename.at(i);
QFile::remove(finished);
QFile::rename(working, finished);
}
conform_done_condition_.wakeAll();
locker.unlock();
emit ConformReady();
} else {
// Failed, just delete the working filename if exists
for (int i=0; i<data.working_filename.size(); i++) {
QFile::remove(data.working_filename.at(i));
}
}
}
}
| 4,154
|
C++
|
.cpp
| 99
| 34.535354
| 183
| 0.651936
|
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
|
18,954
|
decoder.cpp
|
olive-editor_olive/app/codec/decoder.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 "decoder.h"
#include <QCoreApplication>
#include <QDebug>
#include <QHash>
#include "codec/ffmpeg/ffmpegdecoder.h"
#include "codec/planarfiledevice.h"
#include "codec/oiio/oiiodecoder.h"
#include "common/ffmpegutils.h"
#include "common/filefunctions.h"
#include "conformmanager.h"
#include "node/project.h"
#include "task/taskmanager.h"
namespace olive {
const rational Decoder::kAnyTimecode = RATIONAL_MIN;
Decoder::Decoder() :
cached_texture_(nullptr)
{
UpdateLastAccessed();
}
void Decoder::IncrementAccessTime(qint64 t)
{
last_accessed_ += t;
}
bool Decoder::Open(const CodecStream &stream)
{
QMutexLocker locker(&mutex_);
UpdateLastAccessed();
if (stream_.IsValid()) {
// Decoder is already open. Return TRUE if the stream is the stream we have, or FALSE if not.
if (stream_ == stream) {
return true;
} else {
qWarning() << "Tried to open a decoder that was already open with another stream";
return false;
}
} else {
// Stream was not open, try opening it now
if (!stream.IsValid()) {
// Cannot open null stream
qCritical() << "Decoder attempted to open null stream";
return false;
}
if (!stream.Exists()) {
// Cannot open file that doesn't exist
qCritical() << "Decoder attempted to open file that doesn't exist";
return false;
}
// Set stream
stream_ = stream;
// Try open internal
if (OpenInternal()) {
return true;
} else {
// Unset stream
qCritical() << "Failed to open" << stream_.filename() << "stream" << stream_.stream();
CloseInternal();
stream_.Reset();
return false;
}
}
}
TexturePtr Decoder::RetrieveVideo(const RetrieveVideoParams &p)
{
QMutexLocker locker(&mutex_);
UpdateLastAccessed();
if (!stream_.IsValid()) {
qCritical() << "Can't retrieve video on a closed decoder";
return nullptr;
}
if (!SupportsVideo()) {
qCritical() << "Decoder doesn't support video";
return nullptr;
}
if (p.cancelled && p.cancelled->IsCancelled()) {
return nullptr;
}
if (cached_texture_ && cached_time_ == p.time && cached_divider_ == p.divider) {
return cached_texture_;
}
cached_texture_ = RetrieveVideoInternal(p);
cached_time_ = p.time;
cached_divider_ = p.divider;
return cached_texture_;
}
Decoder::RetrieveAudioStatus Decoder::RetrieveAudio(SampleBuffer &dest, const TimeRange &range, const AudioParams ¶ms, const QString& cache_path, LoopMode loop_mode, RenderMode::Mode mode)
{
QMutexLocker locker(&mutex_);
UpdateLastAccessed();
if (!stream_.IsValid()) {
qCritical() << "Can't retrieve audio on a closed decoder";
return kInvalid;
}
if (!SupportsAudio()) {
qCritical() << "Decoder doesn't support audio";
return kInvalid;
}
// Get conform state from ConformManager
ConformManager::Conform conform = ConformManager::instance()->GetConformState(id(), cache_path, stream_, params, (mode == RenderMode::kOnline));
if (conform.state == ConformManager::kConformGenerating) {
// If we need the task, it's available in `conform.task`
return kWaitingForConform;
}
// See if we got the conform
if (RetrieveAudioFromConform(dest, conform.filenames, range, loop_mode, params)) {
return kOK;
} else {
return kUnknownError;
}
}
qint64 Decoder::GetLastAccessedTime()
{
return last_accessed_;
}
void Decoder::Close()
{
QMutexLocker locker(&mutex_);
UpdateLastAccessed();
cached_texture_ = nullptr;
if (stream_.IsValid()) {
CloseInternal();
stream_.Reset();
} else {
qWarning() << "Tried to close a decoder that wasn't open";
}
}
bool Decoder::ConformAudio(const QVector<QString> &output_filenames, const AudioParams ¶ms, CancelAtom *cancelled)
{
return ConformAudioInternal(output_filenames, params, cancelled);
}
/*
* DECODER STATIC PUBLIC MEMBERS
*/
QVector<DecoderPtr> Decoder::ReceiveListOfAllDecoders()
{
QVector<DecoderPtr> decoders;
// The order in which these decoders are added is their priority when probing. Hence FFmpeg should usually be last,
// since it supports so many formats and we presumably want to override those formats with a more specific decoder.
decoders.append(std::make_shared<OIIODecoder>());
decoders.append(std::make_shared<FFmpegDecoder>());
return decoders;
}
DecoderPtr Decoder::CreateFromID(const QString &id)
{
if (id.isEmpty()) {
return nullptr;
}
// Create list to iterate through
QVector<DecoderPtr> decoder_list = ReceiveListOfAllDecoders();
foreach (DecoderPtr d, decoder_list) {
if (d->id() == id) {
return d;
}
}
return nullptr;
}
void Decoder::SignalProcessingProgress(int64_t ts, int64_t duration)
{
if (duration != AV_NOPTS_VALUE && duration != 0) {
emit IndexProgress(static_cast<double>(ts) / static_cast<double>(duration));
}
}
QString Decoder::TransformImageSequenceFileName(const QString &filename, const int64_t& number)
{
int digit_count = GetImageSequenceDigitCount(filename);
QFileInfo file_info(filename);
QString original_basename = file_info.completeBaseName();
QString new_basename = original_basename.left(original_basename.size() - digit_count)
.append(QStringLiteral("%1").arg(number, digit_count, 10, QChar('0')));
return file_info.dir().filePath(file_info.fileName().replace(original_basename, new_basename));
}
int Decoder::GetImageSequenceDigitCount(const QString &filename)
{
QString basename = QFileInfo(filename).completeBaseName();
// See if basename contains a number at the end
int digit_count = 0;
for (int i=basename.size()-1;i>=0;i--) {
if (basename.at(i).isDigit()) {
digit_count++;
} else {
break;
}
}
return digit_count;
}
int64_t Decoder::GetImageSequenceIndex(const QString &filename)
{
int digit_count = GetImageSequenceDigitCount(filename);
QFileInfo file_info(filename);
QString original_basename = file_info.completeBaseName();
QString number_only = original_basename.mid(original_basename.size() - digit_count);
return number_only.toLongLong();
}
TexturePtr Decoder::RetrieveVideoInternal(const RetrieveVideoParams &p)
{
Q_UNUSED(p)
return nullptr;
}
bool Decoder::ConformAudioInternal(const QVector<QString> &filenames, const AudioParams ¶ms, CancelAtom *cancelled)
{
Q_UNUSED(filenames)
Q_UNUSED(cancelled)
Q_UNUSED(params)
return false;
}
bool Decoder::RetrieveAudioFromConform(SampleBuffer &sample_buffer, const QVector<QString> &conform_filenames, TimeRange range, LoopMode loop_mode, const AudioParams &input_params)
{
PlanarFileDevice input;
if (input.open(conform_filenames, QFile::ReadOnly)) {
// Offset range by audio start offset
range -= GetAudioStartOffset();
qint64 read_index = input_params.time_to_bytes(range.in()) / input_params.channel_count();
qint64 write_index = 0;
const qint64 buffer_length_in_bytes = sample_buffer.sample_count() * input_params.bytes_per_sample_per_channel();
while (write_index < buffer_length_in_bytes) {
if (loop_mode == LoopMode::kLoopModeLoop) {
while (read_index >= input.size()) {
read_index -= input.size();
}
while (read_index < 0) {
read_index += input.size();
}
}
qint64 write_count = 0;
if (read_index < 0) {
// Reading before 0, write silence here until audio data would actually start
write_count = qMin(-read_index, buffer_length_in_bytes);
sample_buffer.silence_bytes(write_index, write_index + write_count);
} else if (read_index >= input.size()) {
// Reading after data length, write silence until the end of the buffer
write_count = buffer_length_in_bytes - write_index;
sample_buffer.silence_bytes(write_index, write_index + write_count);
} else {
write_count = qMin(input.size() - read_index, buffer_length_in_bytes - write_index);
input.seek(read_index);
input.read(reinterpret_cast<char**>(sample_buffer.to_raw_ptrs().data()), write_count, write_index);
}
read_index += write_count;
write_index += write_count;
}
input.close();
return true;
}
return false;
}
void Decoder::UpdateLastAccessed()
{
last_accessed_ = QDateTime::currentMSecsSinceEpoch();
}
uint qHash(Decoder::CodecStream stream, uint seed)
{
return qHash(stream.filename(), seed) ^ ::qHash(stream.stream(), seed) ^ qHash(stream.block(), seed);
}
}
| 9,221
|
C++
|
.cpp
| 267
| 30.685393
| 192
| 0.711051
|
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
|
18,955
|
frame.cpp
|
olive-editor_olive/app/codec/frame.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 "frame.h"
#include <OpenImageIO/imagebuf.h>
#include <QDebug>
#include <QtGlobal>
#include <QtMath>
#include "common/oiioutils.h"
#include "render/framemanager.h"
namespace olive {
Frame::Frame() :
data_(nullptr),
data_size_(0),
timestamp_(0)
{
}
Frame::~Frame()
{
destroy();
}
FramePtr Frame::Create()
{
return std::make_shared<Frame>();
}
const VideoParams &Frame::video_params() const
{
return params_;
}
void Frame::set_video_params(const VideoParams ¶ms)
{
params_ = params;
linesize_ = generate_linesize_bytes(width(), params_.format(), params_.channel_count());
linesize_pixels_ = linesize_ / params_.GetBytesPerPixel();
}
FramePtr Frame::Interlace(FramePtr top, FramePtr bottom)
{
if (top->video_params() != bottom->video_params()) {
qCritical() << "Tried to interlace two frames that had incompatible parameters";
return nullptr;
}
FramePtr interlaced = Frame::Create();
interlaced->set_video_params(top->video_params());
interlaced->allocate();
int linesize = interlaced->linesize_bytes();
for (int i=0; i<interlaced->height(); i++) {
FramePtr which = (i%2 == 0) ? top : bottom;
memcpy(interlaced->data() + i*linesize,
which->const_data() + i*linesize,
linesize);
}
return interlaced;
}
int Frame::generate_linesize_bytes(int width, PixelFormat format, int channel_count)
{
// Align to 32 bytes (not sure if this is necessary?)
return VideoParams::GetBytesPerPixel(format, channel_count) * ((width + 31) & ~31);
}
Color Frame::get_pixel(int x, int y) const
{
if (!contains_pixel(x, y)) {
return Color();
}
int byte_offset = y * linesize_bytes() + x * video_params().GetBytesPerPixel();
return Color(reinterpret_cast<const char*>(data_ + byte_offset), video_params().format(), video_params().channel_count());
}
bool Frame::contains_pixel(int x, int y) const
{
return (is_allocated() && x >= 0 && x < width() && y >= 0 && y < height());
}
void Frame::set_pixel(int x, int y, const Color &c)
{
if (!contains_pixel(x, y)) {
return;
}
int byte_offset = y * linesize_bytes() + x * video_params().GetBytesPerPixel();
c.toData(reinterpret_cast<char*>(data_ + byte_offset), video_params().format(), video_params().channel_count());
}
bool Frame::allocate()
{
// Assume this frame is intended to be a video frame
if (!params_.is_valid()) {
qWarning() << "Tried to allocate a frame with invalid parameters";
return false;
}
if (is_allocated()) {
// Already allocated
return true;
}
data_size_ = linesize_ * height();
data_ = FrameManager::Allocate(data_size_);
return true;
}
void Frame::destroy()
{
if (is_allocated()) {
FrameManager::Deallocate(data_size_, data_);
data_size_ = 0;
data_ = nullptr;
}
}
FramePtr Frame::convert(PixelFormat format) const
{
// Create new params with destination format
VideoParams params = params_;
params.set_format(format);
// Create new frame
FramePtr converted = Frame::Create();
converted->set_video_params(params);
converted->set_timestamp(timestamp_);
converted->allocate();
// Do the conversion through OIIO for convenience
OIIO::ImageBuf src(OIIO::ImageSpec(width(), height(),
channel_count(),
OIIOUtils::GetOIIOBaseTypeFromFormat(this->format())));
OIIOUtils::FrameToBuffer(this, &src);
OIIO::ImageBuf dst(OIIO::ImageSpec(converted->width(), converted->height(),
channel_count(),
OIIOUtils::GetOIIOBaseTypeFromFormat(format)));
if (dst.copy_pixels(src)) {
OIIOUtils::BufferToFrame(&dst, converted.get());
return converted;
} else {
return nullptr;
}
}
}
| 4,499
|
C++
|
.cpp
| 138
| 28.644928
| 124
| 0.682102
|
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
|
18,956
|
ffmpegencoder.cpp
|
olive-editor_olive/app/codec/ffmpeg/ffmpegencoder.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 "ffmpegencoder.h"
extern "C" {
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/pixdesc.h>
}
#include <QFile>
#include "common/ffmpegutils.h"
namespace olive {
FFmpegEncoder::FFmpegEncoder(const EncodingParams ¶ms) :
Encoder(params),
fmt_ctx_(nullptr),
video_stream_(nullptr),
video_codec_ctx_(nullptr),
video_scale_ctx_(nullptr),
video_buffersrc_ctx_(nullptr),
video_buffersink_ctx_(nullptr),
audio_stream_(nullptr),
audio_codec_ctx_(nullptr),
audio_resample_ctx_(nullptr),
audio_frame_(nullptr),
open_(false)
{
}
QStringList FFmpegEncoder::GetPixelFormatsForCodec(ExportCodec::Codec c) const
{
QStringList pix_fmts;
const AVCodec* codec_info = GetEncoder(c, SampleFormat::INVALID);
if (codec_info) {
for (int i=0; codec_info->pix_fmts[i]!=-1; i++) {
if (FFmpegUtils::ConvertJPEGSpaceToRegularSpace(codec_info->pix_fmts[i]) != codec_info->pix_fmts[i]) {
// This is a deprecated "JPEG" space, skip it
continue;
}
const char* pix_fmt_name = av_get_pix_fmt_name(codec_info->pix_fmts[i]);
pix_fmts.append(pix_fmt_name);
}
}
return pix_fmts;
}
std::vector<SampleFormat> FFmpegEncoder::GetSampleFormatsForCodec(ExportCodec::Codec c) const
{
std::vector<SampleFormat> f;
if (c == ExportCodec::kCodecPCM) {
// FFmpeg lists these as separate codecs so we need custom functionality here
// We list signed 16 first because ExportDialog will always use the first element by default
// (because first element is the "default" in tFFmpeg)
f = {
SampleFormat::S16,
SampleFormat::U8,
SampleFormat::S32,
SampleFormat::S64,
SampleFormat::F32,
SampleFormat::F64
};
} else {
const AVCodec* codec_info = GetEncoder(c, SampleFormat::INVALID);
if (codec_info && codec_info->sample_fmts) {
for (int i=0; codec_info->sample_fmts[i]!=-1; i++) {
SampleFormat this_format = FFmpegUtils::GetNativeSampleFormat(static_cast<AVSampleFormat>(codec_info->sample_fmts[i]));
if (this_format != SampleFormat::INVALID) {
f.push_back(this_format);
}
}
}
}
return f;
}
bool FFmpegEncoder::Open()
{
if (open_) {
return true;
}
int error_code;
// Convert QString to C string that FFmpeg expects
QByteArray filename_bytes = params().filename().toUtf8();
const char* filename_c_str = filename_bytes.constData();
// Create output format context
error_code = avformat_alloc_output_context2(&fmt_ctx_, nullptr, nullptr, filename_c_str);
// Check error code
if (error_code < 0) {
FFmpegError(tr("Failed to allocate output context"), error_code);
return false;
}
// Initialize a video stream if it's enabled
if (params().video_enabled()) {
if (!InitializeStream(AVMEDIA_TYPE_VIDEO, &video_stream_, &video_codec_ctx_, params().video_codec())) {
return false;
}
// This is the format we will expect frames received in Write() to be in
PixelFormat native_pixel_fmt = params().video_params().format();
// This is the format we will need to convert the frame to for swscale to understand it
video_conversion_fmt_ = FFmpegUtils::GetCompatiblePixelFormat(native_pixel_fmt);
// This is the equivalent pixel format above as an AVPixelFormat that swscale can understand
AVPixelFormat src_alpha_pix_fmt = FFmpegUtils::GetFFmpegPixelFormat(video_conversion_fmt_,
VideoParams::kRGBAChannelCount);
AVPixelFormat src_noalpha_pix_fmt = FFmpegUtils::GetFFmpegPixelFormat(video_conversion_fmt_,
VideoParams::kRGBChannelCount);
if (src_alpha_pix_fmt == AV_PIX_FMT_NONE || src_noalpha_pix_fmt == AV_PIX_FMT_NONE) {
SetError(tr("Failed to find suitable pixel format for this buffer"));
return false;
}
// This is the pixel format the encoder wants to encode to
AVPixelFormat encoder_pix_fmt = video_codec_ctx_->pix_fmt;
video_scale_ctx_ = avfilter_graph_alloc();
if (!video_scale_ctx_) {
return false;
}
static const int FILTER_ARG_SZ = 1024;
char filter_args[FILTER_ARG_SZ];
snprintf(filter_args, FILTER_ARG_SZ, "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
params().video_params().effective_width(),
params().video_params().effective_height(),
src_alpha_pix_fmt,
params().video_params().time_base().numerator(),
params().video_params().time_base().denominator(),
params().video_params().pixel_aspect_ratio().numerator(),
params().video_params().pixel_aspect_ratio().denominator());
avfilter_graph_create_filter(&video_buffersrc_ctx_, avfilter_get_by_name("buffer"), "in", filter_args, nullptr, video_scale_ctx_);
avfilter_graph_create_filter(&video_buffersink_ctx_, avfilter_get_by_name("buffersink"), "out", nullptr, nullptr, video_scale_ctx_);
AVFilterContext *last_filter = video_buffersrc_ctx_;
{
// Set color range
AVFilterContext* range_filter;
snprintf(filter_args, FILTER_ARG_SZ, "in_range=full:out_range=%s",
params().video_params().color_range() == VideoParams::kColorRangeFull ? "full" : "limited");
avfilter_graph_create_filter(&range_filter, avfilter_get_by_name("scale"), "range", filter_args, nullptr, video_scale_ctx_);
avfilter_link(last_filter, 0, range_filter, 0);
last_filter = range_filter;
}
if (src_alpha_pix_fmt != encoder_pix_fmt) {
// Transform pixel format
AVFilterContext* format_filter;
snprintf(filter_args, FILTER_ARG_SZ, "pix_fmts=%u", encoder_pix_fmt);
avfilter_graph_create_filter(&format_filter, avfilter_get_by_name("format"), "format", filter_args, nullptr, video_scale_ctx_);
avfilter_link(last_filter, 0, format_filter, 0);
last_filter = format_filter;
}
avfilter_link(last_filter, 0, video_buffersink_ctx_, 0);
if (avfilter_graph_config(video_scale_ctx_, nullptr) < 0) {
SetError(tr("Failed to configure filter graph"));
return false;
}
}
// Initialize an audio stream if it's enabled
if (params().audio_enabled()) {
if (!InitializeStream(AVMEDIA_TYPE_AUDIO, &audio_stream_, &audio_codec_ctx_, params().audio_codec())) {
return false;
}
}
// Initialize a subtitle stream if it's enabled
if (params().subtitles_enabled()) {
if (!InitializeStream(AVMEDIA_TYPE_SUBTITLE, &subtitle_stream_, &subtitle_codec_ctx_, params().subtitles_codec())) {
return false;
}
}
av_dump_format(fmt_ctx_, 0, filename_c_str, 1);
// Open output file for writing
error_code = avio_open(&fmt_ctx_->pb, filename_c_str, AVIO_FLAG_WRITE);
if (error_code < 0) {
FFmpegError(tr("Failed to open IO context"), error_code);
return false;
}
// Write header
error_code = avformat_write_header(fmt_ctx_, nullptr);
if (error_code < 0) {
FFmpegError(tr("Failed to write format header"), error_code);
return false;
}
open_ = true;
return true;
}
bool FFmpegEncoder::WriteFrame(FramePtr frame, rational time)
{
// We may need to convert this frame to a frame that swscale will understand
if (frame->format() != video_conversion_fmt_) {
frame = frame->convert(video_conversion_fmt_);
}
// Use swscale context to convert formats/linesizes
AVFramePtr input_frame = CreateAVFramePtr(av_frame_alloc());
input_frame->width = frame->width();
input_frame->height = frame->height();
input_frame->format = FFmpegUtils::GetFFmpegPixelFormat(frame->format(), frame->channel_count());
input_frame->data[0] = reinterpret_cast<uint8_t*>(frame->data());
input_frame->linesize[0] = frame->linesize_bytes();
input_frame->color_primaries = video_codec_ctx_->color_primaries;
input_frame->color_trc = video_codec_ctx_->color_trc;
input_frame->colorspace = video_codec_ctx_->colorspace;
input_frame->color_range = video_codec_ctx_->color_range;
int r;
r = av_buffersrc_add_frame_flags(video_buffersrc_ctx_, input_frame.get(), AV_BUFFERSRC_FLAG_KEEP_REF);
if (r < 0) {
FFmpegError(tr("Failed to add frame to filter graph"), r);
return false;
}
AVFramePtr encoded_frame = CreateAVFramePtr(av_frame_alloc());
r = av_buffersink_get_frame(video_buffersink_ctx_, encoded_frame.get());
if (r < 0) {
FFmpegError(tr("Failed to retrieve frame from buffer sink"), r);
return false;
}
encoded_frame->pts = qRound64(time.toDouble() / av_q2d(video_codec_ctx_->time_base));
return WriteAVFrame(encoded_frame.get(), video_codec_ctx_, video_stream_);
}
bool FFmpegEncoder::WriteAudio(const SampleBuffer &audio)
{
if (!audio.is_allocated()) {
return true;
}
bool result = true;
size_t start = 0;
size_t end = audio.sample_count();
const size_t max_frame = 48000;
while (result && start < end) {
// Create input buffer
uint8_t** input_data = nullptr;
size_t input_sample_count = std::min(end - start, max_frame);
int input_linesize;
int r = av_samples_alloc_array_and_samples(&input_data, &input_linesize, audio.audio_params().channel_count(),
input_sample_count, FFmpegUtils::GetFFmpegSampleFormat(audio.audio_params().format()), 0);
if (r < 0) {
FFmpegError(tr("Failed to allocate sample array"), r);
return false;
} else {
int bpsc = audio.audio_params().bytes_per_sample_per_channel();
for (int i=0; i<audio.audio_params().channel_count(); i++) {
memcpy(input_data[i], audio.data(i) + start, input_sample_count * bpsc);
}
start += input_sample_count;
}
result = WriteAudioData(audio.audio_params().is_valid() ? audio.audio_params() : params().audio_params(), const_cast<const uint8_t**>(input_data), input_sample_count);
if (input_data) {
av_freep(&input_data[0]);
av_freep(&input_data);
}
}
return result;
}
bool FFmpegEncoder::WriteAudioData(const AudioParams &audio_params, const uint8_t **input_data, int input_sample_count)
{
if (!InitializeResampleContext(audio_params)) {
qCritical() << "Failed to initialize resample context";
return false;
}
bool result = true;
// Create output buffer
int output_sample_count = input_sample_count ? swr_get_out_samples(audio_resample_ctx_, input_sample_count) : 102400;
uint8_t** output_data = nullptr;
int output_linesize;
av_samples_alloc_array_and_samples(&output_data, &output_linesize, audio_stream_->codecpar->channels,
output_sample_count, static_cast<AVSampleFormat>(audio_stream_->codecpar->format), 0);
// Perform conversion
int converted = swr_convert(audio_resample_ctx_, output_data, output_sample_count, const_cast<const uint8_t**>(input_data), input_sample_count);
if (converted > 0) {
// Split sample buffer into frames
for (int i=0; i<converted; ) {
int frame_remaining_samples = audio_max_samples_ - audio_frame_offset_;
int converted_remaining_samples = converted - i;
int copy_length = qMin(frame_remaining_samples, converted_remaining_samples);
av_samples_copy(audio_frame_->data, output_data, audio_frame_offset_, i,
copy_length,
audio_frame_->channels, static_cast<AVSampleFormat>(audio_frame_->format));
audio_frame_offset_ += copy_length;
i += copy_length;
if (audio_frame_offset_ == audio_max_samples_ || (i == converted && !input_data)) {
// Got all the samples we needed, write the frame
audio_frame_->pts = av_rescale_q(audio_write_count_, {1, audio_codec_ctx_->sample_rate}, audio_codec_ctx_->time_base);
WriteAVFrame(audio_frame_, audio_codec_ctx_, audio_stream_);
audio_write_count_ += audio_frame_offset_;
audio_frame_offset_ = 0;
}
}
} else if (converted < 0) {
FFmpegError(tr("Failed to resample audio"), converted);
result = false;
}
if (!input_data && audio_frame_offset_ > 0) {
audio_frame_->nb_samples = audio_frame_offset_;
audio_frame_->pts = av_rescale_q(audio_write_count_, {1, audio_codec_ctx_->sample_rate}, audio_codec_ctx_->time_base);
WriteAVFrame(audio_frame_, audio_codec_ctx_, audio_stream_);
}
// Free buffers created
if (output_data) {
av_freep(&output_data[0]);
av_freep(&output_data);
}
return result;
}
QString GetAssTime(const rational &time)
{
int64_t total_centiseconds = qRound64(time.toDouble() * 100);
int64_t cs = total_centiseconds % 100;
int64_t ss = (total_centiseconds / 100) % 60;
int64_t mm = (total_centiseconds / 6000) % 60;
int64_t hh = total_centiseconds / 360000;
return QStringLiteral("%1:%2:%3.%4").arg(
QString::number(hh),
QStringLiteral("%1").arg(mm, 2, 10, QLatin1Char('0')),
QStringLiteral("%1").arg(ss, 2, 10, QLatin1Char('0')),
QStringLiteral("%1").arg(cs, 2, 10, QLatin1Char('0'))
);
}
bool FFmpegEncoder::WriteSubtitle(const SubtitleBlock *sub_block)
{
QByteArray utf8_sub = sub_block->GetText().toUtf8();
AVPacket *pkt = av_packet_alloc();
pkt->stream_index = subtitle_stream_->index;
pkt->data = (uint8_t *) utf8_sub.data();
pkt->size = utf8_sub.size();
pkt->pts = Timecode::time_to_timestamp(sub_block->in(), subtitle_codec_ctx_->time_base, Timecode::kFloor);
pkt->duration = av_rescale_q(qRound64(sub_block->length().toDouble() * 1000), {1, 1000}, subtitle_codec_ctx_->time_base);
pkt->dts = pkt->pts;
av_packet_rescale_ts(pkt, subtitle_codec_ctx_->time_base, subtitle_stream_->time_base);
int err = av_interleaved_write_frame(fmt_ctx_, pkt);
bool ret = true;
if (err < 0) {
FFmpegError(tr("Failed to write interleaved packet"), err);
ret = false;
}
av_packet_free(&pkt);
return ret;
}
/*
void FFmpegEncoder::WriteAudio(AudioParams pcm_info, QIODevice* file)
{
// Keep track of sample count to use as each frame's timebase
int sample_counter = 0;
while (true) {
// Calculate how many samples should input this frame
int64_t samples_needed = av_rescale_rnd(maximum_frame_samples + swr_get_delay(swr_ctx, pcm_info.sample_rate()),
audio_codec_ctx_->sample_rate,
pcm_info.sample_rate(),
AV_ROUND_UP);
// Calculate how many bytes this is
int max_read = pcm_info.samples_to_bytes(samples_needed);
// Read bytes from PCM
QByteArray input_data = file->read(max_read);
// Use swresample to convert the data into the correct format
const char* input_data_array = input_data.constData();
int converted = swr_convert(swr_ctx,
// output data
frame->data,
// output sample count (maximum amount of samples in output)
maximum_frame_samples,
// input data
reinterpret_cast<const uint8_t**>(&input_data_array),
// input sample count (maximum amount of samples we read from pcm file)
pcm_info.bytes_to_samples(input_data.size()));
// Update the frame's number of samples to the amount we actually received
frame->nb_samples = converted;
// Update frame timestamp
frame->pts = sample_counter;
// Increment timestamp for the next frame by the amount of samples in this one
sample_counter += converted;
// Write the frame
if (!WriteAVFrame(frame, audio_codec_ctx_, audio_stream_)) {
qCritical() << "Failed to write audio AVFrame";
break;
}
// Break if we've reached the end point
if (file->atEnd()) {
break;
}
}
}
*/
void FFmpegEncoder::Close()
{
if (open_) {
// Flush encoders
FlushEncoders();
// We've written a header, so we'll write a trailer
av_write_trailer(fmt_ctx_);
avio_closep(&fmt_ctx_->pb);
open_ = false;
}
if (audio_resample_ctx_) {
swr_init(audio_resample_ctx_);
audio_resample_ctx_ = nullptr;
}
if (audio_frame_) {
av_frame_free(&audio_frame_);
audio_frame_ = nullptr;
}
if (video_scale_ctx_) {
avfilter_graph_free(&video_scale_ctx_);
video_scale_ctx_ = nullptr;
video_buffersrc_ctx_ = nullptr;
video_buffersink_ctx_ = nullptr;
}
if (video_codec_ctx_) {
avcodec_free_context(&video_codec_ctx_);
video_codec_ctx_ = nullptr;
}
if (audio_codec_ctx_) {
avcodec_free_context(&audio_codec_ctx_);
audio_codec_ctx_ = nullptr;
}
if (fmt_ctx_) {
// NOTE: This also frees video_stream_ and audio_stream_
avformat_free_context(fmt_ctx_);
fmt_ctx_ = nullptr;
video_stream_ = nullptr;
audio_stream_ = nullptr;
}
}
void FFmpegEncoder::FFmpegError(const QString& context, int error_code)
{
char err[1024];
av_strerror(error_code, err, 1024);
QString formatted_err = tr("%1: %2 %3").arg(context, err, QString::number(error_code));
qDebug() << formatted_err;
SetError(formatted_err);
}
bool FFmpegEncoder::WriteAVFrame(AVFrame *frame, AVCodecContext* codec_ctx, AVStream* stream)
{
// Send raw frame to the encoder
int error_code = avcodec_send_frame(codec_ctx, frame);
if (error_code < 0) {
FFmpegError(tr("Failed to send frame to encoder"), error_code);
return false;
}
bool succeeded = false;
AVPacket* pkt = av_packet_alloc();
// Retrieve packets from encoder
while (error_code >= 0) {
error_code = avcodec_receive_packet(codec_ctx, pkt);
// EAGAIN just means the encoder wants another frame before encoding
if (error_code == AVERROR(EAGAIN)) {
break;
} else if (error_code < 0) {
FFmpegError(tr("Failed to receive packet from decoder"), error_code);
goto fail;
}
// Set packet stream index
pkt->stream_index = stream->index;
av_packet_rescale_ts(pkt, codec_ctx->time_base, stream->time_base);
// Write packet to file
error_code = av_interleaved_write_frame(fmt_ctx_, pkt);
if (error_code < 0) {
FFmpegError(tr("Failed to write interleaved packet"), error_code);
goto fail;
}
// Unref packet in case we're getting another
av_packet_unref(pkt);
}
succeeded = true;
fail:
av_packet_free(&pkt);
return succeeded;
}
bool FFmpegEncoder::InitializeStream(AVMediaType type, AVStream** stream_ptr, AVCodecContext** codec_ctx_ptr, const ExportCodec::Codec& codec)
{
if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO && type != AVMEDIA_TYPE_SUBTITLE) {
SetError(tr("Cannot initialize a stream that is not a video, audio, or subtitle type"));
return false;
}
// Find encoder
const AVCodec* encoder = GetEncoder(codec, params().audio_params().format());
if (!encoder) {
SetError(tr("Failed to find codec for 0x%1").arg(codec, 16));
return false;
}
if (encoder->type != type) {
SetError(tr("Retrieved unexpected codec type %1 for codec %2").arg(QString::number(encoder->type), QString::number(codec)));
return false;
}
if (!InitializeCodecContext(stream_ptr, codec_ctx_ptr, encoder)) {
return false;
}
// Set codec parameters
AVCodecContext* codec_ctx = *codec_ctx_ptr;
AVStream* stream = *stream_ptr;
if (type == AVMEDIA_TYPE_VIDEO) {
codec_ctx->width = params().video_params().width();
codec_ctx->height = params().video_params().height();
codec_ctx->sample_aspect_ratio = params().video_params().pixel_aspect_ratio().toAVRational();
codec_ctx->time_base = params().video_params().frame_rate_as_time_base().toAVRational();
codec_ctx->framerate = params().video_params().frame_rate().toAVRational();
codec_ctx->pix_fmt = av_get_pix_fmt(params().video_pix_fmt().toUtf8());
codec_ctx->color_range = params().video_params().color_range() == VideoParams::kColorRangeFull ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (params().video_params().interlacing() != VideoParams::kInterlaceNone) {
// FIXME: I actually don't know what these flags do, the documentation helpfully doesn't
// explain them at all. I hope using both of them is the right thing to do.
codec_ctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME;
if (params().video_params().interlacing() == VideoParams::kInterlacedTopFirst) {
codec_ctx->field_order = AV_FIELD_TT;
} else {
codec_ctx->field_order = AV_FIELD_BB;
if (codec == ExportCodec::kCodecH264 || codec == ExportCodec::kCodecH264rgb) {
// For some reason, FFmpeg doesn't set libx264's bff flag so we have to do it ourselves
av_opt_set(codec_ctx->priv_data, "x264opts", "bff=1", AV_OPT_SEARCH_CHILDREN);
}
}
}
// Set custom options
{
for (auto i=params().video_opts().begin();i!=params().video_opts().end();i++) {
if (!i.key().startsWith(QStringLiteral("ove_"))) {
av_opt_set(codec_ctx->priv_data, i.key().toUtf8(), i.value().toUtf8(), AV_OPT_SEARCH_CHILDREN);
}
}
if (params().video_bit_rate() > 0) {
codec_ctx->bit_rate = params().video_bit_rate();
}
if (params().video_min_bit_rate() > 0) {
codec_ctx->rc_min_rate = params().video_min_bit_rate();
}
if (params().video_max_bit_rate() > 0) {
codec_ctx->rc_max_rate = params().video_max_bit_rate();
}
if (params().video_buffer_size() > 0) {
codec_ctx->rc_buffer_size = static_cast<int>(params().video_buffer_size());
}
// nclc tags. See https://ffmpeg.org/doxygen/4.0/pixfmt_8h.html#ad384ee5a840bafd73daef08e6d9cafe7
// ffprobe -v error -show_format -show_streams "C:\Users\Tom\Documents\srgb correct tags.mov"
if (params().color_transform().output().contains(QStringLiteral("sRGB"), Qt::CaseInsensitive)) {
codec_ctx->color_primaries = AVCOL_PRI_BT709;
codec_ctx->color_trc = AVCOL_TRC_IEC61966_2_1;
codec_ctx->colorspace = AVCOL_SPC_BT709;
} else { // Assume Rec.709
codec_ctx->color_primaries = AVCOL_PRI_BT709;
codec_ctx->color_trc = AVCOL_TRC_BT709;
codec_ctx->colorspace = AVCOL_SPC_BT709;
}
}
} else if (type == AVMEDIA_TYPE_AUDIO) {
// Assume audio stream
codec_ctx->sample_rate = params().audio_params().sample_rate();
codec_ctx->channel_layout = params().audio_params().channel_layout();
codec_ctx->channels = av_get_channel_layout_nb_channels(codec_ctx->channel_layout);
codec_ctx->sample_fmt = FFmpegUtils::GetFFmpegSampleFormat(params().audio_params().format());
codec_ctx->time_base = {1, codec_ctx->sample_rate};
if (params().audio_bit_rate() > 0) {
codec_ctx->bit_rate = params().audio_bit_rate();
}
} else if (type == AVMEDIA_TYPE_SUBTITLE) {
codec_ctx->time_base = av_get_time_base_q();
QByteArray ass_header = SubtitleParams::GenerateASSHeader().toUtf8();
codec_ctx->subtitle_header = new uint8_t[ass_header.size()];
memcpy(codec_ctx->subtitle_header, ass_header.constData(), ass_header.size());
codec_ctx->subtitle_header_size = ass_header.size();
}
if (!SetupCodecContext(stream, codec_ctx, encoder)) {
return false;
}
return true;
}
bool FFmpegEncoder::InitializeCodecContext(AVStream **stream, AVCodecContext **codec_ctx, const AVCodec* codec)
{
*stream = avformat_new_stream(fmt_ctx_, nullptr);
if (!(*stream)) {
SetError(tr("Failed to allocate AVStream"));
return false;
}
// Allocate a codec context
*codec_ctx = avcodec_alloc_context3(codec);
if (!(*codec_ctx)) {
SetError(tr("Failed to allocate AVCodecContext"));
return false;
}
return true;
}
bool FFmpegEncoder::SetupCodecContext(AVStream* stream, AVCodecContext* codec_ctx, const AVCodec* codec)
{
int error_code;
if (fmt_ctx_->oformat->flags & AVFMT_GLOBALHEADER) {
codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
AVDictionary* codec_opts = nullptr;
// Set thread count
if (params().video_threads() == 0) {
av_dict_set(&codec_opts, "threads", "auto", 0);
} else {
QString thread_val = QString::number(params().video_threads());
av_dict_set(&codec_opts, "threads", thread_val.toUtf8(), 0);
}
// Try to open encoder
error_code = avcodec_open2(codec_ctx, codec, &codec_opts);
if (error_code < 0) {
FFmpegError(tr("Failed to open encoder"), error_code);
return false;
}
// Copy context settings to codecpar object
error_code = avcodec_parameters_from_context(stream->codecpar, codec_ctx);
if (error_code < 0) {
FFmpegError(tr("Failed to copy codec parameters to stream"), error_code);
return false;
}
if (codec->type == AVMEDIA_TYPE_VIDEO) {
stream->avg_frame_rate = codec_ctx->framerate;
}
return true;
}
void FFmpegEncoder::FlushEncoders()
{
if (video_codec_ctx_) {
FlushCodecCtx(video_codec_ctx_, video_stream_);
}
if (audio_codec_ctx_) {
WriteAudio(SampleBuffer());
FlushCodecCtx(audio_codec_ctx_, audio_stream_);
}
if (fmt_ctx_) {
if (fmt_ctx_->oformat->flags & AVFMT_ALLOW_FLUSH) {
int r = av_interleaved_write_frame(fmt_ctx_, nullptr);
if (r < 0) {
FFmpegError(tr("Failed to write interleaved packet"), r);
}
}
}
}
void FFmpegEncoder::FlushCodecCtx(AVCodecContext *codec_ctx, AVStream* stream)
{
avcodec_send_frame(codec_ctx, nullptr);
AVPacket* pkt = av_packet_alloc();
int error_code;
do {
error_code = avcodec_receive_packet(codec_ctx, pkt);
if (error_code < 0) {
break;
}
pkt->stream_index = stream->index;
av_packet_rescale_ts(pkt, codec_ctx->time_base, stream->time_base);
int r = av_interleaved_write_frame(fmt_ctx_, pkt);
if (r < 0) {
FFmpegError(tr("Failed to write interleaved packet"), r);
break;
}
av_packet_unref(pkt);
} while (error_code >= 0);
av_packet_free(&pkt);
}
bool FFmpegEncoder::InitializeResampleContext(const AudioParams &audio)
{
if (audio_resample_ctx_) {
return true;
}
// Create resample context
audio_resample_ctx_ = swr_alloc_set_opts(nullptr,
static_cast<int64_t>(audio_codec_ctx_->channel_layout),
audio_codec_ctx_->sample_fmt,
audio_codec_ctx_->sample_rate,
static_cast<int64_t>(audio.channel_layout()),
FFmpegUtils::GetFFmpegSampleFormat(audio.format()),
audio.sample_rate(),
0,
nullptr);
if (!audio_resample_ctx_) {
return false;
}
int err = swr_init(audio_resample_ctx_);
if (err < 0) {
FFmpegError(tr("Failed to create resampling context"), err);
return false;
}
audio_max_samples_ = audio_codec_ctx_->frame_size;
if (!audio_max_samples_) {
// If not, use another frame size
if (params().video_enabled()) {
// If we're encoding video, use enough samples to cover roughly one frame of video
audio_max_samples_ = params().audio_params().time_to_samples(params().video_params().frame_rate_as_time_base());
} else {
// If no video, just use an arbitrary number
audio_max_samples_ = 256;
}
}
audio_frame_ = av_frame_alloc();
if (!audio_frame_) {
return false;
}
audio_frame_->channel_layout = audio_codec_ctx_->channel_layout;
audio_frame_->format = audio_codec_ctx_->sample_fmt;
audio_frame_->nb_samples = audio_max_samples_;
err = av_frame_get_buffer(audio_frame_, 0);
if (err < 0) {
FFmpegError(tr("Failed to create audio frame"), err);
return false;
}
audio_frame_offset_ = 0;
audio_write_count_ = 0;
return true;
}
const AVCodec *FFmpegEncoder::GetEncoder(ExportCodec::Codec c, SampleFormat aformat)
{
switch (c) {
case ExportCodec::kCodecH264:
return avcodec_find_encoder_by_name("libx264");
case ExportCodec::kCodecH264rgb:
return avcodec_find_encoder_by_name("libx264rgb");
case ExportCodec::kCodecDNxHD:
return avcodec_find_encoder(AV_CODEC_ID_DNXHD);
case ExportCodec::kCodecProRes:
return avcodec_find_encoder(AV_CODEC_ID_PRORES);
case ExportCodec::kCodecCineform:
return avcodec_find_encoder(AV_CODEC_ID_CFHD);
case ExportCodec::kCodecH265:
return avcodec_find_encoder(AV_CODEC_ID_HEVC);
case ExportCodec::kCodecVP9:
return avcodec_find_encoder(AV_CODEC_ID_VP9);
case ExportCodec::kCodecAV1: {
const AVCodec *encoder = avcodec_find_encoder_by_name("libsvtav1");
if(!encoder)
encoder = avcodec_find_encoder(AV_CODEC_ID_AV1);
return encoder;
}
case ExportCodec::kCodecOpenEXR:
return avcodec_find_encoder(AV_CODEC_ID_EXR);
case ExportCodec::kCodecPNG:
return avcodec_find_encoder(AV_CODEC_ID_PNG);
case ExportCodec::kCodecTIFF:
return avcodec_find_encoder(AV_CODEC_ID_TIFF);
case ExportCodec::kCodecMP2:
return avcodec_find_encoder(AV_CODEC_ID_MP2);
case ExportCodec::kCodecMP3:
return avcodec_find_encoder(AV_CODEC_ID_MP3);
case ExportCodec::kCodecAAC:
return avcodec_find_encoder(AV_CODEC_ID_AAC);
case ExportCodec::kCodecPCM:
switch (aformat) {
case SampleFormat::INVALID:
case SampleFormat::COUNT:
case SampleFormat::U8P:
case SampleFormat::S16P:
case SampleFormat::S32P:
case SampleFormat::S64P:
case SampleFormat::F32P:
case SampleFormat::F64P:
break;
case SampleFormat::U8:
return avcodec_find_encoder(AV_CODEC_ID_PCM_U8);
case SampleFormat::S16:
return avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE);
case SampleFormat::S32:
return avcodec_find_encoder(AV_CODEC_ID_PCM_S32LE);
case SampleFormat::S64:
return avcodec_find_encoder(AV_CODEC_ID_PCM_S64LE);
case SampleFormat::F32:
return avcodec_find_encoder(AV_CODEC_ID_PCM_F32LE);
case SampleFormat::F64:
return avcodec_find_encoder(AV_CODEC_ID_PCM_F64LE);
}
break;
case ExportCodec::kCodecFLAC:
return avcodec_find_encoder(AV_CODEC_ID_FLAC);
case ExportCodec::kCodecOpus:
return avcodec_find_encoder(AV_CODEC_ID_OPUS);
case ExportCodec::kCodecVorbis:
return avcodec_find_encoder(AV_CODEC_ID_VORBIS);
case ExportCodec::kCodecSRT:
return avcodec_find_encoder(AV_CODEC_ID_SUBRIP);
case ExportCodec::kCodecCount:
// These are audio or invalid codecs and therefore have no pixel formats
break;
}
return nullptr;
}
}
| 31,499
|
C++
|
.cpp
| 772
| 34.952073
| 171
| 0.662726
|
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
|
18,957
|
ffmpegdecoder.cpp
|
olive-editor_olive/app/codec/ffmpeg/ffmpegdecoder.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 "ffmpegdecoder.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
}
#include <OpenImageIO/imagebuf.h>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <QtMath>
#include <QThread>
#include <QtConcurrent/QtConcurrent>
#include "codec/planarfiledevice.h"
#include "common/ffmpegutils.h"
#include "common/filefunctions.h"
#include "render/renderer.h"
#include "render/subtitleparams.h"
namespace olive {
QVariant Yuv2RgbShader;
QVariant DeinterlaceShader;
FFmpegDecoder::FFmpegDecoder() :
sws_ctx_(nullptr),
working_packet_(nullptr),
cache_at_zero_(false),
cache_at_eof_(false)
{
}
bool FFmpegDecoder::OpenInternal()
{
if (instance_.Open(stream().filename().toUtf8(), stream().stream())) {
AVStream* s = instance_.avstream();
// Store one second in the source's timebase
second_ts_ = qRound64(av_q2d(av_inv_q(s->time_base)));
working_packet_ = av_packet_alloc();
return true;
}
return false;
}
TexturePtr FFmpegDecoder::ProcessFrameIntoTexture(AVFramePtr f, const RetrieveVideoParams &p, const AVFramePtr original)
{
// Determine native format
AVPixelFormat ideal_fmt = FFmpegUtils::GetCompatiblePixelFormat(static_cast<AVPixelFormat>(f->format));
PixelFormat native_fmt = GetNativePixelFormat(ideal_fmt);
int native_channels = GetNativeChannelCount(ideal_fmt);
// Set up video params
VideoParams vp(original->width,
original->height,
native_fmt,
native_channels,
av_guess_sample_aspect_ratio(instance_.fmt_ctx(), instance_.avstream(), nullptr),
VideoParams::kInterlaceNone,
p.divider);
// Create texture
TexturePtr tex = p.renderer->CreateTexture(vp);
switch (f->format) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV444P12LE:
{
// Run through YUV to RGB shader
if (Yuv2RgbShader.isNull()) {
// Compile shader
Yuv2RgbShader = p.renderer->CreateNativeShader(ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/yuv2rgb.frag"))));
if (Yuv2RgbShader.isNull()) {
return nullptr;
}
}
int px_size;
int bits_per_pixel;
switch (f->format) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV444P:
default:
px_size = 1;
bits_per_pixel = 8;
break;
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV444P10LE:
px_size = 2;
bits_per_pixel = 10;
break;
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV444P12LE:
px_size = 2;
bits_per_pixel = 12;
break;
}
AVFrame *hw_in = f.get();
VideoParams plane_params = vp;
plane_params.set_channel_count(1);
plane_params.set_format(native_fmt);
TexturePtr y_plane = p.renderer->CreateTexture(plane_params, hw_in->data[0], hw_in->linesize[0] / px_size);
switch (f->format) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV422P12LE:
plane_params.set_width(plane_params.width()/2);
break;
}
switch (f->format) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV420P12LE:
plane_params.set_height(plane_params.height()/2);
break;
}
TexturePtr u_plane = p.renderer->CreateTexture(plane_params, hw_in->data[1], hw_in->linesize[1] / px_size);
TexturePtr v_plane = p.renderer->CreateTexture(plane_params, hw_in->data[2], hw_in->linesize[2] / px_size);
ShaderJob job;
job.Insert(QStringLiteral("y_channel"), NodeValue(NodeValue::kTexture, QVariant::fromValue(y_plane)));
job.Insert(QStringLiteral("u_channel"), NodeValue(NodeValue::kTexture, QVariant::fromValue(u_plane)));
job.Insert(QStringLiteral("v_channel"), NodeValue(NodeValue::kTexture, QVariant::fromValue(v_plane)));
job.Insert(QStringLiteral("bits_per_pixel"), NodeValue(NodeValue::kInt, bits_per_pixel));
job.Insert(QStringLiteral("full_range"), NodeValue(NodeValue::kBoolean, hw_in->color_range == AVCOL_RANGE_JPEG));
const int *yuv_coeffs = sws_getCoefficients(FFmpegUtils::GetSwsColorspaceFromAVColorSpace(hw_in->colorspace));
job.Insert(QStringLiteral("yuv_crv"), NodeValue(NodeValue::kFloat, yuv_coeffs[0]/65536.0));
job.Insert(QStringLiteral("yuv_cgu"), NodeValue(NodeValue::kFloat, yuv_coeffs[2]/65536.0));
job.Insert(QStringLiteral("yuv_cgv"), NodeValue(NodeValue::kFloat, yuv_coeffs[3]/65536.0));
job.Insert(QStringLiteral("yuv_cbu"), NodeValue(NodeValue::kFloat, yuv_coeffs[1]/65536.0));
tex = p.renderer->CreateTexture(vp);
p.renderer->BlitToTexture(Yuv2RgbShader, job, tex.get(), false);
break;
}
case AV_PIX_FMT_RGBA:
case AV_PIX_FMT_RGBA64LE:
// RGBA can be uploaded directly to the texture
tex->Upload(f->data[0], f->linesize[0] / vp.GetBytesPerPixel());
break;
}
// Deinterlace if necessary
if (p.src_interlacing != VideoParams::kInterlaceNone) {
if (DeinterlaceShader.isNull()) {
// Compile shader
DeinterlaceShader = p.renderer->CreateNativeShader(ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/deinterlace2.frag"))));
if (DeinterlaceShader.isNull()) {
return nullptr;
}
}
rational frame_rate_tb = av_guess_frame_rate(instance_.fmt_ctx(), instance_.avstream(), original.get());
// Double frame rate for interlaced fields
frame_rate_tb *= 2;
// Flip frame rate so it can be used as a timebase
frame_rate_tb.flip();
int64_t req = Timecode::time_to_timestamp(p.time + rational(instance_.fmt_ctx()->start_time, AV_TIME_BASE), frame_rate_tb);
int64_t frm = Timecode::rescale_timestamp(original->pts, instance_.avstream()->time_base, frame_rate_tb);
bool first = (req == frm);
bool top_first = (p.src_interlacing == VideoParams::kInterlacedTopFirst);
int interlacing = (first == top_first) ? 1 : 2;
TexturePtr deinterlaced = p.renderer->CreateTexture(tex->params());
ShaderJob job;
job.Insert(QStringLiteral("ove_maintex"), NodeValue(NodeValue::kTexture, tex));
job.Insert(QStringLiteral("interlacing"), NodeValue(NodeValue::kInt, interlacing));
job.Insert(QStringLiteral("pixel_height"), NodeValue(NodeValue::kInt, original->height));
p.renderer->BlitToTexture(DeinterlaceShader, job, deinterlaced.get(), false);
tex = deinterlaced;
}
return tex;
}
TexturePtr FFmpegDecoder::RetrieveVideoInternal(const RetrieveVideoParams &p)
{
if (AVFramePtr f = RetrieveFrame(p.time, p.cancelled)) {
if (p.cancelled && p.cancelled->IsCancelled()) {
return nullptr;
}
AVFramePtr original = f;
// Disregard "JPEG" pixel formats because we allow the user to override that
f->format = FFmpegUtils::ConvertJPEGSpaceToRegularSpace(static_cast<AVPixelFormat>(f->format));
// Force frame's color range to whatever it's set to in Olive
f->color_range = p.force_range == VideoParams::kColorRangeFull ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
// Perform any CPU processing required
f = PreProcessFrame(f, p);
if (!f) {
// Error occurred while software scaling
return nullptr;
}
// Finally, perform any GPU processing required
return ProcessFrameIntoTexture(f, p, original);
}
return nullptr;
}
void FFmpegDecoder::CloseInternal()
{
if (working_packet_) {
av_packet_free(&working_packet_);
working_packet_ = nullptr;
}
ClearFrameCache();
FreeScaler();
instance_.Close();
}
rational FFmpegDecoder::GetAudioStartOffset() const
{
auto f = instance_.fmt_ctx();
if (f) {
rational fmt_start = rational(instance_.fmt_ctx()->start_time, AV_TIME_BASE);
rational str_start = rational(instance_.avstream()->time_base) * instance_.avstream()->start_time;
return str_start - fmt_start;
} else {
return 0;
}
}
QString FFmpegDecoder::id() const
{
return QStringLiteral("ffmpeg");
}
FootageDescription FFmpegDecoder::Probe(const QString &filename, CancelAtom *cancelled) const
{
// Return value
FootageDescription desc(id());
// Variable for receiving errors from FFmpeg
int error_code;
// Convert QString to a C string
QByteArray filename_c = filename.toUtf8();
// Open file in a format context
AVFormatContext* fmt_ctx = nullptr;
error_code = avformat_open_input(&fmt_ctx, filename_c, nullptr, nullptr);
// Handle format context error
if (error_code == 0) {
// Retrieve metadata about the media
avformat_find_stream_info(fmt_ctx, nullptr);
int64_t footage_duration = fmt_ctx->duration;
bool duration_guessed_from_bitrate = (fmt_ctx->duration_estimation_method == AVFMT_DURATION_FROM_BITRATE);
if (duration_guessed_from_bitrate) {
qWarning() << "Unreliable duration detected - we will manually determine it ourselves (this may take some time)";
}
// Dump it into the Footage object
int video_streams = 0, audio_streams = 0, still_streams = 0;
for (unsigned int i=0;i<fmt_ctx->nb_streams;i++) {
// FFmpeg AVStream
AVStream* avstream = fmt_ctx->streams[i];
// Find decoder for this stream, if it exists we can proceed
const AVCodec* decoder = avcodec_find_decoder(avstream->codecpar->codec_id);
if (decoder
&& (avstream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
|| avstream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
|| avstream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
if (avstream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
AVPixelFormat compatible_pix_fmt = AV_PIX_FMT_NONE;
bool image_is_still = false;
rational pixel_aspect_ratio;
rational frame_rate;
VideoParams::Interlacing interlacing = VideoParams::kInterlaceNone;
{
// Read at least two frames to get more information about this video stream
AVPacket* pkt = av_packet_alloc();
AVFrame* frame = av_frame_alloc();
{
Instance instance;
instance.Open(filename_c, avstream->index);
// Read first frame and retrieve some metadata
if (instance.GetFrame(pkt, frame) >= 0) {
// Check if video is interlaced and what field dominance it has if so
if (frame->interlaced_frame) {
if (frame->top_field_first) {
interlacing = VideoParams::kInterlacedTopFirst;
} else {
interlacing = VideoParams::kInterlacedBottomFirst;
}
}
pixel_aspect_ratio = av_guess_sample_aspect_ratio(instance.fmt_ctx(),
instance.avstream(),
frame);
frame_rate = av_guess_frame_rate(instance.fmt_ctx(),
instance.avstream(),
frame);
compatible_pix_fmt = FFmpegUtils::GetCompatiblePixelFormat(static_cast<AVPixelFormat>(avstream->codecpar->format));
}
// Read second frame
int ret = instance.GetFrame(pkt, frame);
if (ret >= 0) {
// Check if we need a manual duration
if (avstream->duration == AV_NOPTS_VALUE || duration_guessed_from_bitrate) {
if (footage_duration == AV_NOPTS_VALUE || duration_guessed_from_bitrate) {
// Manually read through file for duration
int64_t new_dur;
do {
new_dur = frame->best_effort_timestamp;
} while (instance.GetFrame(pkt, frame) >= 0 && (!cancelled || !cancelled->IsCancelled()));
avstream->duration = new_dur;
} else {
// Fallback to footage duration
avstream->duration = Timecode::rescale_timestamp_ceil(footage_duration, rational(1, AV_TIME_BASE), avstream->time_base);
}
}
} else if (ret == AVERROR_EOF) {
// Video has only one frame in it, treat it like a still image
image_is_still = true;
}
instance.Close();
}
av_frame_free(&frame);
av_packet_free(&pkt);
}
VideoParams stream;
stream.set_stream_index(i);
stream.set_width(avstream->codecpar->width);
stream.set_height(avstream->codecpar->height);
stream.set_video_type((image_is_still) ? VideoParams::kVideoTypeStill : VideoParams::kVideoTypeVideo);
stream.set_format(GetNativePixelFormat(compatible_pix_fmt));
stream.set_channel_count(GetNativeChannelCount(compatible_pix_fmt));
stream.set_interlacing(interlacing);
stream.set_pixel_aspect_ratio(pixel_aspect_ratio);
stream.set_frame_rate(frame_rate);
stream.set_start_time(avstream->start_time);
stream.set_time_base(avstream->time_base);
stream.set_duration(avstream->duration);
stream.set_color_range(avstream->codecpar->color_range == AVCOL_RANGE_JPEG ? VideoParams::kColorRangeFull : VideoParams::kColorRangeLimited);
// Defaults to false, requires user intervention if incorrect
stream.set_premultiplied_alpha(false);
desc.AddVideoStream(stream);
if (image_is_still) {
still_streams++;
} else {
video_streams++;
}
} else if (avstream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
// Create an audio stream object
uint64_t channel_layout = avstream->codecpar->channel_layout;
if (!channel_layout) {
channel_layout = static_cast<uint64_t>(av_get_default_channel_layout(avstream->codecpar->channels));
}
if (avstream->duration == AV_NOPTS_VALUE || duration_guessed_from_bitrate) {
// Loop through stream until we get the whole duration
if (footage_duration == AV_NOPTS_VALUE || duration_guessed_from_bitrate) {
Instance instance;
instance.Open(filename_c, avstream->index);
AVPacket* pkt = av_packet_alloc();
AVFrame* frame = av_frame_alloc();
int64_t new_dur;
do {
new_dur = frame->best_effort_timestamp;
} while (instance.GetFrame(pkt, frame) >= 0 && (!cancelled || !cancelled->IsCancelled()));
avstream->duration = new_dur;
av_frame_free(&frame);
av_packet_free(&pkt);
instance.Close();
} else {
avstream->duration = Timecode::rescale_timestamp_ceil(footage_duration, rational(1, AV_TIME_BASE), avstream->time_base);
}
}
AudioParams stream;
stream.set_stream_index(i);
stream.set_channel_layout(channel_layout);
stream.set_sample_rate(avstream->codecpar->sample_rate);
stream.set_format(FFmpegUtils::GetNativeSampleFormat(static_cast<AVSampleFormat>(avstream->codecpar->format)));
stream.set_time_base(avstream->time_base);
stream.set_duration(avstream->duration);
desc.AddAudioStream(stream);
audio_streams++;
} else if (avstream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
// Limit to SRT for now...
if (avstream->codecpar->codec_id == AV_CODEC_ID_SUBRIP) {
SubtitleParams sub;
AVPacket* pkt = av_packet_alloc();
{
Instance instance;
instance.Open(filename_c, avstream->index);
while (instance.GetPacket(pkt) >= 0) {
TimeRange time(Timecode::timestamp_to_time(pkt->pts, avstream->time_base),
Timecode::timestamp_to_time(pkt->pts + pkt->duration, avstream->time_base));
QString text = QString::fromUtf8((const char *) pkt->data, pkt->size);
sub.push_back(Subtitle(time, text));
}
instance.Close();
}
av_packet_free(&pkt);
desc.AddSubtitleStream(sub);
}
}
}
}
desc.SetStreamCount(fmt_ctx->nb_streams);
if (video_streams == 0 && audio_streams > 0 && still_streams > 0) {
// This footage has no video streams, but has audio and image streams. We've probably
// imported a song with embedded album art that most people don't care about. We'll keep the
// stills referenced in case users do, but we'll default them to disabled so they're
// easier to work with.
for (VideoParams &vp : desc.GetVideoStreams()) {
vp.set_enabled(false);
}
}
}
// Free all memory
avformat_close_input(&fmt_ctx);
return desc;
}
QString FFmpegDecoder::FFmpegError(int error_code)
{
char err[1024];
av_strerror(error_code, err, 512);
return QStringLiteral("%1 %2").arg(QString::number(error_code), err);
}
bool FFmpegDecoder::ConformAudioInternal(const QVector<QString> &filenames, const AudioParams ¶ms, CancelAtom *cancelled)
{
// Iterate through each audio frame and extract the PCM data
// Seek to starting point
instance_.Seek(0);
// Handle NULL channel layout
uint64_t channel_layout = ValidateChannelLayout(instance_.avstream());
if (!channel_layout) {
qCritical() << "Failed to determine channel layout of audio file, could not conform";
return false;
}
// Create resampling context
SwrContext* resampler = swr_alloc_set_opts(nullptr,
params.channel_layout(),
FFmpegUtils::GetFFmpegSampleFormat(params.format()),
params.sample_rate(),
channel_layout,
static_cast<AVSampleFormat>(instance_.avstream()->codecpar->format),
instance_.avstream()->codecpar->sample_rate,
0,
nullptr);
swr_init(resampler);
AVPacket* pkt = av_packet_alloc();
AVFrame* frame = av_frame_alloc();
int ret;
bool success = false;
int64_t duration = instance_.avstream()->duration;
if (duration == 0 || duration == AV_NOPTS_VALUE) {
duration = instance_.fmt_ctx()->duration;
if (!(duration == 0 || duration == AV_NOPTS_VALUE)) {
// Rescale from AVFormatContext timebase to AVStream timebase
duration = av_rescale_q_rnd(duration, {1, AV_TIME_BASE}, instance_.avstream()->time_base, AV_ROUND_UP);
}
}
PlanarFileDevice wave_out;
if (wave_out.open(filenames, QFile::WriteOnly)) {
int nb_channels = params.channel_count();
SampleBuffer data;
data.set_audio_params(params);
while (true) {
// Check if we have a `cancelled` ptr and its value
if (cancelled && cancelled->IsCancelled()) {
break;
}
ret = instance_.GetFrame(pkt, frame);
if (ret < 0) {
if (ret == AVERROR_EOF) {
success = true;
} else {
char err_str[512];
av_strerror(ret, err_str, 512);
qWarning() << "Failed to conform:" << ret << err_str;
}
break;
}
// Allocate buffers
int nb_samples = swr_get_out_samples(resampler, frame->nb_samples);
int nb_bytes_per_channel = params.samples_to_bytes(nb_samples) / nb_channels;
data.set_sample_count(nb_bytes_per_channel);
data.allocate();
// Resample audio to our destination parameters
nb_samples = swr_convert(resampler,
reinterpret_cast<uint8_t**>(data.to_raw_ptrs().data()),
nb_samples,
const_cast<const uint8_t**>(frame->data),
frame->nb_samples);
// If no error, write to files
if (nb_samples > 0) {
// Update byte count for the number of samples we actually received
nb_bytes_per_channel = params.samples_to_bytes(nb_samples) / nb_channels;
// Write to files
wave_out.write(const_cast<const char**>(reinterpret_cast<char**>(data.to_raw_ptrs().data())), nb_bytes_per_channel);
}
// Free buffer
data.destroy();
// Handle error now after freeing
if (nb_samples < 0) {
char err_str[512];
av_strerror(nb_samples, err_str, 512);
qWarning() << "libswresample failed with error:" << nb_samples << err_str;
break;
}
SignalProcessingProgress(frame->best_effort_timestamp, duration);
}
wave_out.close();
} else {
qWarning() << "Failed to open WAVE output for indexing";
}
swr_free(&resampler);
av_frame_free(&frame);
av_packet_free(&pkt);
return success;
}
PixelFormat FFmpegDecoder::GetNativePixelFormat(AVPixelFormat pix_fmt)
{
switch (pix_fmt) {
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_RGBA:
return PixelFormat::U8;
case AV_PIX_FMT_RGB48:
case AV_PIX_FMT_RGBA64:
return PixelFormat::U16;
default:
return PixelFormat::INVALID;
}
}
int FFmpegDecoder::GetNativeChannelCount(AVPixelFormat pix_fmt)
{
switch (pix_fmt) {
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_RGB48:
return VideoParams::kRGBChannelCount;
case AV_PIX_FMT_RGBA:
case AV_PIX_FMT_RGBA64:
return VideoParams::kRGBAChannelCount;
default:
return 0;
}
}
uint64_t FFmpegDecoder::ValidateChannelLayout(AVStream* stream)
{
if (stream->codecpar->channel_layout) {
return stream->codecpar->channel_layout;
}
return av_get_default_channel_layout(stream->codecpar->channels);
}
const char *FFmpegDecoder::GetInterlacingModeInFFmpeg(VideoParams::Interlacing interlacing)
{
if (interlacing == VideoParams::kInterlacedTopFirst) {
return "tff";
} else {
return "bff";
}
}
bool FFmpegDecoder::IsPixelFormatGLSLCompatible(AVPixelFormat f)
{
// NOTE: We don't include RGB24 or RGB48 here because those are slow on the GPU and performance
// should be better if we convert to RGBA on the CPU beforehand
switch (f) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV444P12LE:
case AV_PIX_FMT_RGBA:
case AV_PIX_FMT_RGBA64LE:
return true;
default:
return false;
}
}
void FFmpegDecoder::ClearFrameCache()
{
if (!cached_frames_.empty()) {
cached_frames_.clear();
cache_at_eof_ = false;
cache_at_zero_ = false;
}
}
AVFramePtr FFmpegDecoder::PreProcessFrame(AVFramePtr f, const RetrieveVideoParams &p)
{
// In pre-processing, we try to achieve the following:
// - If a divider is being used, scale down the image
// - If a pixel format is not compatible with the GLSL shader, convert it to RGBA ourselves
if (p.divider == 1 && IsPixelFormatGLSLCompatible(static_cast<AVPixelFormat>(f->format))) {
// No CPU processing required, the user wants this in full resolution and the pixel format can
// be converted on the GPU
return f;
}
// Some scaling and/or format conversion needs to be done
AVFramePtr dest = CreateAVFramePtr();
dest->width = f->width;
dest->height = f->height;
dest->format = f->format;
dest->color_range = f->color_range;
dest->colorspace = f->colorspace;
if (p.divider > 1) {
dest->width = VideoParams::GetScaledDimension(dest->width, p.divider);
dest->height = VideoParams::GetScaledDimension(dest->height, p.divider);
}
if (!IsPixelFormatGLSLCompatible(static_cast<AVPixelFormat>(dest->format))) {
dest->format = FFmpegUtils::GetCompatiblePixelFormat(static_cast<AVPixelFormat>(dest->format), p.maximum_format);
}
int r = av_frame_get_buffer(dest.get(), 0);
if (r < 0) {
FFmpegError(r);
return nullptr;
}
if (!sws_ctx_
|| sws_src_width_ != f->width
|| sws_src_height_ != f->height
|| sws_src_format_ != f->format
|| sws_dst_width_ != dest->width
|| sws_dst_height_ != dest->height
|| sws_dst_format_ != dest->format
|| sws_colrange_ != dest->color_range
|| sws_colspace_ != dest->colorspace) {
// SwsContext must be recreated, destroy current if it exists
FreeScaler();
// Cache info
sws_src_width_ = f->width;
sws_src_height_ = f->height;
sws_src_format_ = static_cast<AVPixelFormat>(f->format);
sws_dst_width_ = dest->width;
sws_dst_height_ = dest->height;
sws_dst_format_ = static_cast<AVPixelFormat>(dest->format);
sws_colrange_ = dest->color_range;
sws_colspace_ = dest->colorspace;
// Create new scaler
sws_ctx_ = sws_getContext(sws_src_width_,
sws_src_height_,
sws_src_format_,
sws_dst_width_,
sws_dst_height_,
sws_dst_format_,
SWS_POINT,
nullptr,
nullptr,
nullptr);
// Set swscale's colorspace details
sws_setColorspaceDetails(sws_ctx_,
sws_getCoefficients(FFmpegUtils::GetSwsColorspaceFromAVColorSpace(dest->colorspace)),
dest->color_range == AVCOL_RANGE_JPEG ? 1 : 0,
sws_getCoefficients(FFmpegUtils::GetSwsColorspaceFromAVColorSpace(dest->colorspace)),
dest->color_range == AVCOL_RANGE_JPEG ? 1 : 0,
0, 0x10000, 0x10000);
}
r = sws_scale(sws_ctx_, f->data, f->linesize, 0, f->height, dest->data, dest->linesize);
if (r < 0) {
FFmpegError(r);
return nullptr;
}
return dest;
}
AVFramePtr FFmpegDecoder::RetrieveFrame(const rational& time, CancelAtom *cancelled)
{
int64_t target_ts = Timecode::time_to_timestamp(time, instance_.avstream()->time_base);
if (instance_.fmt_ctx()->start_time != AV_NOPTS_VALUE) {
target_ts += av_rescale_q(instance_.fmt_ctx()->start_time, {1, AV_TIME_BASE}, instance_.avstream()->time_base);
}
const int64_t min_seek = 0;
int64_t seek_ts = std::max(min_seek, target_ts - MaximumQueueSize());
bool still_seeking = false;
if (time != kAnyTimecode) {
// If the frame wasn't in the frame cache, see if this frame cache is too old to use
if (cached_frames_.empty()
|| (target_ts < cached_frames_.front()->pts || target_ts > cached_frames_.back()->pts + 2*second_ts_)) {
ClearFrameCache();
instance_.Seek(seek_ts);
if (seek_ts == min_seek) {
cache_at_zero_ = true;
}
still_seeking = true;
} else {
// Search cache for frame
AVFramePtr cached_frame = GetFrameFromCache(target_ts);
if (cached_frame) {
return cached_frame;
}
}
}
int ret;
AVFramePtr return_frame = nullptr;
AVFramePtr filtered = nullptr;
while (true) {
// Break out of loop if we've cancelled
if (cancelled && cancelled->IsCancelled()) {
break;
}
if (!filtered) {
filtered = CreateAVFramePtr();
}
// Pull from the decoder
ret = instance_.GetFrame(working_packet_, filtered.get());
if (cancelled && cancelled->IsCancelled()) {
break;
}
// Handle any errors that aren't EOF (EOF is handled later on)
if (ret < 0 && ret != AVERROR_EOF) {
qCritical() << "Failed to retrieve frame:" << ret;
break;
}
if (still_seeking) {
// Handle a failure to seek (occurs on some media)
// We'll only be here if the frame cache was emptied earlier
if (!cache_at_zero_ && (ret == AVERROR_EOF || filtered->best_effort_timestamp > target_ts)) {
seek_ts = qMax(min_seek, seek_ts - second_ts_);
instance_.Seek(seek_ts);
if (seek_ts == min_seek) {
cache_at_zero_ = true;
}
continue;
} else {
still_seeking = false;
}
}
if (ret == AVERROR_EOF) {
// Handle an "expected" EOF by using the last frame of our cache
cache_at_eof_ = true;
if (cached_frames_.empty()) {
qCritical() << "Unexpected codec EOF - unable to retrieve frame";
} else {
return_frame = cached_frames_.back();
}
break;
} else {
// Cut down to thread count - 1 before we acquire a new frame
if (cached_frames_.size() > size_t(MaximumQueueSize())) {
RemoveFirstFrame();
}
// Store frame before just in case
AVFramePtr previous;
if (cached_frames_.empty()) {
previous = nullptr;
} else {
previous = cached_frames_.back();
}
// Append this frame and signal to other threads that a new frame has arrived
cached_frames_.push_back(filtered);
// If this is a valid frame, see if this or the frame before it are the one we need
if (filtered->pts == target_ts || time == kAnyTimecode) {
return_frame = filtered;
break;
} else if (filtered->pts > target_ts) {
if (!previous && cache_at_zero_) {
return_frame = filtered;
break;
} else {
return_frame = previous;
break;
}
}
}
filtered = nullptr;
}
av_packet_unref(working_packet_);
return return_frame;
}
void FFmpegDecoder::FreeScaler()
{
if (sws_ctx_) {
sws_freeContext(sws_ctx_);
sws_ctx_ = nullptr;
}
}
AVFramePtr FFmpegDecoder::GetFrameFromCache(const int64_t &t) const
{
if (t < cached_frames_.front()->pts) {
if (cache_at_zero_) {
return cached_frames_.front();
}
} else if (t > cached_frames_.back()->pts) {
if (cache_at_eof_) {
return cached_frames_.back();
}
} else {
// We already have this frame in the cache, find it
for (auto it=cached_frames_.cbegin(); it!=cached_frames_.cend(); it++) {
AVFramePtr this_frame = *it;
auto next = it;
next++;
if (this_frame->pts == t // Test for an exact match
|| (next != cached_frames_.cend() && (*next)->pts > t)) { // Or for this frame to be the "closest"
return this_frame;
}
}
}
return nullptr;
}
void FFmpegDecoder::RemoveFirstFrame()
{
cached_frames_.pop_front();
cache_at_zero_ = false;
}
int FFmpegDecoder::MaximumQueueSize()
{
// Fairly arbitrary size. This used to need to be the number of current threads to ensure any
// thread that arrived would have its frame available, but if we only have one render thread,
// that's no longer a concern. Now, this value could technically be 1, but some memory cache
// may be useful for reversing. This value may be tweaked over time.
return 2;
}
FFmpegDecoder::Instance::Instance() :
fmt_ctx_(nullptr),
codec_ctx_(nullptr),
avstream_(nullptr),
opts_(nullptr)
{
}
bool FFmpegDecoder::Instance::Open(const char *filename, int stream_index)
{
// Open file in a format context
int error_code = avformat_open_input(&fmt_ctx_, filename, nullptr, nullptr);
// Handle format context error
if (error_code != 0) {
qCritical() << "Failed to open input:" << filename << FFmpegError(error_code);
return false;
}
// Get stream information from format
error_code = avformat_find_stream_info(fmt_ctx_, nullptr);
// Handle get stream information error
if (error_code < 0) {
qCritical() << "Failed to find stream info:" << FFmpegError(error_code);
return false;
}
// Get reference to correct AVStream
avstream_ = fmt_ctx_->streams[stream_index];
// Find decoder
const AVCodec* codec = avcodec_find_decoder(avstream_->codecpar->codec_id);
// Handle failure to find decoder
if (codec == nullptr) {
qCritical() << "Failed to find appropriate decoder for this codec:"
<< filename
<< stream_index
<< avstream_->codecpar->codec_id;
return false;
}
// Allocate context for the decoder
codec_ctx_ = avcodec_alloc_context3(codec);
if (codec_ctx_ == nullptr) {
qCritical() << "Failed to allocate codec context";
return false;
}
// Copy parameters from the AVStream to the AVCodecContext
error_code = avcodec_parameters_to_context(codec_ctx_, avstream_->codecpar);
// Handle failure to copy parameters
if (error_code < 0) {
qCritical() << "Failed to copy parameters from AVStream to AVCodecContext";
return false;
}
// Set multithreading setting
error_code = av_dict_set(&opts_, "threads", "auto", 0);
// Handle failure to set multithreaded decoding
if (error_code < 0) {
qCritical() << "Failed to set codec options, performance may suffer";
}
// Open codec
error_code = avcodec_open2(codec_ctx_, codec, &opts_);
if (error_code < 0) {
char buf[512];
av_strerror(error_code, buf, 512);
qCritical() << "Failed to open codec" << codec->id << error_code << buf;
return false;
}
return true;
}
void FFmpegDecoder::Instance::Close()
{
if (opts_) {
av_dict_free(&opts_);
opts_ = nullptr;
}
if (codec_ctx_) {
avcodec_free_context(&codec_ctx_);
codec_ctx_ = nullptr;
}
if (fmt_ctx_) {
avformat_close_input(&fmt_ctx_);
fmt_ctx_ = nullptr;
}
}
int FFmpegDecoder::Instance::GetFrame(AVPacket *pkt, AVFrame *frame)
{
bool eof = false;
int ret;
// Clear any previous frames
av_frame_unref(frame);
while ((ret = avcodec_receive_frame(codec_ctx_, frame)) == AVERROR(EAGAIN) && !eof) {
// Find next packet in the correct stream index
ret = GetPacket(pkt);
if (ret == AVERROR_EOF) {
// Don't break so that receive gets called again, but don't try to read again
eof = true;
// Send a null packet to signal end of
avcodec_send_packet(codec_ctx_, nullptr);
} else if (ret < 0) {
// Handle other error by breaking loop and returning the code we received
break;
} else {
// Successful read, send the packet
ret = avcodec_send_packet(codec_ctx_, pkt);
// We don't need the packet anymore, so free it
av_packet_unref(pkt);
if (ret < 0) {
break;
}
}
}
return ret;
}
const char *FFmpegDecoder::Instance::GetSubtitleHeader() const
{
return reinterpret_cast<const char*>(codec_ctx_->subtitle_header);
}
int FFmpegDecoder::Instance::GetSubtitle(AVPacket *pkt, AVSubtitle *sub)
{
int ret = GetPacket(pkt);
if (ret >= 0) {
int got_sub;
ret = avcodec_decode_subtitle2(codec_ctx_, sub, &got_sub, pkt);
if (!got_sub) {
ret = -1;
}
}
return ret;
}
int FFmpegDecoder::Instance::GetPacket(AVPacket *pkt)
{
int ret;
do {
av_packet_unref(pkt);
ret = av_read_frame(fmt_ctx_, pkt);
} while (pkt->stream_index != avstream_->index && ret >= 0);
return ret;
}
void FFmpegDecoder::Instance::Seek(int64_t timestamp)
{
avcodec_flush_buffers(codec_ctx_);
av_seek_frame(fmt_ctx_, avstream_->index, timestamp, AVSEEK_FLAG_BACKWARD);
}
}
| 36,662
|
C++
|
.cpp
| 949
| 31.476291
| 151
| 0.63693
|
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
|
18,958
|
oiiodecoder.cpp
|
olive-editor_olive/app/codec/oiio/oiiodecoder.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 "oiiodecoder.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include "common/define.h"
#include "common/oiioutils.h"
#include "config/config.h"
#include "core.h"
#include "render/renderer.h"
namespace olive {
QStringList OIIODecoder::supported_formats_;
OIIODecoder::OIIODecoder() :
image_(nullptr)
{
}
QString OIIODecoder::id() const
{
return QStringLiteral("oiio");
}
FootageDescription OIIODecoder::Probe(const QString &filename, CancelAtom *cancelled) const
{
Q_UNUSED(cancelled)
FootageDescription desc(id());
// Filter out any file extensions that aren't expected to work - sometimes OIIO will crash trying
// to open a file that it can't if it's given one
if (!FileTypeIsSupported(filename)) {
return desc;
}
std::string std_filename = filename.toStdString();
auto in = OIIO::ImageInput::open(std_filename);
if (!in) {
return desc;
}
// Filter out OIIO detecting an "FFmpeg movie", we have a native FFmpeg decoder that can handle
// it better
if (!strcmp(in->format_name(), "FFmpeg movie")) {
return desc;
}
bool stream_enabled = true;
int i;
for (i=0; in->seek_subimage(i, 0); i++) {
OIIO::ImageSpec spec = in->spec();
VideoParams video_params = GetVideoParamsFromImageSpec(spec);
video_params.set_stream_index(i);
if (i > 1) {
// This is a multilayer image and this image might have an offset
OIIO::ImageSpec root_spec = in->spec(0);
float norm_x = spec.x + float(spec.width)*0.5f - float(root_spec.width)*0.5f;
float norm_y = spec.y + float(spec.height)*0.5f - float(root_spec.height)*0.5f;
video_params.set_x(norm_x);
video_params.set_y(norm_y);
}
// By default, only enable the first subimage (presumably the combined image). Later we will
// ask the user if they want to enable the layers instead.
video_params.set_enabled(stream_enabled);
stream_enabled = false;
// OIIO automatically premultiplies alpha
// FIXME: We usually disassociate the alpha for the color management later, for 8-bit images this
// likely reduces the fidelity?
video_params.set_premultiplied_alpha(true);
desc.AddVideoStream(video_params);
}
desc.SetStreamCount(i);
// If we're here, we have a successful image open
in->close();
return desc;
}
bool OIIODecoder::OpenInternal()
{
// If we can open the filename provided, assume everything is working
return OpenImageHandler(stream().filename(), stream().stream());
}
TexturePtr OIIODecoder::RetrieveVideoInternal(const RetrieveVideoParams &p)
{
VideoParams vp = GetVideoParamsFromImageSpec(image_->spec());
vp.set_divider(p.divider);
if (!buffer_.is_allocated()
|| last_params_.divider != p.divider) {
last_params_ = p;
buffer_.destroy();
buffer_.set_video_params(vp);
buffer_.allocate();
if (p.divider == 1) {
// Just upload straight to the buffer
image_->read_image(oiio_pix_fmt_, buffer_.data(), OIIO::AutoStride, buffer_.linesize_bytes());
} else {
OIIO::ImageBuf buf(image_->spec());
image_->read_image(image_->spec().format, buf.localpixels(), buf.pixel_stride(), buf.scanline_stride(), buf.z_stride());
// Roughly downsample image for divider (for some reason OIIO::ImageBufAlgo::resample failed here)
int px_sz = vp.GetBytesPerPixel();
for (int dst_y=0; dst_y<buffer_.height(); dst_y++) {
int src_y = dst_y * buf.spec().height / buffer_.height();
for (int dst_x=0; dst_x<buffer_.width(); dst_x++) {
int src_x = dst_x * buf.spec().width / buffer_.width();
memcpy(buffer_.data() + buffer_.linesize_bytes() * dst_y + px_sz * dst_x,
static_cast<uint8_t*>(buf.localpixels()) + buf.scanline_stride() * src_y + px_sz * src_x,
px_sz);
}
}
}
}
return p.renderer->CreateTexture(vp, buffer_.data(), buffer_.linesize_pixels());
}
void OIIODecoder::CloseInternal()
{
CloseImageHandle();
}
bool OIIODecoder::FileTypeIsSupported(const QString& fn)
{
// We prioritize OIIO over FFmpeg to pick up still images more effectively, but some OIIO decoders (notably OpenJPEG)
// will segfault entirely if given unexpected data (an MPEG-4 for instance). To workaround this issue, we use OIIO's
// "extension_list" attribute and match it with the extension of the file.
// Check if we've created the supported formats list, create it if not
if (supported_formats_.isEmpty()) {
QStringList extension_list = QString::fromStdString(OIIO::get_string_attribute("extension_list")).split(';');
// The format of "extension_list" is "format:ext", we want to separate it into a simple list of extensions
foreach (const QString& ext, extension_list) {
QStringList format_and_ext = ext.split(':');
supported_formats_.append(format_and_ext.at(1).split(','));
}
}
if (!supported_formats_.contains(QFileInfo(fn).suffix(), Qt::CaseInsensitive)) {
return false;
}
return true;
}
bool OIIODecoder::OpenImageHandler(const QString &fn, int subimage)
{
image_ = OIIO::ImageInput::open(fn.toStdString());
if (!image_) {
return false;
}
if (!image_->seek_subimage(subimage, 0)) {
return false;
}
// Check if we can work with this pixel format
const OIIO::ImageSpec& spec = image_->spec();
// We use RGBA frames because that tends to be the native format of GPUs
pix_fmt_ = OIIOUtils::GetFormatFromOIIOBasetype(static_cast<OIIO::TypeDesc::BASETYPE>(spec.format.basetype));
if (pix_fmt_ == PixelFormat::INVALID) {
qWarning() << "Failed to convert OIIO::ImageDesc to native pixel format";
return false;
}
oiio_pix_fmt_ = OIIOUtils::GetOIIOBaseTypeFromFormat(pix_fmt_);
if (oiio_pix_fmt_ == OIIO::TypeDesc::UNKNOWN) {
qCritical() << "Failed to determine appropriate OIIO basetype from native format";
return false;
}
return true;
}
void OIIODecoder::CloseImageHandle()
{
if (image_) {
image_->close();
image_ = nullptr;
}
buffer_.destroy();
}
VideoParams OIIODecoder::GetVideoParamsFromImageSpec(const OIIO::ImageSpec &spec)
{
VideoParams video_params;
video_params.set_width(spec.width);
video_params.set_height(spec.height);
video_params.set_format(OIIOUtils::GetFormatFromOIIOBasetype(static_cast<OIIO::TypeDesc::BASETYPE>(spec.format.basetype)));
video_params.set_channel_count(spec.nchannels);
video_params.set_pixel_aspect_ratio(OIIOUtils::GetPixelAspectRatioFromOIIO(spec));
video_params.set_video_type(VideoParams::kVideoTypeStill);
return video_params;
}
}
| 7,339
|
C++
|
.cpp
| 185
| 35.708108
| 126
| 0.707981
|
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
|
18,959
|
oiioencoder.cpp
|
olive-editor_olive/app/codec/oiio/oiioencoder.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 "oiioencoder.h"
#include "common/oiioutils.h"
namespace olive {
OIIOEncoder::OIIOEncoder(const EncodingParams ¶ms) :
Encoder(params)
{
}
bool OIIOEncoder::Open()
{
return true;
}
bool OIIOEncoder::WriteFrame(FramePtr frame, rational time)
{
std::string filename = GetFilenameForFrame(time).toStdString();
auto output = OIIO::ImageOutput::create(filename);
if (!output) {
return false;
}
OIIO::TypeDesc type = OIIOUtils::GetOIIOBaseTypeFromFormat(frame->format());
OIIO::ImageSpec spec(frame->width(), frame->height(), frame->channel_count(), type);
if (!output->open(filename, spec)) {
return false;
}
if (!output->write_image(type, frame->data(), OIIO::AutoStride, frame->linesize_bytes())) {
return false;
}
if (!output->close()) {
return false;
}
return true;
}
bool OIIOEncoder::WriteAudio(const SampleBuffer &audio)
{
// Do nothing
return false;
}
bool OIIOEncoder::WriteSubtitle(const SubtitleBlock *sub_block)
{
return false;
}
void OIIOEncoder::Close()
{
// Do nothing
}
}
| 1,776
|
C++
|
.cpp
| 59
| 27.40678
| 93
| 0.744543
|
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
|
18,960
|
undocommand.cpp
|
olive-editor_olive/app/undo/undocommand.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 "undocommand.h"
#include "core.h"
namespace olive {
void MultiUndoCommand::redo()
{
for (auto it=children_.cbegin(); it!=children_.cend(); it++) {
(*it)->redo_and_set_modified();
}
}
void MultiUndoCommand::undo()
{
for (auto it=children_.crbegin(); it!=children_.crend(); it++) {
(*it)->undo_and_set_modified();
}
}
UndoCommand::UndoCommand()
{
prepared_ = false;
done_ = false;
}
void UndoCommand::redo_and_set_modified()
{
project_ = GetRelevantProject();
redo_now();
if (project_) {
modified_ = project_->is_modified();
project_->set_modified(true);
}
}
void UndoCommand::undo_and_set_modified()
{
undo_now();
if (project_) {
project_->set_modified(modified_);
}
}
void UndoCommand::redo_now()
{
if (!done_) {
if (!prepared_) {
prepare();
prepared_ = true;
}
redo();
done_ = true;
}
}
void UndoCommand::undo_now()
{
if (done_) {
undo();
done_ = false;
}
}
}
| 1,686
|
C++
|
.cpp
| 69
| 21.492754
| 71
| 0.686913
|
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
|
18,961
|
undostack.cpp
|
olive-editor_olive/app/undo/undostack.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 "undostack.h"
#include <QCoreApplication>
namespace olive {
const int UndoStack::kMaxUndoCommands = 200;
class EmptyCommand : public UndoCommand
{
public:
EmptyCommand(){}
virtual Project* GetRelevantProject() const override {return nullptr;}
protected:
virtual void redo() override {}
virtual void undo() override {}
};
UndoStack::UndoStack()
{
undo_action_ = new QAction();
connect(undo_action_, &QAction::triggered, this, &UndoStack::undo);
redo_action_ = new QAction();
connect(redo_action_, &QAction::triggered, this, &UndoStack::redo);
clear();
UpdateActions();
}
UndoStack::~UndoStack()
{
clear();
delete undo_action_;
delete redo_action_;
}
void UndoStack::push(UndoCommand *command, const QString &name)
{
MultiUndoCommand *mcu = dynamic_cast<MultiUndoCommand*>(command);
if (mcu && mcu->child_count() == 0) {
delete command;
return;
}
// Clear any redoable commands
this->beginRemoveRows(QModelIndex(), commands_.size(), commands_.size() + undone_commands_.size());
if (CanRedo()) {
for (auto it=undone_commands_.cbegin(); it!=undone_commands_.cend(); it++) {
delete (*it).command;
}
undone_commands_.clear();
}
this->endRemoveRows();
// Do command and push
this->beginInsertRows(QModelIndex(), commands_.size(), commands_.size());
command->redo_and_set_modified();
commands_.push_back({command, name});
this->endInsertRows();
// Delete oldest
if (commands_.size() > kMaxUndoCommands) {
this->beginRemoveRows(QModelIndex(), 0, 0);
delete commands_.front().command;
commands_.pop_front();
this->endRemoveRows();
}
UpdateActions();
}
void UndoStack::jump(size_t index)
{
while (commands_.size() > index) {
undo();
}
while (commands_.size() < index) {
redo();
}
}
void UndoStack::undo()
{
if (CanUndo()) {
// Undo most recently done command
commands_.back().command->undo_and_set_modified();
// Place at the front of the "undone commands" list
undone_commands_.push_front(commands_.back());
// Remove undone command from the commands list
commands_.pop_back();
// Update actions
UpdateActions();
}
}
void UndoStack::redo()
{
if (CanRedo()) {
// Redo most recently undone command
undone_commands_.front().command->redo_and_set_modified();
// Place at the back of the done commands list
commands_.push_back(undone_commands_.front());
// Remove done command from undone list
undone_commands_.pop_front();
// Update actions
UpdateActions();
}
}
void UndoStack::clear()
{
this->beginResetModel();
for (auto it=commands_.cbegin(); it!=commands_.cend(); it++) {
delete (*it).command;
}
commands_.clear();
for (auto it=undone_commands_.cbegin(); it!=undone_commands_.cend(); it++) {
delete (*it).command;
}
undone_commands_.clear();
this->endResetModel();
push(new EmptyCommand(), tr("New/Open Project"));
}
bool UndoStack::CanUndo() const
{
return !commands_.empty() && !dynamic_cast<EmptyCommand*>(commands_.back().command);
}
void UndoStack::UpdateActions()
{
undo_action_->setEnabled(CanUndo());
redo_action_->setEnabled(CanRedo());
undo_action_->setText(QCoreApplication::translate("UndoStack", "Undo %1").arg(CanUndo() ? commands_.back().name : QString()));
redo_action_->setText(QCoreApplication::translate("UndoStack", "Redo %1").arg(CanRedo() ? undone_commands_.front().name : QString()));
emit indexChanged(commands_.size());
}
int UndoStack::columnCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return 2;
}
QVariant UndoStack::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
switch (index.column()) {
case 0:
return index.row() + 1;
case 1:
{
std::list<CommandEntry>::const_iterator it;
size_t real_index = index.row();
if (real_index < commands_.size()) {
it = commands_.cbegin();
} else {
real_index -= commands_.size();
it = undone_commands_.cbegin();
}
for (size_t i = 0; i < real_index; i++) {
it++;
}
const QString &name = (*it).name;
return (name.isEmpty()) ? tr("Command") : name;
}
}
} else if (role == Qt::ForegroundRole) {
if (size_t(index.row()) >= commands_.size()) {
return QVariant(QColor(Qt::gray));
}
}
return QVariant();
}
QModelIndex UndoStack::index(int row, int column, const QModelIndex &parent) const
{
return createIndex(row, column, nullptr);
}
QModelIndex UndoStack::parent(const QModelIndex &index) const
{
return QModelIndex();
}
int UndoStack::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return commands_.size() + undone_commands_.size();
}
QVariant UndoStack::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole) {
switch (section) {
case 0:
return QStringLiteral("Number");
case 1:
return QStringLiteral("Action");
}
}
return QVariant();
}
bool UndoStack::hasChildren(const QModelIndex &parent) const
{
return !parent.isValid();
}
}
| 5,911
|
C++
|
.cpp
| 202
| 25.782178
| 136
| 0.684341
|
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
|
18,962
|
humanstrings.cpp
|
olive-editor_olive/app/ui/humanstrings.cpp
|
#include "humanstrings.h"
#include <QCoreApplication>
namespace olive {
QString HumanStrings::SampleRateToString(const int &sample_rate)
{
return QCoreApplication::translate("AudioParams", "%1 Hz").arg(sample_rate);
}
QString HumanStrings::ChannelLayoutToString(const uint64_t &layout)
{
switch (layout) {
case AV_CH_LAYOUT_MONO:
return QCoreApplication::translate("AudioParams", "Mono");
case AV_CH_LAYOUT_STEREO:
return QCoreApplication::translate("AudioParams", "Stereo");
case AV_CH_LAYOUT_2_1:
return QCoreApplication::translate("AudioParams", "2.1");
case AV_CH_LAYOUT_5POINT1:
return QCoreApplication::translate("AudioParams", "5.1");
case AV_CH_LAYOUT_7POINT1:
return QCoreApplication::translate("AudioParams", "7.1");
default:
return QCoreApplication::translate("AudioParams", "Unknown (0x%1)").arg(layout, 1, 16);
}
}
QString HumanStrings::FormatToString(const SampleFormat &f)
{
switch (f) {
case SampleFormat::U8:
return QCoreApplication::translate("AudioParams", "Unsigned 8-bit (Packed)");
case SampleFormat::S16:
return QCoreApplication::translate("AudioParams", "Signed 16-bit (Packed)");
case SampleFormat::S32:
return QCoreApplication::translate("AudioParams", "Signed 32-bit (Packed)");
case SampleFormat::S64:
return QCoreApplication::translate("AudioParams", "Signed 64-bit (Packed)");
case SampleFormat::F32:
return QCoreApplication::translate("AudioParams", "Float 32-bit (Packed)");
case SampleFormat::F64:
return QCoreApplication::translate("AudioParams", "Float 64-bit (Packed)");
case SampleFormat::U8P:
return QCoreApplication::translate("AudioParams", "Unsigned 8-bit (Planar)");
case SampleFormat::S16P:
return QCoreApplication::translate("AudioParams", "Signed 16-bit (Planar)");
case SampleFormat::S32P:
return QCoreApplication::translate("AudioParams", "Signed 32-bit (Planar)");
case SampleFormat::S64P:
return QCoreApplication::translate("AudioParams", "Signed 64-bit (Planar)");
case SampleFormat::F32P:
return QCoreApplication::translate("AudioParams", "Float 32-bit (Planar)");
case SampleFormat::F64P:
return QCoreApplication::translate("AudioParams", "Float 64-bit (Planar)");
case SampleFormat::INVALID:
case SampleFormat::COUNT:
break;
}
return QCoreApplication::translate("AudioParams", "Unknown (0x%1)").arg(f, 1, 16);
}
}
| 2,403
|
C++
|
.cpp
| 58
| 38.086207
| 91
| 0.743261
|
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
|
18,963
|
colorcoding.cpp
|
olive-editor_olive/app/ui/colorcoding.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 "colorcoding.h"
namespace olive {
QVector<Color> ColorCoding::colors_ = {
Color(0.545f, 0.255f, 0.255f),
Color(0.412f, 0.188f, 0.259f),
Color(0.561f, 0.427f, 0.239f),
Color(0.486f, 0.306f, 0.235f),
Color(0.631f, 0.612f, 0.212f),
Color(0.404f, 0.478f, 0.243f),
Color(0.349f, 0.576f, 0.275f),
Color(0.224f, 0.459f, 0.251f),
Color(0.259f, 0.471f, 0.541f),
Color(0.184f, 0.376f, 0.329f),
Color(0.259f, 0.365f, 0.541f),
Color(0.196f, 0.216f, 0.412f),
Color(0.612f, 0.294f, 0.502f),
Color(0.404f, 0.220f, 0.459f),
Color(0.800f, 0.800f, 0.800f),
Color(0.502f, 0.502f, 0.502f)
};
QString ColorCoding::GetColorName(int c)
{
// FIXME: I'm sure we could come up with more creative names for these colors
switch (c) {
case kRed:
return tr("Red");
case kMaroon:
return tr("Maroon");
case kOrange:
return tr("Orange");
case kBrown:
return tr("Brown");
case kYellow:
return tr("Yellow");
case kOlive:
return tr("Olive");
case kLime:
return tr("Lime");
case kGreen:
return tr("Green");
case kCyan:
return tr("Cyan");
case kTeal:
return tr("Teal");
case kBlue:
return tr("Blue");
case kNavy:
return tr("Navy");
case kPink:
return tr("Pink");
case kPurple:
return tr("Purple");
case kSilver:
return tr("Silver");
case kGray:
return tr("Gray");
}
return QString();
}
Color ColorCoding::GetColor(int c)
{
return colors_.at(c);
}
Qt::GlobalColor ColorCoding::GetUISelectorColor(const Color &c)
{
if (c.GetRoughLuminance() > 0.40f) {
return Qt::black;
} else {
return Qt::white;
}
}
}
| 2,343
|
C++
|
.cpp
| 86
| 24.046512
| 79
| 0.685829
|
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
|
18,964
|
icons.cpp
|
olive-editor_olive/app/ui/icons/icons.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 "icons.h"
namespace olive {
/// Works in conjunction with `genicons.sh` to generate and utilize icons of specific sizes
const int ICON_SIZE_COUNT = 4;
const int ICON_SIZES[] = {
16,
32,
64,
128
};
/// Internal icon library for use throughout Olive without having to regenerate constantly
QIcon icon::GoToStart;
QIcon icon::PrevFrame;
QIcon icon::Play;
QIcon icon::Pause;
QIcon icon::NextFrame;
QIcon icon::GoToEnd;
QIcon icon::New;
QIcon icon::Open;
QIcon icon::Save;
QIcon icon::Undo;
QIcon icon::Redo;
QIcon icon::TreeView;
QIcon icon::ListView;
QIcon icon::IconView;
QIcon icon::ToolPointer;
QIcon icon::ToolEdit;
QIcon icon::ToolRipple;
QIcon icon::ToolRolling;
QIcon icon::ToolRazor;
QIcon icon::ToolSlip;
QIcon icon::ToolSlide;
QIcon icon::ToolHand;
QIcon icon::ToolTransition;
QIcon icon::ToolTrackSelect;
QIcon icon::Folder;
QIcon icon::Sequence;
QIcon icon::Video;
QIcon icon::Audio;
QIcon icon::Image;
QIcon icon::MiniMap;
QIcon icon::TriUp;
QIcon icon::TriLeft;
QIcon icon::TriDown;
QIcon icon::TriRight;
QIcon icon::TextBold;
QIcon icon::TextItalic;
QIcon icon::TextUnderline;
QIcon icon::TextStrikethrough;
QIcon icon::TextSmallCaps;
QIcon icon::TextAlignLeft;
QIcon icon::TextAlignRight;
QIcon icon::TextAlignCenter;
QIcon icon::TextAlignJustify;
QIcon icon::TextAlignTop;
QIcon icon::TextAlignBottom;
QIcon icon::TextAlignMiddle;
QIcon icon::Snapping;
QIcon icon::ZoomIn;
QIcon icon::ZoomOut;
QIcon icon::Record;
QIcon icon::Add;
QIcon icon::Error;
QIcon icon::DirUp;
QIcon icon::Clock;
QIcon icon::Diamond;
QIcon icon::Plus;
QIcon icon::Minus;
QIcon icon::AddEffect;
QIcon icon::EyeOpened;
QIcon icon::EyeClosed;
QIcon icon::LockOpened;
QIcon icon::LockClosed;
QIcon icon::Pencil;
QIcon icon::Subtitles;
QIcon icon::ColorPicker;
void icon::LoadAll(const QString& theme)
{
GoToStart = Create(theme, "prev");
PrevFrame = Create(theme, "rew");
Play = Create(theme, "play");
Pause = Create(theme, "pause");
NextFrame = Create(theme, "ff");
GoToEnd = Create(theme, "next");
New = Create(theme, "new");
Open = Create(theme, "open");
Save = Create(theme, "save");
Undo = Create(theme, "undo");
Redo = Create(theme, "redo");
TreeView = Create(theme, "treeview");
ListView = Create(theme, "listview");
IconView = Create(theme, "iconview");
ToolPointer = Create(theme, "arrow");
ToolEdit = Create(theme, "beam");
ToolRipple = Create(theme, "ripple");
ToolRolling = Create(theme, "rolling");
ToolRazor = Create(theme, "razor");
ToolSlip = Create(theme, "slip");
ToolSlide = Create(theme, "slide");
ToolHand = Create(theme, "hand");
ToolTransition = Create(theme, "transition-tool");
ToolTrackSelect = Create(theme, "track-tool");
Folder = Create(theme, "folder");
Sequence = Create(theme, "sequence");
Video = Create(theme, "videosource");
Audio = Create(theme, "audiosource");
Image = Create(theme, "imagesource");
MiniMap = Create(theme, "map");
TriUp = Create(theme, "tri-up");
TriLeft = Create(theme, "tri-left");
TriDown = Create(theme, "tri-down");
TriRight = Create(theme, "tri-right");
TextBold = Create(theme, "text-bold");
TextItalic = Create(theme, "text-italic");
TextUnderline = Create(theme, "text-underline");
TextStrikethrough = Create(theme, "text-strikethrough");
TextSmallCaps = Create(theme, "text-small-caps");
TextAlignLeft = Create(theme, "align-left");
TextAlignRight = Create(theme, "align-right");
TextAlignCenter = Create(theme, "align-center");
TextAlignJustify = Create(theme, "align-justify-all");
TextAlignTop = Create(theme, "align-v-top");
TextAlignBottom = Create(theme, "align-v-bottom");
TextAlignMiddle = Create(theme, "align-v-middle");
Snapping = Create(theme, "magnet");
ZoomIn = Create(theme, "zoomin");
ZoomOut = Create(theme, "zoomout");
Record = Create(theme, "record");
Add = Create(theme, "add-button");
Error = Create(theme, "error");
DirUp = Create(theme, "dirup");
Clock = Create(theme, "clock");
Diamond = Create(theme, "diamond");
Plus = Create(theme, "plus");
Minus = Create(theme, "minus");
AddEffect = Create(theme, "add-effect");
ColorPicker = Create(theme, "color-picker");
EyeOpened = Create(theme, "eye-opened");
EyeClosed = Create(theme, "eye-closed");
LockOpened = Create(theme, "lock-opened");
LockClosed = Create(theme, "lock-closed");
Pencil = Create(theme, "text-edit");
Subtitles = Create(theme, "subtitles");
}
QIcon icon::Create(const QString& theme, const QString &name)
{
QIcon icon;
for (int i=0;i<ICON_SIZE_COUNT;i++) {
icon.addFile(QStringLiteral("%1/png/%2.%3.png").arg(theme, name, QString::number(ICON_SIZES[i])),
QSize(ICON_SIZES[i], ICON_SIZES[i]), QIcon::Normal);
icon.addFile(QStringLiteral("%1/png/%2.%3.disabled.png").arg(theme, name, QString::number(ICON_SIZES[i])),
QSize(ICON_SIZES[i], ICON_SIZES[i]), QIcon::Disabled);
}
return icon;
}
}
| 5,654
|
C++
|
.cpp
| 170
| 30.876471
| 110
| 0.728072
|
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
|
18,965
|
style.cpp
|
olive-editor_olive/app/ui/style/style.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 "style.h"
#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QPalette>
#include <QStyle>
#include <QStyleFactory>
#include <QTextStream>
#include "config/config.h"
#include "ui/icons/icons.h"
namespace olive {
const char* StyleManager::kDefaultStyle = "olive-dark";
QString StyleManager::current_style_;
QMap<QString, QString> StyleManager::available_themes_;
QPalette StyleManager::ParsePalette(const QString& ini_path)
{
QSettings ini(ini_path, QSettings::IniFormat);
QPalette palette;
ParsePaletteGroup(&ini, &palette, QPalette::All);
ParsePaletteGroup(&ini, &palette, QPalette::Active);
ParsePaletteGroup(&ini, &palette, QPalette::Inactive);
ParsePaletteGroup(&ini, &palette, QPalette::Disabled);
return palette;
}
void StyleManager::ParsePaletteGroup(QSettings *ini, QPalette *palette, QPalette::ColorGroup group)
{
QString group_name;
switch (group) {
case QPalette::All:
group_name = "All";
break;
case QPalette::Active:
group_name = "Active";
break;
case QPalette::Inactive:
group_name = "Inactive";
break;
case QPalette::Disabled:
group_name = "Disabled";
break;
default:
return;
}
ini->beginGroup(group_name);
QStringList keys = ini->childKeys();
foreach (QString k, keys) {
ParsePaletteColor(ini, palette, group, k);
}
ini->endGroup();
}
void StyleManager::ParsePaletteColor(QSettings *ini, QPalette *palette, QPalette::ColorGroup group, const QString &role_name)
{
QPalette::ColorRole role;
if (!QString::compare(role_name, "Window", Qt::CaseInsensitive)) {
role = QPalette::Window;
} else if (!QString::compare(role_name, "WindowText", Qt::CaseInsensitive)) {
role = QPalette::WindowText;
} else if (!QString::compare(role_name, "Base", Qt::CaseInsensitive)) {
role = QPalette::Base;
} else if (!QString::compare(role_name, "AlternateBase", Qt::CaseInsensitive)) {
role = QPalette::AlternateBase;
} else if (!QString::compare(role_name, "ToolTipBase", Qt::CaseInsensitive)) {
role = QPalette::ToolTipBase;
} else if (!QString::compare(role_name, "ToolTipText", Qt::CaseInsensitive)) {
role = QPalette::ToolTipText;
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
} else if (!QString::compare(role_name, "PlaceholderText", Qt::CaseInsensitive)) {
role = QPalette::PlaceholderText;
#endif
} else if (!QString::compare(role_name, "Text", Qt::CaseInsensitive)) {
role = QPalette::Text;
} else if (!QString::compare(role_name, "Button", Qt::CaseInsensitive)) {
role = QPalette::Button;
} else if (!QString::compare(role_name, "ButtonText", Qt::CaseInsensitive)) {
role = QPalette::ButtonText;
} else if (!QString::compare(role_name, "BrightText", Qt::CaseInsensitive)) {
role = QPalette::BrightText;
} else if (!QString::compare(role_name, "Highlight", Qt::CaseInsensitive)) {
role = QPalette::Highlight;
} else if (!QString::compare(role_name, "HighlightedText", Qt::CaseInsensitive)) {
role = QPalette::HighlightedText;
} else if (!QString::compare(role_name, "Link", Qt::CaseInsensitive)) {
role = QPalette::Link;
} else if (!QString::compare(role_name, "LinkVisited", Qt::CaseInsensitive)) {
role = QPalette::LinkVisited;
} else {
return;
}
palette->setColor(group, role, QColor(ini->value(role_name).toString()));
}
void StyleManager::Init()
{
qApp->setStyle(QStyleFactory::create("Fusion"));
available_themes_.insert(QStringLiteral("olive-dark"), QStringLiteral("Olive Dark"));
available_themes_.insert(QStringLiteral("olive-light"), QStringLiteral("Olive Light"));
QString config_style = OLIVE_CONFIG("Style").toString();
if (config_style.isEmpty() || !available_themes_.contains(config_style)) {
SetStyle(kDefaultStyle);
} else {
SetStyle(config_style);
}
}
const QString &StyleManager::GetStyle()
{
return current_style_;
}
void StyleManager::SetStyle(const QString &style_path)
{
current_style_ = style_path;
QString abs_style_path = QStringLiteral(":/style/%1").arg(style_path);
// Load all icons for this style (icons must be loaded first because the style change below triggers the icon change)
icon::LoadAll(abs_style_path);
// Set palette for this
QString palette_file = QStringLiteral("%1/palette.ini").arg(abs_style_path);
if (QFileInfo::exists(palette_file)) {
qApp->setPalette(ParsePalette(palette_file));
} else {
qApp->setPalette(qApp->style()->standardPalette());
}
// Set CSS style for this
QFile css_file(QStringLiteral("%1/style.css").arg(abs_style_path));
if (css_file.exists() && css_file.open(QFile::ReadOnly | QFile::Text)) {
// Read in entire CSS from file and set as the application stylesheet
QTextStream css_ts(&css_file);
qApp->setStyleSheet(css_ts.readAll());
css_file.close();
} else {
qApp->setStyleSheet(QString());
}
}
}
| 5,598
|
C++
|
.cpp
| 145
| 35.393103
| 125
| 0.722591
|
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
|
18,966
|
node.cpp
|
olive-editor_olive/app/node/node.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 "node.h"
#include <QApplication>
#include <QGuiApplication>
#include <QDebug>
#include <QFile>
#include "common/lerp.h"
#include "core.h"
#include "config/config.h"
#include "node/group/group.h"
#include "node/project/serializer/typeserializer.h"
#include "nodeundo.h"
#include "project.h"
#include "serializeddata.h"
#include "ui/colorcoding.h"
#include "ui/icons/icons.h"
namespace olive {
#define super QObject
const QString Node::kEnabledInput = QStringLiteral("enabled_in");
Node::Node() :
override_color_(-1),
folder_(nullptr),
flags_(kNone),
caches_enabled_(true)
{
AddInput(kEnabledInput, NodeValue::kBoolean, true);
video_cache_ = new FrameHashCache(this);
thumbnail_cache_ = new ThumbnailCache(this);
audio_cache_ = new AudioPlaybackCache(this);
waveform_cache_ = new AudioWaveformCache(this);
waveform_cache_->SetSavingEnabled(false);
}
Node::~Node()
{
// Disconnect all edges
DisconnectAll();
// Remove self from anything while we're still a node rather than a base QObject
setParent(nullptr);
// Remove all immediates
foreach (NodeInputImmediate* i, standard_immediates_) {
delete i;
}
for (auto it=array_immediates_.cbegin(); it!=array_immediates_.cend(); it++) {
foreach (NodeInputImmediate* i, it.value()) {
delete i;
}
}
}
Project *Node::parent() const
{
return static_cast<Project*>(QObject::parent());
}
Project *Node::project() const
{
return Project::GetProjectFromObject(this);
}
QString Node::ShortName() const
{
return Name();
}
QString Node::Description() const
{
// Return an empty string by default
return QString();
}
void Node::Retranslate()
{
SetInputName(kEnabledInput, tr("Enabled"));
}
QVariant Node::data(const DataType &d) const
{
if (d == ICON) {
// Just a meaningless default icon to be used where necessary
return icon::New;
}
return QVariant();
}
bool Node::SetNodePositionInContext(Node *node, const QPointF &pos)
{
Position p = context_positions_.value(node);
p.position = pos;
return SetNodePositionInContext(node, p);
}
bool Node::SetNodePositionInContext(Node *node, const Position &pos)
{
bool added = !ContextContainsNode(node);
context_positions_.insert(node, pos);
if (added) {
emit NodeAddedToContext(node);
}
emit NodePositionInContextChanged(node, pos.position);
return added;
}
bool Node::RemoveNodeFromContext(Node *node)
{
if (ContextContainsNode(node)) {
context_positions_.remove(node);
emit NodeRemovedFromContext(node);
return true;
} else {
return false;
}
}
Color Node::color() const
{
int c;
if (override_color_ >= 0) {
c = override_color_;
} else {
c = OLIVE_CONFIG_STR(QStringLiteral("CatColor%1").arg(this->Category().first())).toInt();
}
return ColorCoding::GetColor(c);
}
QLinearGradient Node::gradient_color(qreal top, qreal bottom) const
{
QLinearGradient grad;
grad.setStart(0, top);
grad.setFinalStop(0, bottom);
QColor c = QtUtils::toQColor(color());
grad.setColorAt(0.0, c.lighter());
grad.setColorAt(1.0, c);
return grad;
}
QBrush Node::brush(qreal top, qreal bottom) const
{
if (OLIVE_CONFIG("UseGradients").toBool()) {
return gradient_color(top, bottom);
} else {
return QtUtils::toQColor(color());
}
}
void Node::ConnectEdge(Node *output, const NodeInput &input)
{
// Ensure graph is the same
Q_ASSERT(input.node()->parent() == output->parent());
// Ensure a connection isn't getting overwritten
Q_ASSERT(input.node()->input_connections().find(input) == input.node()->input_connections().end());
// Insert connection on both sides
input.node()->input_connections_[input] = output;
output->output_connections_.push_back(std::pair<Node*, NodeInput>({output, input}));
// Call internal events
input.node()->InputConnectedEvent(input.input(), input.element(), output);
output->OutputConnectedEvent(input);
// Emit signals
emit input.node()->InputConnected(output, input);
emit output->OutputConnected(output, input);
// Invalidate all if this node isn't ignoring this input
if (!(input.node()->GetInputFlags(input.input()) & kInputFlagIgnoreInvalidations)) {
input.node()->InvalidateAll(input.input(), input.element());
}
}
void Node::DisconnectEdge(Node *output, const NodeInput &input)
{
// Ensure graph is the same
Q_ASSERT(input.node()->parent() == output->parent());
// Ensure connection exists
Q_ASSERT(input.node()->input_connections().at(input) == output);
// Remove connection from both sides
InputConnections& inputs = input.node()->input_connections_;
inputs.erase(inputs.find(input));
OutputConnections& outputs = output->output_connections_;
outputs.erase(std::find(outputs.begin(), outputs.end(), std::pair<Node*, NodeInput>({output, input})));
// Call internal events
input.node()->InputDisconnectedEvent(input.input(), input.element(), output);
output->OutputDisconnectedEvent(input);
emit input.node()->InputDisconnected(output, input);
emit output->OutputDisconnected(output, input);
if (!(input.node()->GetInputFlags(input.input()) & kInputFlagIgnoreInvalidations)) {
input.node()->InvalidateAll(input.input(), input.element());
}
}
void Node::CopyCacheUuidsFrom(Node *n)
{
video_cache_->SetUuid(n->video_cache_->GetUuid());
audio_cache_->SetUuid(n->audio_cache_->GetUuid());
thumbnail_cache_->SetUuid(n->thumbnail_cache_->GetUuid());
waveform_cache_->SetUuid(n->waveform_cache_->GetUuid());
}
QString Node::GetInputName(const QString &id) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->human_name;
} else {
ReportInvalidInput("get name of", id, -1);
return QString();
}
}
bool Node::IsInputHidden(const QString &input) const
{
return (GetInputFlags(input) & kInputFlagHidden);
}
bool Node::IsInputConnectable(const QString &input) const
{
return !(GetInputFlags(input) & kInputFlagNotConnectable);
}
bool Node::IsInputKeyframable(const QString &input) const
{
return !(GetInputFlags(input) & kInputFlagNotKeyframable);
}
bool Node::IsInputKeyframing(const QString &input, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->is_keyframing();
} else {
ReportInvalidInput("get keyframing state of", input, element);
return false;
}
}
void Node::SetInputIsKeyframing(const QString &input, bool e, int element)
{
if (!IsInputKeyframable(input)) {
qDebug() << "Ignored set keyframing of" << input << "because this input is not keyframable";
return;
}
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
imm->set_is_keyframing(e);
emit KeyframeEnableChanged(NodeInput(this, input, element), e);
} else {
ReportInvalidInput("set keyframing state of", input, element);
}
}
bool Node::IsInputConnected(const QString &input, int element) const
{
return GetConnectedOutput(input, element);
}
Node *Node::GetConnectedOutput(const QString &input, int element) const
{
for (auto it=input_connections_.cbegin(); it!=input_connections_.cend(); it++) {
if (it->first.input() == input && it->first.element() == element) {
return it->second;
}
}
return nullptr;
}
bool Node::IsUsingStandardValue(const QString &input, int track, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->is_using_standard_value(track);
} else {
ReportInvalidInput("determine whether using standard value in", input, element);
return true;
}
}
NodeValue::Type Node::GetInputDataType(const QString &id) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->type;
} else {
ReportInvalidInput("get data type of", id, -1);
return NodeValue::kNone;
}
}
void Node::SetInputDataType(const QString &id, const NodeValue::Type &type)
{
Input* input_meta = GetInternalInputData(id);
if (input_meta) {
input_meta->type = type;
int array_sz = InputArraySize(id);
for (int i=-1; i<array_sz; i++) {
GetImmediate(id, i)->set_data_type(type);
}
emit InputDataTypeChanged(id, type);
} else {
ReportInvalidInput("set data type of", id, -1);
}
}
bool Node::HasInputProperty(const QString &id, const QString &name) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->properties.contains(name);
} else {
ReportInvalidInput("get property of", id, -1);
return false;
}
}
QHash<QString, QVariant> Node::GetInputProperties(const QString &id) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->properties;
} else {
ReportInvalidInput("get property table of", id, -1);
return QHash<QString, QVariant>();
}
}
QVariant Node::GetInputProperty(const QString &id, const QString &name) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->properties.value(name);
} else {
ReportInvalidInput("get property of", id, -1);
return QVariant();
}
}
void Node::SetInputProperty(const QString &id, const QString &name, const QVariant &value)
{
Input* i = GetInternalInputData(id);
if (i) {
i->properties.insert(name, value);
emit InputPropertyChanged(id, name, value);
} else {
ReportInvalidInput("set property of", id, -1);
}
}
SplitValue Node::GetSplitValueAtTime(const QString &input, const rational &time, int element) const
{
SplitValue vals;
int nb_tracks = GetNumberOfKeyframeTracks(input);
for (int i=0;i<nb_tracks;i++) {
vals.append(GetSplitValueAtTimeOnTrack(input, time, i, element));
}
return vals;
}
QVariant Node::GetSplitValueAtTimeOnTrack(const QString &input, const rational &time, int track, int element) const
{
if (!IsUsingStandardValue(input, track, element)) {
const NodeKeyframeTrack& key_track = GetKeyframeTracks(input, element).at(track);
if (key_track.first()->time() >= time) {
// This time precedes any keyframe, so we just return the first value
return key_track.first()->value();
}
if (key_track.last()->time() <= time) {
// This time is after any keyframes so we return the last value
return key_track.last()->value();
}
NodeValue::Type type = GetInputDataType(input);
// If we're here, the time must be somewhere in between the keyframes
NodeKeyframe *before = nullptr, *after = nullptr;
int low = 0;
int high = key_track.size()-1;
while (low <= high) {
int mid = low + (high - low) / 2;
NodeKeyframe *mid_key = key_track.at(mid);
NodeKeyframe *next_key = key_track.at(mid + 1);
if (mid_key->time() <= time && next_key->time() > time) {
before = mid_key;
after = next_key;
break;
} else if (mid_key->time() < time) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (before) {
if (before->time() == time
|| ((!NodeValue::type_can_be_interpolated(type) || before->type() == NodeKeyframe::kHold) && after->time() > time)) {
// Time == keyframe time, so value is precise
return before->value();
} else if (after->time() == time) {
// Time == keyframe time, so value is precise
return after->value();
} else if (before->time() < time && after->time() > time) {
// We must interpolate between these keyframes
double before_val, after_val, interpolated;
if (type == NodeValue::kRational) {
before_val = before->value().value<rational>().toDouble();
after_val = after->value().value<rational>().toDouble();
} else {
before_val = before->value().toDouble();
after_val = after->value().toDouble();
}
if (before->type() == NodeKeyframe::kBezier && after->type() == NodeKeyframe::kBezier) {
// Perform a cubic bezier with two control points
interpolated = Bezier::CubicXtoY(time.toDouble(),
Imath::V2d(before->time().toDouble(), before_val),
Imath::V2d(before->time().toDouble() + before->valid_bezier_control_out().x(), before_val + before->valid_bezier_control_out().y()),
Imath::V2d(after->time().toDouble() + after->valid_bezier_control_in().x(), after_val + after->valid_bezier_control_in().y()),
Imath::V2d(after->time().toDouble(), after_val));
} else if (before->type() == NodeKeyframe::kBezier || after->type() == NodeKeyframe::kBezier) {
// Perform a quadratic bezier with only one control point
Imath::V2d control_point;
if (before->type() == NodeKeyframe::kBezier) {
control_point.x = (before->valid_bezier_control_out().x() + before->time().toDouble());
control_point.y = (before->valid_bezier_control_out().y() + before_val);
} else {
control_point.x = (after->valid_bezier_control_in().x() + after->time().toDouble());
control_point.y = (after->valid_bezier_control_in().y() + after_val);
}
// Interpolate value using quadratic beziers
interpolated = Bezier::QuadraticXtoY(time.toDouble(),
Imath::V2d(before->time().toDouble(), before_val),
control_point,
Imath::V2d(after->time().toDouble(), after_val));
} else {
// To have arrived here, the keyframes must both be linear
qreal period_progress = (time.toDouble() - before->time().toDouble()) / (after->time().toDouble() - before->time().toDouble());
interpolated = lerp(before_val, after_val, period_progress);
}
if (type == NodeValue::kRational) {
return QVariant::fromValue(rational::fromDouble(interpolated));
} else {
return interpolated;
}
}
} else {
qWarning() << "Binary search for keyframes failed";
}
}
return GetSplitStandardValueOnTrack(input, track, element);
}
QVariant Node::GetDefaultValue(const QString &input) const
{
NodeValue::Type type = GetInputDataType(input);
return NodeValue::combine_track_values_into_normal_value(type, GetSplitDefaultValue(input));
}
SplitValue Node::GetSplitDefaultValue(const QString &input) const
{
const Input* i = GetInternalInputData(input);
if (i) {
return i->default_value;
} else {
ReportInvalidInput("retrieve default value of", input, -1);
return SplitValue();
}
}
QVariant Node::GetSplitDefaultValueOnTrack(const QString &input, int track) const
{
SplitValue val = GetSplitDefaultValue(input);
if (track < val.size()) {
return val.at(track);
} else {
return QVariant();
}
}
void Node::SetDefaultValue(const QString &input, const QVariant &val)
{
NodeValue::Type type = GetInputDataType(input);
SetSplitDefaultValue(input, NodeValue::split_normal_value_into_track_values(type, val));
}
void Node::SetSplitDefaultValue(const QString &input, const SplitValue &val)
{
Input* i = GetInternalInputData(input);
if (i) {
i->default_value = val;
} else {
ReportInvalidInput("set default value of", input, -1);
}
}
void Node::SetSplitDefaultValueOnTrack(const QString &input, const QVariant &val, int track)
{
Input* i = GetInternalInputData(input);
if (i) {
if (track < i->default_value.size()) {
i->default_value[track] = val;
}
} else {
ReportInvalidInput("set default value on track of", input, -1);
}
}
const QVector<NodeKeyframeTrack> &Node::GetKeyframeTracks(const QString &input, int element) const
{
return GetImmediate(input, element)->keyframe_tracks();
}
QVector<NodeKeyframe *> Node::GetKeyframesAtTime(const QString &input, const rational &time, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->get_keyframe_at_time(time);
} else {
ReportInvalidInput("get keyframes at time from", input, element);
return QVector<NodeKeyframe*>();
}
}
NodeKeyframe *Node::GetKeyframeAtTimeOnTrack(const QString &input, const rational &time, int track, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->get_keyframe_at_time_on_track(time, track);
} else {
ReportInvalidInput("get keyframe at time on track from", input, element);
return nullptr;
}
}
NodeKeyframe::Type Node::GetBestKeyframeTypeForTimeOnTrack(const QString &input, const rational &time, int track, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->get_best_keyframe_type_for_time(time, track);
} else {
ReportInvalidInput("get closest keyframe before a time from", input, element);
return NodeKeyframe::kDefaultType;
}
}
int Node::GetNumberOfKeyframeTracks(const QString &id) const
{
return NodeValue::get_number_of_keyframe_tracks(GetInputDataType(id));
}
NodeKeyframe *Node::GetEarliestKeyframe(const QString &id, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->get_earliest_keyframe();
} else {
ReportInvalidInput("get earliest keyframe from", id, element);
return nullptr;
}
}
NodeKeyframe *Node::GetLatestKeyframe(const QString &id, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->get_latest_keyframe();
} else {
ReportInvalidInput("get latest keyframe from", id, element);
return nullptr;
}
}
NodeKeyframe *Node::GetClosestKeyframeBeforeTime(const QString &id, const rational &time, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->get_closest_keyframe_before_time(time);
} else {
ReportInvalidInput("get closest keyframe before a time from", id, element);
return nullptr;
}
}
NodeKeyframe *Node::GetClosestKeyframeAfterTime(const QString &id, const rational &time, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->get_closest_keyframe_after_time(time);
} else {
ReportInvalidInput("get closest keyframe after a time from", id, element);
return nullptr;
}
}
bool Node::HasKeyframeAtTime(const QString &id, const rational &time, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->has_keyframe_at_time(time);
} else {
ReportInvalidInput("determine if it has a keyframe at a time from", id, element);
return false;
}
}
QStringList Node::GetComboBoxStrings(const QString &id) const
{
return GetInputProperty(id, QStringLiteral("combo_str")).toStringList();
}
QVariant Node::GetStandardValue(const QString &id, int element) const
{
NodeValue::Type type = GetInputDataType(id);
return NodeValue::combine_track_values_into_normal_value(type, GetSplitStandardValue(id, element));
}
SplitValue Node::GetSplitStandardValue(const QString &id, int element) const
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
return imm->get_split_standard_value();
} else {
ReportInvalidInput("get standard value of", id, element);
return SplitValue();
}
}
QVariant Node::GetSplitStandardValueOnTrack(const QString &input, int track, int element) const
{
NodeInputImmediate* imm = GetImmediate(input, element);
if (imm) {
return imm->get_split_standard_value_on_track(track);
} else {
ReportInvalidInput("get standard value of", input, element);
return QVariant();
}
}
void Node::SetStandardValue(const QString &id, const QVariant &value, int element)
{
NodeValue::Type type = GetInputDataType(id);
SetSplitStandardValue(id, NodeValue::split_normal_value_into_track_values(type, value), element);
}
void Node::SetSplitStandardValue(const QString &id, const SplitValue &value, int element)
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
imm->set_split_standard_value(value);
for (int i=0; i<value.size(); i++) {
if (IsUsingStandardValue(id, i, element)) {
// If this standard value is being used, we need to send a value changed signal
ParameterValueChanged(id, element, TimeRange(RATIONAL_MIN, RATIONAL_MAX));
break;
}
}
} else {
ReportInvalidInput("set standard value of", id, element);
}
}
void Node::SetSplitStandardValueOnTrack(const QString &id, int track, const QVariant &value, int element)
{
NodeInputImmediate* imm = GetImmediate(id, element);
if (imm) {
imm->set_standard_value_on_track(value, track);
if (IsUsingStandardValue(id, track, element)) {
// If this standard value is being used, we need to send a value changed signal
ParameterValueChanged(id, element, TimeRange(RATIONAL_MIN, RATIONAL_MAX));
}
} else {
ReportInvalidInput("set standard value of", id, element);
}
}
bool Node::InputIsArray(const QString &id) const
{
return GetInputFlags(id) & kInputFlagArray;
}
void Node::InputArrayInsert(const QString &id, int index)
{
// Add new input
ArrayResizeInternal(id, InputArraySize(id) + 1);
// Move connections down
InputConnections copied_edges = input_connections();
for (auto it=copied_edges.crbegin(); it!=copied_edges.crend(); it++) {
if (it->first.input() == id && it->first.element() >= index) {
// Disconnect this and reconnect it one element down
NodeInput new_edge = it->first;
new_edge.set_element(new_edge.element() + 1);
DisconnectEdge(it->second, it->first);
ConnectEdge(it->second, new_edge);
}
}
// Shift values and keyframes up one element
for (int i=InputArraySize(id)-1; i>index; i--) {
CopyValuesOfElement(this, this, id, i-1, i);
}
// Reset value of element we just "inserted"
ClearElement(id, index);
}
void Node::InputArrayResize(const QString &id, int size)
{
if (InputArraySize(id) == size) {
return;
}
NodeArrayResizeCommand* c = new NodeArrayResizeCommand(this, id, size);
c->redo_now();
delete c;
}
void Node::InputArrayRemove(const QString &id, int index)
{
// Remove input
ArrayResizeInternal(id, InputArraySize(id) - 1);
// Move connections up
InputConnections copied_edges = input_connections();
for (auto it=copied_edges.cbegin(); it!=copied_edges.cend(); it++) {
if (it->first.input() == id && it->first.element() >= index) {
// Disconnect this and reconnect it one element up if it's not the element being removed
DisconnectEdge(it->second, it->first);
if (it->first.element() > index) {
NodeInput new_edge = it->first;
new_edge.set_element(new_edge.element() - 1);
ConnectEdge(it->second, new_edge);
}
}
}
// Shift values and keyframes down one element
int arr_sz = InputArraySize(id);
for (int i=index; i<arr_sz; i++) {
// Copying ArraySize()+1 is actually legal because immediates are never deleted
CopyValuesOfElement(this, this, id, i+1, i);
}
// Reset value of last element
ClearElement(id, arr_sz);
}
int Node::InputArraySize(const QString &id) const
{
const Input* i = GetInternalInputData(id);
if (i) {
return i->array_size;
} else {
ReportInvalidInput("retrieve array size of", id, -1);
return 0;
}
}
void Node::SetValueHintForInput(const QString &input, const ValueHint &hint, int element)
{
value_hints_.insert({input, element}, hint);
emit InputValueHintChanged(NodeInput(this, input, element));
InvalidateAll(input, element);
}
const NodeKeyframeTrack &Node::GetTrackFromKeyframe(NodeKeyframe *key) const
{
return GetImmediate(key->input(), key->element())->keyframe_tracks().at(key->track());
}
NodeInputImmediate *Node::GetImmediate(const QString &input, int element) const
{
if (element == -1) {
return standard_immediates_.value(input, nullptr);
} else if (array_immediates_.contains(input)) {
const QVector<NodeInputImmediate*>& imm_arr = array_immediates_.value(input);
if (element >= 0 && element < imm_arr.size()) {
return imm_arr.at(element);
}
}
return nullptr;
}
InputFlags Node::GetInputFlags(const QString &input) const
{
const Input* i = GetInternalInputData(input);
if (i) {
return i->flags;
} else {
ReportInvalidInput("retrieve flags of", input, -1);
return InputFlags(kInputFlagNormal);
}
}
void Node::SetInputFlag(const QString &input, InputFlag f, bool on)
{
Input* i = GetInternalInputData(input);
if (i) {
if (on) {
i->flags |= f;
} else {
i->flags &= ~f;
}
emit InputFlagsChanged(input, i->flags);
} else {
ReportInvalidInput("set flags of", input, -1);
}
}
void Node::Value(const NodeValueRow& value, const NodeGlobals &globals, NodeValueTable *table) const
{
// Do nothing
Q_UNUSED(value)
Q_UNUSED(globals)
Q_UNUSED(table)
}
void Node::InvalidateCache(const TimeRange &range, const QString &from, int element, InvalidateCacheOptions options)
{
Q_UNUSED(from)
Q_UNUSED(element)
if (AreCachesEnabled()) {
if (range.in() != range.out()) {
TimeRange vr = range.Intersected(GetVideoCacheRange());
if (vr.length() != 0) {
video_frame_cache()->Invalidate(vr);
thumbnail_cache()->Invalidate(vr);
}
TimeRange ar = range.Intersected(GetAudioCacheRange());
if (ar.length() != 0) {
audio_playback_cache()->Invalidate(ar);
waveform_cache()->Invalidate(ar);
}
}
}
SendInvalidateCache(range, options);
}
TimeRange Node::InputTimeAdjustment(const QString &, int, const TimeRange &input_time, bool clamp) const
{
// Default behavior is no time adjustment at all
return input_time;
}
TimeRange Node::OutputTimeAdjustment(const QString &, int, const TimeRange &input_time) const
{
// Default behavior is no time adjustment at all
return input_time;
}
QVector<Node *> Node::CopyDependencyGraph(const QVector<Node *> &nodes, MultiUndoCommand *command)
{
int nb_nodes = nodes.size();
QVector<Node*> copies(nb_nodes);
for (int i=0; i<nb_nodes; i++) {
// Create another of the same node
Node* c = nodes.at(i)->copy();
// Copy the values, but NOT the connections, since we'll be connecting to our own clones later
Node::CopyInputs(nodes.at(i), c, false);
// Add to graph
Project* graph = nodes.at(i)->parent();
if (command) {
command->add_child(new NodeAddCommand(graph, c));
} else {
c->setParent(graph);
}
// Store in array at the same index as source
copies[i] = c;
}
CopyDependencyGraph(nodes, copies, command);
return copies;
}
void Node::CopyDependencyGraph(const QVector<Node *> &src, const QVector<Node *> &dst, MultiUndoCommand *command)
{
for (int i=0; i<src.size(); i++) {
Node* src_node = src.at(i);
Node* dst_node = dst.at(i);
for (auto it=src_node->input_connections_.cbegin(); it!=src_node->input_connections_.cend(); it++) {
// Determine if the connected node is in our src list
int connection_index = src.indexOf(it->second);
if (connection_index > -1) {
// Find the equivalent node in the dst list
Node *copied_output = dst.at(connection_index);
NodeInput copied_input = NodeInput(dst_node, it->first.input(), it->first.element());
if (command) {
command->add_child(new NodeEdgeAddCommand(copied_output, copied_input));
command->add_child(new NodeSetValueHintCommand(copied_input, src_node->GetValueHintForInput(copied_input.input(), copied_input.element())));
} else {
ConnectEdge(copied_output, copied_input);
copied_input.node()->SetValueHintForInput(copied_input.input(), src_node->GetValueHintForInput(copied_input.input(), copied_input.element()), copied_input.element());
}
}
}
}
}
Node *Node::CopyNodeAndDependencyGraphMinusItemsInternal(QMap<Node*, Node*>& created, Node *node, MultiUndoCommand *command)
{
// Make a new node of the same type
Node* copy = node->copy();
// Add to map
created.insert(node, copy);
// Add it to the same graph
command->add_child(new NodeAddCommand(node->parent(), copy));
// Copy context children
const PositionMap &map = node->GetContextPositions();
for (auto it=map.cbegin(); it!=map.cend(); it++) {
// Add either the copy (if it exists) or the original node to the context
Node *child;
if (it.key()->IsItem()) {
child = it.key();
} else {
child = created.value(it.key());
if (!child) {
child = CopyNodeAndDependencyGraphMinusItemsInternal(created, it.key(), command);
}
}
command->add_child(new NodeSetPositionCommand(child, copy, it.value()));
}
// If this is a group, copy input and output passthroughs
if (NodeGroup *src_group = dynamic_cast<NodeGroup*>(node)) {
NodeGroup *dst_group = static_cast<NodeGroup*>(copy);
for (auto it=src_group->GetInputPassthroughs().cbegin(); it!=src_group->GetInputPassthroughs().cend(); it++) {
// This node should have been created by the context loop above
NodeInput input = it->second;
input.set_node(created.value(input.node()));
command->add_child(new NodeGroupAddInputPassthrough(dst_group, input, it->first));
}
command->add_child(new NodeGroupSetOutputPassthrough(dst_group, created.value(src_group->GetOutputPassthrough())));
}
// Copy values to the clone
CopyInputs(node, copy, false, command);
// Go through input connections and copy if non-item and connect if item
for (auto it=node->input_connections_.cbegin(); it!=node->input_connections_.cend(); it++) {
NodeInput input = it->first;
Node* connected = it->second;
Node* connected_copy;
if (connected->IsItem()) {
// This is an item and we avoid copying those and just connect to them directly
connected_copy = connected;
} else {
// Non-item, we want to clone this too
connected_copy = created.value(connected, nullptr);
if (!connected_copy) {
connected_copy = CopyNodeAndDependencyGraphMinusItemsInternal(created, connected, command);
}
}
NodeInput copied_input = input;
copied_input.set_node(copy);
command->add_child(new NodeEdgeAddCommand(connected_copy, copied_input));
command->add_child(new NodeSetValueHintCommand(copied_input, node->GetValueHintForInput(input.input(), input.element())));
}
return copy;
}
Node *Node::CopyNodeAndDependencyGraphMinusItems(Node *node, MultiUndoCommand *command)
{
QMap<Node*, Node*> created;
return CopyNodeAndDependencyGraphMinusItemsInternal(created, node, command);
}
Node *Node::CopyNodeInGraph(Node *node, MultiUndoCommand *command)
{
Node* copy;
if (OLIVE_CONFIG("SplitClipsCopyNodes").toBool()) {
copy = Node::CopyNodeAndDependencyGraphMinusItems(node, command);
} else {
copy = node->copy();
command->add_child(new NodeAddCommand(node->parent(), copy));
CopyInputs(node, copy, true, command);
const PositionMap &map = node->GetContextPositions();
for (auto it=map.cbegin(); it!=map.cend(); it++) {
// Add to the context
command->add_child(new NodeSetPositionCommand(it.key(), copy, it.value()));
}
}
return copy;
}
void Node::SendInvalidateCache(const TimeRange &range, const InvalidateCacheOptions &options)
{
for (const OutputConnection& conn : output_connections_) {
// Send clear cache signal to the Node
const NodeInput& in = conn.second;
in.node()->InvalidateCache(range, in.input(), in.element(), options);
}
}
void Node::InvalidateAll(const QString &input, int element)
{
InvalidateCache(TimeRange(RATIONAL_MIN, RATIONAL_MAX), input, element);
}
bool Node::Link(Node *a, Node *b)
{
if (a == b || !a || !b) {
return false;
}
if (AreLinked(a, b)) {
return false;
}
a->links_.append(b);
b->links_.append(a);
a->LinkChangeEvent();
b->LinkChangeEvent();
emit a->LinksChanged();
emit b->LinksChanged();
return true;
}
bool Node::Unlink(Node *a, Node *b)
{
if (!AreLinked(a, b)) {
return false;
}
a->links_.removeOne(b);
b->links_.removeOne(a);
a->LinkChangeEvent();
b->LinkChangeEvent();
emit a->LinksChanged();
emit b->LinksChanged();
return true;
}
bool Node::AreLinked(Node *a, Node *b)
{
return a->links_.contains(b);
}
bool Node::Load(QXmlStreamReader *reader, SerializedData *data)
{
uint version = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
quintptr ptr = attr.value().toULongLong();
data->node_ptrs.insert(ptr, this);
} else if (attr.name() == QStringLiteral("version")) {
version = attr.value().toUInt();
}
}
Q_UNUSED(version)
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
LoadInput(reader, data);
} else if (reader->name() == QStringLiteral("label")) {
this->SetLabel(reader->readElementText());
} else if (reader->name() == QStringLiteral("color")) {
this->SetOverrideColor(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("links")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("link")) {
data->block_links.append({this, reader->readElementText().toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("custom")) {
if (!LoadCustom(reader, data)) {
return false;
}
} else if (reader->name() == QStringLiteral("connections")) {
// Load connections
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("connection")) {
QString param_id;
int ele = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("element")) {
ele = attr.value().toInt();
} else if (attr.name() == QStringLiteral("input")) {
param_id = attr.value().toString();
}
}
QString output_node_id;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("output")) {
output_node_id = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
data->desired_connections.append({NodeInput(this, param_id, ele), output_node_id.toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("hints")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("hint")) {
QString input;
int element = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
input = attr.value().toString();
} else if (attr.name() == QStringLiteral("element")) {
element = attr.value().toInt();
}
}
Node::ValueHint vh;
if (!vh.load(reader)) {
return false;
}
this->SetValueHintForInput(input, vh, element);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("context")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr node_ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
node_ptr = attr.value().toULongLong();
}
}
if (node_ptr) {
Node::Position node_pos;
if (!node_pos.load(reader)) {
return false;
}
data->positions[this].insert(node_ptr, node_pos);
} else {
return false;
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("caches")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("audio")) {
this->audio_playback_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("video")) {
this->video_frame_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("thumb")) {
this->thumbnail_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("waveform")) {
this->waveform_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
this->LoadFinishedEvent();
return true;
}
void Node::Save(QXmlStreamWriter *writer) const
{
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
writer->writeAttribute(QStringLiteral("id"), this->id());
writer->writeAttribute(QStringLiteral("ptr"), QString::number(reinterpret_cast<quintptr>(this)));
if (!this->GetLabel().isEmpty()) {
writer->writeTextElement(QStringLiteral("label"), this->GetLabel());
}
if (this->GetOverrideColor() != -1) {
writer->writeTextElement(QStringLiteral("color"), QString::number(this->GetOverrideColor()));
}
foreach (const QString& input, this->inputs()) {
writer->writeStartElement(QStringLiteral("input"));
SaveInput(writer, input);
writer->writeEndElement(); // input
}
if (!this->links().empty()) {
writer->writeStartElement(QStringLiteral("links"));
foreach (Node* link, this->links()) {
writer->writeTextElement(QStringLiteral("link"), QString::number(reinterpret_cast<quintptr>(link)));
}
writer->writeEndElement(); // links
}
if (!this->input_connections().empty()) {
writer->writeStartElement(QStringLiteral("connections"));
for (auto it=this->input_connections().cbegin(); it!=this->input_connections().cend(); it++) {
writer->writeStartElement(QStringLiteral("connection"));
writer->writeAttribute(QStringLiteral("input"), it->first.input());
writer->writeAttribute(QStringLiteral("element"), QString::number(it->first.element()));
writer->writeTextElement(QStringLiteral("output"), QString::number(reinterpret_cast<quintptr>(it->second)));
writer->writeEndElement(); // connection
}
writer->writeEndElement(); // connections
}
if (!this->GetValueHints().empty()) {
writer->writeStartElement(QStringLiteral("hints"));
for (auto it=this->GetValueHints().cbegin(); it!=this->GetValueHints().cend(); it++) {
writer->writeStartElement(QStringLiteral("hint"));
writer->writeAttribute(QStringLiteral("input"), it.key().input);
writer->writeAttribute(QStringLiteral("element"), QString::number(it.key().element));
it.value().save(writer);
writer->writeEndElement(); // hint
}
writer->writeEndElement(); // hints
}
const Node::PositionMap &map = this->GetContextPositions();
if (!map.isEmpty()) {
writer->writeStartElement(QStringLiteral("context"));
for (auto jt=map.cbegin(); jt!=map.cend(); jt++) {
writer->writeStartElement(QStringLiteral("node"));
writer->writeAttribute(QStringLiteral("ptr"), QString::number(reinterpret_cast<quintptr>(jt.key())));
jt.value().save(writer);
writer->writeEndElement(); // node
}
writer->writeEndElement(); // context
}
writer->writeStartElement(QStringLiteral("caches"));
writer->writeTextElement(QStringLiteral("audio"), this->audio_playback_cache()->GetUuid().toString());
writer->writeTextElement(QStringLiteral("video"), this->video_frame_cache()->GetUuid().toString());
writer->writeTextElement(QStringLiteral("thumb"), this->thumbnail_cache()->GetUuid().toString());
writer->writeTextElement(QStringLiteral("waveform"), this->waveform_cache()->GetUuid().toString());
writer->writeEndElement(); // caches
writer->writeStartElement(QStringLiteral("custom"));
SaveCustom(writer);
writer->writeEndElement(); // custom
}
bool Node::LoadCustom(QXmlStreamReader *reader, SerializedData *data)
{
reader->skipCurrentElement();
return true;
}
void Node::PostLoadEvent(SerializedData *data)
{
// Resolve positions
const QMap<quintptr, Node::Position> &positions = data->positions.value(this);
for (auto jt=positions.cbegin(); jt!=positions.cend(); jt++) {
Node *n = data->node_ptrs.value(jt.key());
if (n) {
this->SetNodePositionInContext(n, jt.value());
}
}
}
bool Node::LoadInput(QXmlStreamReader *reader, SerializedData *data)
{
if (dynamic_cast<NodeGroup*>(this)) {
// Ignore input of group
reader->skipCurrentElement();
return true;
}
QString param_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
param_id = attr.value().toString();
break;
}
}
if (param_id.isEmpty()) {
qWarning() << "Failed to load parameter with missing ID";
reader->skipCurrentElement();
return false;
}
if (!this->HasInputWithID(param_id)) {
qWarning() << "Failed to load parameter that didn't exist:" << param_id;
reader->skipCurrentElement();
return false;
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
// Load primary immediate
if (!LoadImmediate(reader, param_id, -1, data)) {
return false;
}
} else if (reader->name() == QStringLiteral("subelements")) {
// Load subelements
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("count")) {
this->InputArrayResize(param_id, attr.value().toInt());
}
}
int element_counter = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
if (!LoadImmediate(reader, param_id, element_counter, data)) {
return false;
}
element_counter++;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
return true;
}
void Node::SaveInput(QXmlStreamWriter *writer, const QString &id) const
{
writer->writeAttribute(QStringLiteral("id"), id);
writer->writeStartElement(QStringLiteral("primary"));
SaveImmediate(writer, id, -1);
writer->writeEndElement(); // primary
int arr_sz = this->InputArraySize(id);
if (arr_sz > 0) {
writer->writeStartElement(QStringLiteral("subelements"));
writer->writeAttribute(QStringLiteral("count"), QString::number(arr_sz));
for (int i=0; i<arr_sz; i++) {
writer->writeStartElement(QStringLiteral("element"));
SaveImmediate(writer, id, i);
writer->writeEndElement(); // element
}
writer->writeEndElement(); // subelements
}
}
bool Node::LoadImmediate(QXmlStreamReader *reader, const QString &input, int element, SerializedData *data)
{
NodeValue::Type data_type = this->GetInputDataType(input);
// HACK: SubtitleParams contain the actual subtitle data, so loading/replacing it will overwrite
// the valid subtitles. We hack around it by simply skipping loading subtitles, we'll see
// if this ends up being an issue in the future.
if (data_type == NodeValue::kSubtitleParams) {
reader->skipCurrentElement();
return true;
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
// Load standard value
int val_index = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
QVariant value_on_track;
if (data_type == NodeValue::kVideoParams) {
VideoParams vp;
vp.Load(reader);
value_on_track = QVariant::fromValue(vp);
} else if (data_type == NodeValue::kAudioParams) {
AudioParams ap = TypeSerializer::LoadAudioParams(reader);
value_on_track = QVariant::fromValue(ap);
} else {
QString value_text = reader->readElementText();
if (!value_text.isEmpty()) {
value_on_track = NodeValue::StringToValue(data_type, value_text, true);
}
}
this->SetSplitStandardValueOnTrack(input, val_index, value_on_track, element);
val_index++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframing")) {
bool k = reader->readElementText().toInt();
if (this->IsInputKeyframable(input)) {
this->SetInputIsKeyframing(input, k, element);
}
} else if (reader->name() == QStringLiteral("keyframes")) {
int track = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
NodeKeyframe* key = new NodeKeyframe();
key->set_input(input);
key->set_element(element);
key->set_track(track);
key->load(reader, data_type);
key->setParent(this);
} else {
reader->skipCurrentElement();
}
}
track++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("csinput")) {
this->SetInputProperty(input, QStringLiteral("col_input"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csdisplay")) {
this->SetInputProperty(input, QStringLiteral("col_display"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csview")) {
this->SetInputProperty(input, QStringLiteral("col_view"), reader->readElementText());
} else if (reader->name() == QStringLiteral("cslook")) {
this->SetInputProperty(input, QStringLiteral("col_look"), reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
return true;
}
void Node::SaveImmediate(QXmlStreamWriter *writer, const QString &input, int element) const
{
bool is_keyframing = this->IsInputKeyframing(input, element);
if (this->IsInputKeyframable(input)) {
writer->writeTextElement(QStringLiteral("keyframing"), QString::number(is_keyframing));
}
NodeValue::Type data_type = this->GetInputDataType(input);
// Write standard value
writer->writeStartElement(QStringLiteral("standard"));
foreach (const QVariant& v, this->GetSplitStandardValue(input, element)) {
writer->writeStartElement(QStringLiteral("track"));
if (data_type == NodeValue::kVideoParams) {
v.value<VideoParams>().Save(writer);
} else if (data_type == NodeValue::kAudioParams) {
TypeSerializer::SaveAudioParams(writer, v.value<AudioParams>());
} else {
writer->writeCharacters(NodeValue::ValueToString(data_type, v, true));
}
writer->writeEndElement(); // track
}
writer->writeEndElement(); // standard
// Write keyframes
if (is_keyframing) {
writer->writeStartElement(QStringLiteral("keyframes"));
for (const NodeKeyframeTrack& track : this->GetKeyframeTracks(input, element)) {
writer->writeStartElement(QStringLiteral("track"));
for (NodeKeyframe* key : track) {
writer->writeStartElement(QStringLiteral("key"));
key->save(writer, data_type);
writer->writeEndElement(); // key
}
writer->writeEndElement(); // track
}
writer->writeEndElement(); // keyframes
}
if (data_type == NodeValue::kColor) {
// Save color management information
writer->writeTextElement(QStringLiteral("csinput"), this->GetInputProperty(input, QStringLiteral("col_input")).toString());
writer->writeTextElement(QStringLiteral("csdisplay"), this->GetInputProperty(input, QStringLiteral("col_display")).toString());
writer->writeTextElement(QStringLiteral("csview"), this->GetInputProperty(input, QStringLiteral("col_view")).toString());
writer->writeTextElement(QStringLiteral("cslook"), this->GetInputProperty(input, QStringLiteral("col_look")).toString());
}
}
void Node::InsertInput(const QString &id, NodeValue::Type type, const QVariant &default_value, InputFlags flags, int index)
{
if (id.isEmpty()) {
qWarning() << "Rejected adding input with an empty ID on node" << this->id();
return;
}
if (HasParamWithID(id)) {
qWarning() << "Failed to add input to node" << this->id() << "- param with ID" << id << "already exists";
return;
}
Node::Input i;
i.type = type;
i.default_value = NodeValue::split_normal_value_into_track_values(type, default_value);
i.flags = flags;
i.array_size = 0;
input_ids_.insert(index, id);
input_data_.insert(index, i);
if (!standard_immediates_.value(id, nullptr)) {
standard_immediates_.insert(id, CreateImmediate(id));
}
emit InputAdded(id);
}
void Node::RemoveInput(const QString &id)
{
int index = input_ids_.indexOf(id);
if (index == -1) {
ReportInvalidInput("remove", id, -1);
return;
}
input_ids_.removeAt(index);
input_data_.removeAt(index);
emit InputRemoved(id);
}
void Node::ReportInvalidInput(const char *attempted_action, const QString& id, int element) const
{
qWarning() << "Failed to" << attempted_action << "parameter" << id << "element" << element
<< "in node" << this->id() << "- input doesn't exist";
}
NodeInputImmediate *Node::CreateImmediate(const QString &input)
{
const Input* i = GetInternalInputData(input);
if (i) {
return new NodeInputImmediate(i->type, i->default_value);
} else {
ReportInvalidInput("create immediate", input, -1);
return nullptr;
}
}
void Node::ArrayResizeInternal(const QString &id, int size)
{
Input* imm = GetInternalInputData(id);
if (!imm) {
ReportInvalidInput("set array size", id, -1);
return;
}
if (imm->array_size != size) {
// Update array size
if (imm->array_size < size) {
// Size is larger, create any immediates that don't exist
QVector<NodeInputImmediate*>& subinputs = array_immediates_[id];
for (int i=subinputs.size(); i<size; i++) {
subinputs.append(CreateImmediate(id));
}
// Note that we do not delete any immediates when decreasing size since the user might still
// want that data. Therefore it's important to note that array_size_ does NOT necessarily
// equal subinputs_.size()
}
int old_sz = imm->array_size;
imm->array_size = size;
emit InputArraySizeChanged(id, old_sz, size);
ParameterValueChanged(id, -1, TimeRange(RATIONAL_MIN, RATIONAL_MAX));
}
}
QString Node::GetConnectCommandString(Node *output, const NodeInput &input)
{
return tr("Connected %1 to %2 - %3").arg(output->GetLabelAndName(), input.node()->GetLabelAndName(), input.GetInputName());
}
QString Node::GetDisconnectCommandString(Node *output, const NodeInput &input)
{
return tr("Disconnected %1 from %2 - %3").arg(output->GetLabelAndName(), input.node()->GetLabelAndName(), input.GetInputName());
}
int Node::GetInternalInputArraySize(const QString &input)
{
return array_immediates_.value(input).size();
}
void FindWaysNodeArrivesHereRecursively(const Node *output, const Node *input, QVector<NodeInput> &v)
{
for (auto it=input->input_connections().cbegin(); it!=input->input_connections().cend(); it++) {
if (it->second == output) {
v.append(it->first);
} else {
FindWaysNodeArrivesHereRecursively(output, it->second, v);
}
}
}
QVector<NodeInput> Node::FindWaysNodeArrivesHere(const Node *output) const
{
QVector<NodeInput> v;
FindWaysNodeArrivesHereRecursively(output, this, v);
return v;
}
void Node::SetInputName(const QString &id, const QString &name)
{
Input* i = GetInternalInputData(id);
if (i) {
i->human_name = name;
emit InputNameChanged(id, name);
} else {
ReportInvalidInput("set name of", id, -1);
}
}
const QString &Node::GetLabel() const
{
return label_;
}
void Node::SetLabel(const QString &s)
{
if (label_ != s) {
label_ = s;
emit LabelChanged(label_);
}
}
QString Node::GetLabelAndName() const
{
if (GetLabel().isEmpty()) {
return Name();
} else {
return tr("%1 (%2)").arg(GetLabel(), Name());
}
}
QString Node::GetLabelOrName() const
{
if (GetLabel().isEmpty()) {
return Name();
}
return GetLabel();
}
void Node::CopyInputs(const Node *source, Node *destination, bool include_connections, MultiUndoCommand *command)
{
Q_ASSERT(source->id() == destination->id());
foreach (const QString& input, source->inputs()) {
// NOTE: This assert is to ensure that inputs in the source also exist in the destination, which
// they should. If they don't and you hit this assert, check if you're handling group
// passthroughs correctly.
Q_ASSERT(destination->HasInputWithID(input));
CopyInput(source, destination, input, include_connections, true, command);
}
if (command) {
command->add_child(new NodeRenameCommand(destination, source->GetLabel()));
} else {
destination->SetLabel(source->GetLabel());
}
if (command) {
command->add_child(new NodeOverrideColorCommand(destination, source->GetOverrideColor()));
} else {
destination->SetOverrideColor(source->GetOverrideColor());
}
}
void Node::CopyInput(const Node *src, Node *dst, const QString &input, bool include_connections, bool traverse_arrays, MultiUndoCommand *command)
{
Q_ASSERT(src->id() == dst->id());
CopyValuesOfElement(src, dst, input, -1, command);
// Copy array size
if (src->InputIsArray(input) && traverse_arrays) {
int src_array_sz = src->InputArraySize(input);
for (int i=0; i<src_array_sz; i++) {
CopyValuesOfElement(src, dst, input, i, command);
}
}
// Copy connections
if (include_connections) {
// Copy all connections
for (auto it=src->input_connections().cbegin(); it!=src->input_connections().cend(); it++) {
if (!traverse_arrays && it->first.element() != -1) {
continue;
}
auto conn_output = it->second;
NodeInput conn_input(dst, input, it->first.element());
if (command) {
command->add_child(new NodeEdgeAddCommand(conn_output, conn_input));
} else {
ConnectEdge(conn_output, conn_input);
}
}
}
}
void Node::CopyValuesOfElement(const Node *src, Node *dst, const QString &input, int src_element, int dst_element, MultiUndoCommand *command)
{
if (dst_element >= dst->GetInternalInputArraySize(input)) {
qDebug() << "Ignored destination element that was out of array bounds";
return;
}
NodeInput dst_input(dst, input, dst_element);
// Copy standard value
SplitValue standard = src->GetSplitStandardValue(input, src_element);
if (command) {
command->add_child(new NodeParamSetSplitStandardValueCommand(dst_input, standard));
} else {
dst->SetSplitStandardValue(input, standard, dst_element);
}
// Copy keyframes
if (NodeInputImmediate *immediate = dst->GetImmediate(input, dst_element)) {
if (command) {
command->add_child(new NodeImmediateRemoveAllKeyframesCommand(immediate));
} else {
immediate->delete_all_keyframes();
}
}
for (const NodeKeyframeTrack& track : src->GetImmediate(input, src_element)->keyframe_tracks()) {
for (NodeKeyframe* key : track) {
NodeKeyframe *copy = key->copy(dst_element, command ? nullptr : dst);
if (command) {
command->add_child(new NodeParamInsertKeyframeCommand(dst, copy));
}
}
}
// Copy keyframing state
if (src->IsInputKeyframable(input)) {
bool is_keying = src->IsInputKeyframing(input, src_element);
if (command) {
command->add_child(new NodeParamSetKeyframingCommand(dst_input, is_keying));
} else {
dst->SetInputIsKeyframing(input, is_keying, dst_element);
}
}
// If this is the root of an array, copy the array size
if (src_element == -1 && dst_element == -1) {
int array_sz = src->InputArraySize(input);
if (command) {
command->add_child(new NodeArrayResizeCommand(dst, input, array_sz));
} else {
dst->ArrayResizeInternal(input, array_sz);
}
}
// Copy value hint
Node::ValueHint vh = src->GetValueHintForInput(input, src_element);
if (command) {
command->add_child(new NodeSetValueHintCommand(dst_input, vh));
} else {
dst->SetValueHintForInput(input, vh, dst_element);
}
}
void GetDependenciesRecursively(QVector<Node*>& list, const Node* node, bool traverse, bool exclusive_only)
{
for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) {
Node* connected_node = it->second;
if (!exclusive_only || !connected_node->IsItem()) {
if (!list.contains(connected_node)) {
list.append(connected_node);
if (traverse) {
GetDependenciesRecursively(list, connected_node, traverse, exclusive_only);
}
}
}
}
}
/**
* @brief Recursively collects dependencies of Node `n` and appends them to QList `list`
*
* @param traverse
*
* TRUE to recursively traverse each node for a complete dependency graph. FALSE to return only the immediate
* dependencies.
*/
QVector<Node *> Node::GetDependenciesInternal(bool traverse, bool exclusive_only) const
{
QVector<Node*> list;
GetDependenciesRecursively(list, this, traverse, exclusive_only);
return list;
}
QVector<Node *> Node::GetDependencies() const
{
return GetDependenciesInternal(true, false);
}
QVector<Node *> Node::GetExclusiveDependencies() const
{
return GetDependenciesInternal(true, true);
}
QVector<Node *> Node::GetImmediateDependencies() const
{
return GetDependenciesInternal(false, false);
}
ShaderCode Node::GetShaderCode(const ShaderRequest &request) const
{
return ShaderCode(QString(), QString());
}
void Node::ProcessSamples(const NodeValueRow &, const SampleBuffer &, SampleBuffer &, int) const
{
}
void Node::GenerateFrame(FramePtr frame, const GenerateJob &job) const
{
Q_UNUSED(frame)
Q_UNUSED(job)
}
bool Node::InputsFrom(Node *n, bool recursively) const
{
for (auto it=input_connections_.cbegin(); it!=input_connections_.cend(); it++) {
Node *connected = it->second;
if (connected == n) {
return true;
} else if (recursively && connected->InputsFrom(n, recursively)) {
return true;
}
}
return false;
}
bool Node::InputsFrom(const QString &id, bool recursively) const
{
for (auto it=input_connections_.cbegin(); it!=input_connections_.cend(); it++) {
Node *connected = it->second;
if (connected->id() == id) {
return true;
} else if (recursively && connected->InputsFrom(id, recursively)) {
return true;
}
}
return false;
}
void Node::DisconnectAll()
{
// Disconnect inputs (copy map since internal map will change as we disconnect)
InputConnections copy = input_connections_;
for (auto it=copy.cbegin(); it!=copy.cend(); it++) {
DisconnectEdge(it->second, it->first);
}
while (!output_connections_.empty()) {
OutputConnection conn = output_connections_.back();
DisconnectEdge(conn.first, conn.second);
}
}
QString Node::GetCategoryName(const CategoryID &c)
{
switch (c) {
case kCategoryOutput:
return tr("Output");
case kCategoryDistort:
return tr("Distort");
case kCategoryMath:
return tr("Math");
case kCategoryKeying:
return tr("Keying");
case kCategoryColor:
return tr("Color");
case kCategoryFilter:
return tr("Filter");
case kCategoryTimeline:
return tr("Timeline");
case kCategoryGenerator:
return tr("Generator");
case kCategoryTransition:
return tr("Transition");
case kCategoryProject:
return tr("Project");
case kCategoryTime:
return tr("Time");
case kCategoryUnknown:
case kCategoryCount:
break;
}
return tr("Uncategorized");
}
TimeRange Node::TransformTimeTo(TimeRange time, Node *target, TransformTimeDirection dir, int path_index)
{
Node *from = this;
Node *to = target;
if (dir == kTransformTowardsInput) {
std::swap(from, to);
}
std::list<NodeInput> path = FindPath(from, to, path_index);
if (!path.empty()) {
if (dir == kTransformTowardsInput) {
for (auto it=path.crbegin(); it!=path.crend(); it++) {
const NodeInput &i = (*it);
time = i.node()->InputTimeAdjustment(i.input(), i.element(), time, false);
}
} else {
// Traverse in output direction
for (auto it=path.cbegin(); it!=path.cend(); it++) {
const NodeInput &i = (*it);
time = i.node()->OutputTimeAdjustment(i.input(), i.element(), time);
}
}
}
return time;
}
void Node::ParameterValueChanged(const QString& input, int element, const TimeRange& range)
{
InputValueChangedEvent(input, element);
emit ValueChanged(NodeInput(this, input, element), range);
if (GetInputFlags(input) & kInputFlagIgnoreInvalidations) {
return;
}
InvalidateCache(range, input, element);
}
TimeRange Node::GetRangeAffectedByKeyframe(NodeKeyframe *key) const
{
const NodeKeyframeTrack& key_track = GetTrackFromKeyframe(key);
int keyframe_index = key_track.indexOf(key);
TimeRange range = GetRangeAroundIndex(key->input(), keyframe_index, key->track(), key->element());
// If a previous key exists and it's a hold, we don't need to invalidate those frames
if (key_track.size() > 1
&& keyframe_index > 0
&& key_track.at(keyframe_index - 1)->type() == NodeKeyframe::kHold) {
range.set_in(key->time());
}
return range;
}
TimeRange Node::GetRangeAroundIndex(const QString &input, int index, int track, int element) const
{
rational range_begin = RATIONAL_MIN;
rational range_end = RATIONAL_MAX;
const NodeKeyframeTrack& key_track = GetImmediate(input, element)->keyframe_tracks().at(track);
if (key_track.size() > 1) {
if (index > 0) {
// If this is not the first key, we'll need to limit it to the key just before
range_begin = key_track.at(index - 1)->time();
}
if (index < key_track.size() - 1) {
// If this is not the last key, we'll need to limit it to the key just after
range_end = key_track.at(index + 1)->time();
}
}
return TimeRange(range_begin, range_end);
}
void Node::ClearElement(const QString& input, int index)
{
GetImmediate(input, index)->delete_all_keyframes();
if (IsInputKeyframable(input)) {
SetInputIsKeyframing(input, false, index);
}
SetSplitStandardValue(input, GetSplitDefaultValue(input), index);
}
void Node::InputValueChangedEvent(const QString &input, int element)
{
Q_UNUSED(input)
Q_UNUSED(element)
}
void Node::InputConnectedEvent(const QString &input, int element, Node *output)
{
Q_UNUSED(input)
Q_UNUSED(element)
Q_UNUSED(output)
}
void Node::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
Q_UNUSED(input)
Q_UNUSED(element)
Q_UNUSED(output)
}
void Node::OutputConnectedEvent(const NodeInput &input)
{
Q_UNUSED(input)
}
void Node::OutputDisconnectedEvent(const NodeInput &input)
{
Q_UNUSED(input)
}
void Node::childEvent(QChildEvent *event)
{
super::childEvent(event);
if (NodeKeyframe* key = dynamic_cast<NodeKeyframe*>(event->child())) {
NodeInput i(this, key->input(), key->element());
if (event->type() == QEvent::ChildAdded) {
GetImmediate(key->input(), key->element())->insert_keyframe(key);
connect(key, &NodeKeyframe::TimeChanged, this, &Node::InvalidateFromKeyframeTimeChange);
connect(key, &NodeKeyframe::ValueChanged, this, &Node::InvalidateFromKeyframeValueChange);
connect(key, &NodeKeyframe::TypeChanged, this, &Node::InvalidateFromKeyframeTypeChanged);
connect(key, &NodeKeyframe::BezierControlInChanged, this, &Node::InvalidateFromKeyframeBezierInChange);
connect(key, &NodeKeyframe::BezierControlOutChanged, this, &Node::InvalidateFromKeyframeBezierOutChange);
emit KeyframeAdded(key);
ParameterValueChanged(i, GetRangeAffectedByKeyframe(key));
} else if (event->type() == QEvent::ChildRemoved) {
TimeRange time_affected = GetRangeAffectedByKeyframe(key);
disconnect(key, &NodeKeyframe::TimeChanged, this, &Node::InvalidateFromKeyframeTimeChange);
disconnect(key, &NodeKeyframe::ValueChanged, this, &Node::InvalidateFromKeyframeValueChange);
disconnect(key, &NodeKeyframe::TypeChanged, this, &Node::InvalidateFromKeyframeTypeChanged);
disconnect(key, &NodeKeyframe::BezierControlInChanged, this, &Node::InvalidateFromKeyframeBezierInChange);
disconnect(key, &NodeKeyframe::BezierControlOutChanged, this, &Node::InvalidateFromKeyframeBezierOutChange);
emit KeyframeRemoved(key);
GetImmediate(key->input(), key->element())->remove_keyframe(key);
ParameterValueChanged(i, time_affected);
}
} else if (NodeGizmo *gizmo = dynamic_cast<NodeGizmo*>(event->child())) {
if (event->type() == QEvent::ChildAdded) {
gizmos_.append(gizmo);
} else if (event->type() == QEvent::ChildRemoved) {
gizmos_.removeOne(gizmo);
}
}
}
void Node::InvalidateFromKeyframeBezierInChange()
{
NodeKeyframe* key = static_cast<NodeKeyframe*>(sender());
const NodeKeyframeTrack& track = GetTrackFromKeyframe(key);
int keyframe_index = track.indexOf(key);
rational start = RATIONAL_MIN;
rational end = key->time();
if (keyframe_index > 0) {
start = track.at(keyframe_index - 1)->time();
}
ParameterValueChanged(key->key_track_ref().input(), TimeRange(start, end));
}
void Node::InvalidateFromKeyframeBezierOutChange()
{
NodeKeyframe* key = static_cast<NodeKeyframe*>(sender());
const NodeKeyframeTrack& track = GetTrackFromKeyframe(key);
int keyframe_index = track.indexOf(key);
rational start = key->time();
rational end = RATIONAL_MAX;
if (keyframe_index < track.size() - 1) {
end = track.at(keyframe_index + 1)->time();
}
ParameterValueChanged(key->key_track_ref().input(), TimeRange(start, end));
}
void Node::InvalidateFromKeyframeTimeChange()
{
NodeKeyframe* key = static_cast<NodeKeyframe*>(sender());
NodeInputImmediate* immediate = GetImmediate(key->input(), key->element());
TimeRange original_range = GetRangeAffectedByKeyframe(key);
TimeRangeList invalidate_range;
invalidate_range.insert(original_range);
if (!(original_range.in() < key->time() && original_range.out() > key->time())) {
// This keyframe needs resorting, store it and remove it from the list
immediate->remove_keyframe(key);
// Automatically insertion sort
immediate->insert_keyframe(key);
// Invalidate new area that the keyframe has been moved to
invalidate_range.insert(GetRangeAffectedByKeyframe(key));
}
// Invalidate entire area surrounding the keyframe (either where it currently is, or where it used to be before it
// was resorted in the if block above)
foreach (const TimeRange& r, invalidate_range) {
ParameterValueChanged(key->key_track_ref().input(), r);
}
emit KeyframeTimeChanged(key);
}
void Node::InvalidateFromKeyframeValueChange()
{
NodeKeyframe* key = static_cast<NodeKeyframe*>(sender());
ParameterValueChanged(key->key_track_ref().input(), GetRangeAffectedByKeyframe(key));
emit KeyframeValueChanged(key);
}
void Node::InvalidateFromKeyframeTypeChanged()
{
NodeKeyframe* key = static_cast<NodeKeyframe*>(sender());
const NodeKeyframeTrack& track = GetTrackFromKeyframe(key);
if (track.size() == 1) {
// If there are no other frames, the interpolation won't do anything
return;
}
// Invalidate entire range
ParameterValueChanged(key->key_track_ref().input(), GetRangeAroundIndex(key->input(), track.indexOf(key), key->track(), key->element()));
emit KeyframeTypeChanged(key);
}
void Node::SetValueAtTime(const NodeInput &input, const rational &time, const QVariant &value, int track, MultiUndoCommand *command, bool insert_on_all_tracks_if_no_key)
{
if (input.IsKeyframing()) {
rational node_time = time;
NodeKeyframe* existing_key = input.GetKeyframeAtTimeOnTrack(node_time, track);
if (existing_key) {
command->add_child(new NodeParamSetKeyframeValueCommand(existing_key, value));
} else {
// No existing key, create a new one
int nb_tracks = NodeValue::get_number_of_keyframe_tracks(input.node()->GetInputDataType(input.input()));
for (int i=0; i<nb_tracks; i++) {
QVariant track_value;
if (i == track) {
track_value = value;
} else if (!insert_on_all_tracks_if_no_key) {
continue;
} else {
track_value = input.node()->GetSplitValueAtTimeOnTrack(input.input(), node_time, i, input.element());
}
NodeKeyframe* new_key = new NodeKeyframe(node_time,
track_value,
input.node()->GetBestKeyframeTypeForTimeOnTrack(NodeKeyframeTrackReference(input, i), node_time),
i,
input.element(),
input.input());
command->add_child(new NodeParamInsertKeyframeCommand(input.node(), new_key));
}
}
} else {
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(input, track), value));
}
}
bool FindPathInternal(std::list<NodeInput> &vec, Node *from, Node *to, int &path_index)
{
for (auto it=from->output_connections().cbegin(); it!=from->output_connections().cend(); it++) {
const NodeInput &next = it->second;
vec.push_back(next);
if (next.node() == to) {
// Found a path! Determine if it's the index we want
if (path_index == 0) {
// It is!
return true;
} else {
// It isn't, keep looking...
path_index--;
}
}
if (FindPathInternal(vec, next.node(), to, path_index)) {
return true;
}
vec.pop_back();
}
return false;
}
std::list<NodeInput> Node::FindPath(Node *from, Node *to, int path_index)
{
std::list<NodeInput> v;
FindPathInternal(v, from, to, path_index);
return v;
}
bool Node::ValueHint::load(QXmlStreamReader *reader)
{
uint version = 0;
XMLAttributeLoop(reader, attr) {
version = attr.value().toUInt();
}
Q_UNUSED(version)
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("types")) {
QVector<NodeValue::Type> types;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("type")) {
types.append(static_cast<NodeValue::Type>(reader->readElementText().toInt()));
} else {
reader->skipCurrentElement();
}
}
this->set_type(types);
} else if (reader->name() == QStringLiteral("index")) {
this->set_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("tag")) {
this->set_tag(reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
return true;
}
void Node::ValueHint::save(QXmlStreamWriter *writer) const
{
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
writer->writeStartElement(QStringLiteral("types"));
for (auto it=this->types().cbegin(); it!=this->types().cend(); it++) {
writer->writeTextElement(QStringLiteral("type"), QString::number(*it));
}
writer->writeEndElement(); // types
writer->writeTextElement(QStringLiteral("index"), QString::number(this->index()));
writer->writeTextElement(QStringLiteral("tag"), this->tag());
}
bool Node::Position::load(QXmlStreamReader *reader)
{
bool got_pos_x = false;
bool got_pos_y = false;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("x")) {
this->position.setX(reader->readElementText().toDouble());
got_pos_x = true;
} else if (reader->name() == QStringLiteral("y")) {
this->position.setY(reader->readElementText().toDouble());
got_pos_y = true;
} else if (reader->name() == QStringLiteral("expanded")) {
this->expanded = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
return got_pos_x && got_pos_y;
}
void Node::Position::save(QXmlStreamWriter *writer) const
{
writer->writeTextElement(QStringLiteral("x"), QString::number(this->position.x()));
writer->writeTextElement(QStringLiteral("y"), QString::number(this->position.y()));
writer->writeTextElement(QStringLiteral("expanded"), QString::number(this->expanded));
}
}
| 73,763
|
C++
|
.cpp
| 2,018
| 31.766105
| 176
| 0.678937
|
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
|
18,967
|
factory.cpp
|
olive-editor_olive/app/node/factory.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 "factory.h"
#include <QCoreApplication>
#include "audio/pan/pan.h"
#include "audio/volume/volume.h"
#include "block/clip/clip.h"
#include "block/gap/gap.h"
#include "block/subtitle/subtitle.h"
#include "block/transition/crossdissolve/crossdissolvetransition.h"
#include "block/transition/diptocolor/diptocolortransition.h"
#include "color/displaytransform/displaytransform.h"
#include "color/ociogradingtransformlinear/ociogradingtransformlinear.h"
#include "distort/cornerpin/cornerpindistortnode.h"
#include "distort/crop/cropdistortnode.h"
#include "distort/flip/flipdistortnode.h"
#include "distort/mask/mask.h"
#include "distort/ripple/rippledistortnode.h"
#include "distort/swirl/swirldistortnode.h"
#include "distort/tile/tiledistortnode.h"
#include "distort/transform/transformdistortnode.h"
#include "distort/wave/wavedistortnode.h"
#include "effect/opacity/opacityeffect.h"
#include "filter/blur/blur.h"
#include "filter/dropshadow/dropshadowfilter.h"
#include "filter/mosaic/mosaicfilternode.h"
#include "filter/stroke/stroke.h"
#include "generator/matrix/matrix.h"
#include "generator/noise/noise.h"
#include "generator/polygon/polygon.h"
#include "generator/shape/shapenode.h"
#include "generator/solid/solid.h"
#include "generator/text/textv1.h"
#include "generator/text/textv2.h"
#include "generator/text/textv3.h"
#include "input/multicam/multicamnode.h"
#include "input/time/timeinput.h"
#include "input/value/valuenode.h"
#include "keying/chromakey/chromakey.h"
#include "keying/colordifferencekey/colordifferencekey.h"
#include "keying/despill/despill.h"
#include "math/math/math.h"
#include "math/merge/merge.h"
#include "math/trigonometry/trigonometry.h"
#include "output/track/track.h"
#include "output/viewer/viewer.h"
#include "project/folder/folder.h"
#include "project/footage/footage.h"
#include "project/sequence/sequence.h"
#include "time/timeformat/timeformat.h"
#include "time/timeoffset/timeoffsetnode.h"
#include "time/timeremap/timeremap.h"
namespace olive {
QList<Node*> NodeFactory::library_;
void NodeFactory::Initialize()
{
Destroy();
// Add internal types
for (int i=0;i<kInternalNodeCount;i++) {
Node* created_node = CreateFromFactoryIndex(static_cast<InternalID>(i));
library_.append(created_node);
}
}
void NodeFactory::Destroy()
{
qDeleteAll(library_);
library_.clear();
}
Menu *NodeFactory::CreateMenu(QWidget* parent, bool create_none_item, Node::CategoryID restrict_to, uint64_t restrict_flags)
{
Menu* menu = new Menu(parent);
menu->setToolTipsVisible(true);
for (int i=0;i<library_.size();i++) {
Node* n = library_.at(i);
if (restrict_to != Node::kCategoryUnknown && !n->Category().contains(restrict_to)) {
// Skip this node
continue;
}
if (restrict_flags && !(n->GetFlags() & restrict_flags)) {
continue;
}
if (n->GetFlags() & Node::kDontShowInCreateMenu) {
continue;
}
// Make sure nodes are up-to-date with the current translation
n->Retranslate();
Menu* destination = nullptr;
QString category_name = Node::GetCategoryName(n->Category().isEmpty()
? Node::kCategoryUnknown
: n->Category().first());
// See if a menu with this category name already exists
QList<QAction*> menu_actions = menu->actions();
foreach (QAction* action, menu_actions) {
if (action->menu() && action->menu()->title() == category_name) {
destination = static_cast<Menu*>(action->menu());
break;
}
}
// Create menu here if it doesn't exist
if (!destination) {
destination = new Menu(category_name, menu);
menu->InsertAlphabetically(destination);
}
// Add entry to menu
QAction* a = destination->InsertAlphabetically(n->Name());
a->setData(i);
a->setToolTip(n->Description());
}
if (create_none_item) {
QAction* none_item = new QAction(QCoreApplication::translate("NodeFactory", "None"),
menu);
none_item->setData(-1);
if (menu->actions().isEmpty()) {
menu->addAction(none_item);
} else {
QAction* separator = menu->insertSeparator(menu->actions().first());
menu->insertAction(separator, none_item);
}
}
return menu;
}
Node* NodeFactory::CreateFromMenuAction(QAction *action)
{
int index = action->data().toInt();
if (index == -1) {
return nullptr;
}
return library_.at(index)->copy();
}
QString NodeFactory::GetIDFromMenuAction(QAction *action)
{
int index = action->data().toInt();
if (index == -1) {
return QString();
}
return library_.at(action->data().toInt())->id();
}
QString NodeFactory::GetNameFromID(const QString &id)
{
if (!id.isEmpty()) {
foreach (Node* n, library_) {
if (n->id() == id) {
return n->Name();
}
}
}
return QString();
}
Node *NodeFactory::CreateFromID(const QString &id)
{
foreach (Node* n, library_) {
if (n->id() == id) {
return n->copy();
}
}
return nullptr;
}
Node *NodeFactory::CreateFromFactoryIndex(const NodeFactory::InternalID &id)
{
switch (id) {
case kClipBlock:
return new ClipBlock();
case kGapBlock:
return new GapBlock();
case kPolygonGenerator:
return new PolygonGenerator();
case kMatrixGenerator:
return new MatrixGenerator();
case kTransformDistort:
return new TransformDistortNode();
case kTrackOutput:
return new Track();
case kViewerOutput:
return new ViewerOutput();
case kAudioVolume:
return new VolumeNode();
case kAudioPanning:
return new PanNode();
case kMath:
return new MathNode();
case kTrigonometry:
return new TrigonometryNode();
case kTime:
return new TimeInput();
case kBlurFilter:
return new BlurFilterNode();
case kSolidGenerator:
return new SolidGenerator();
case kMerge:
return new MergeNode();
case kStrokeFilter:
return new StrokeFilterNode();
case kTextGeneratorV1:
return new TextGeneratorV1();
case kTextGeneratorV2:
return new TextGeneratorV2();
case kTextGeneratorV3:
return new TextGeneratorV3();
case kCrossDissolveTransition:
return new CrossDissolveTransition();
case kDipToColorTransition:
return new DipToColorTransition();
case kMosaicFilter:
return new MosaicFilterNode();
case kCropDistort:
return new CropDistortNode();
case kProjectFootage:
return new Footage();
case kProjectFolder:
return new Folder();
case kProjectSequence:
return new Sequence();
case kValueNode:
return new ValueNode();
case kTimeRemapNode:
return new TimeRemapNode();
case kSubtitleBlock:
return new SubtitleBlock();
case kShapeGenerator:
return new ShapeNode();
case kColorDifferenceKeyKeying:
return new ColorDifferenceKeyNode();
case kDespillKeying:
return new DespillNode();
case kGroupNode:
return new NodeGroup();
case kOpacityEffect:
return new OpacityEffect();
case kFlipDistort:
return new FlipDistortNode();
case kNoiseGenerator:
return new NoiseGeneratorNode();
case kTimeOffsetNode:
return new TimeOffsetNode();
case kCornerPinDistort:
return new CornerPinDistortNode();
case kDisplayTransform:
return new DisplayTransformNode();
case kOCIOGradingTransformLinear:
return new OCIOGradingTransformLinearNode();
case kChromaKey:
return new ChromaKeyNode();
case kMaskDistort:
return new MaskDistortNode();
case kDropShadowFilter:
return new DropShadowFilter();
case kTimeFormat:
return new TimeFormatNode();
case kWaveDistort:
return new WaveDistortNode();
case kTileDistort:
return new TileDistortNode();
case kSwirlDistort:
return new SwirlDistortNode();
case kRippleDistort:
return new RippleDistortNode();
case kMulticamNode:
return new MultiCamNode();
case kInternalNodeCount:
break;
}
return nullptr;
}
}
| 8,702
|
C++
|
.cpp
| 276
| 27.583333
| 124
| 0.724171
|
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
|
18,968
|
traverser.cpp
|
olive-editor_olive/app/node/traverser.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 "traverser.h"
#include "node.h"
#include "node/block/clip/clip.h"
#include "render/job/footagejob.h"
#include "render/rendermanager.h"
namespace olive {
NodeValueDatabase NodeTraverser::GenerateDatabase(const Node* node, const TimeRange &range)
{
NodeValueDatabase database;
// HACK: Pick up loop mode from clips
LoopMode old_loop_mode = loop_mode_;
if (const ClipBlock *clip = dynamic_cast<const ClipBlock*>(node)) {
loop_mode_ = clip->loop_mode();
}
// We need to insert tables into the database for each input
auto ignore = node->IgnoreInputsForRendering();
foreach (const QString& input, node->inputs()) {
if (IsCancelled()) {
return NodeValueDatabase();
}
if (ignore.contains(input)) {
continue;
}
database.Insert(input, ProcessInput(node, input, range));
}
loop_mode_ = old_loop_mode;
return database;
}
NodeValueRow NodeTraverser::GenerateRow(NodeValueDatabase *database, const Node *node, const TimeRange &range)
{
// Generate row
NodeValueRow row;
for (auto it=database->begin(); it!=database->end(); it++) {
// Get hint for which value should be pulled
NodeValue value = GenerateRowValue(node, it.key(), &it.value(), range);
row.insert(it.key(), value);
}
// TEMP: Audio needs to be refactored to work with new job system. But refactoring hasn't been
// done yet, so we emulate old behavior here JUST FOR AUDIO.
for (auto it=row.begin(); it!=row.end(); it++) {
NodeValue &val = it.value();
if (val.type() == NodeValue::kSamples) {
ResolveJobs(val);
}
}
// END TEMP
return row;
}
NodeValueRow NodeTraverser::GenerateRow(const Node *node, const TimeRange &range)
{
// Generate database of input values of node
NodeValueDatabase database = GenerateDatabase(node, range);
return GenerateRow(&database, node, range);
}
NodeValue NodeTraverser::GenerateRowValue(const Node *node, const QString &input, NodeValueTable *table, const TimeRange &time)
{
NodeValue value = GenerateRowValueElement(node, input, -1, table, time);
if (value.array()) {
// Resolve each element of array
NodeValueTableArray tables = value.value<NodeValueTableArray>();
NodeValueArray output;
for (auto it=tables.begin(); it!=tables.end(); it++) {
output[it->first] = GenerateRowValueElement(node, input, it->first, &it->second, time);
}
value = NodeValue(value.type(), QVariant::fromValue(output), value.source(), value.array(), value.tag());
}
return value;
}
NodeValue NodeTraverser::GenerateRowValueElement(const Node *node, const QString &input, int element, NodeValueTable *table, const TimeRange &time)
{
int value_index = GenerateRowValueElementIndex(node->GetValueHintForInput(input, element), node->GetInputDataType(input), table);
if (value_index == -1) {
// If value was -1, try getting the last value
value_index = table->Count() - 1;
}
if (value_index == -1) {
// If value is still -1, assume the table is empty and return nothing
return NodeValue();
}
NodeValue value = table->TakeAt(value_index);
if (value.type() == NodeValue::kTexture && UseCache()) {
if (TexturePtr tex = value.toTexture()) {
QMutexLocker locker(node->video_frame_cache()->mutex());
node->video_frame_cache()->LoadState();
QString cache = node->video_frame_cache()->GetValidCacheFilename(time.in());
if (!cache.isEmpty()) {
value.set_value(tex->toJob(CacheJob(cache, value)));
}
}
}
return value;
}
int NodeTraverser::GenerateRowValueElementIndex(const Node::ValueHint &hint, NodeValue::Type preferred_type, const NodeValueTable *table)
{
QVector<NodeValue::Type> types = hint.types();
if (types.isEmpty()) {
types.append(preferred_type);
}
if (hint.index() == -1) {
// Get most recent value with this type and tag
return table->GetValueIndex(types, hint.tag());
} else {
// Try to find value at this index
int index = table->Count() - 1 - hint.index();
int diff = 0;
while (index + diff < table->Count() && index - diff >= 0) {
if (index + diff < table->Count() && types.contains(table->at(index + diff).type())) {
return index + diff;
}
if (index - diff >= 0 && types.contains(table->at(index - diff).type())) {
return index - diff;
}
diff++;
}
return -1;
}
}
int NodeTraverser::GenerateRowValueElementIndex(const Node *node, const QString &input, int element, const NodeValueTable *table)
{
return GenerateRowValueElementIndex(node->GetValueHintForInput(input, element), node->GetInputDataType(input), table);
}
void NodeTraverser::Transform(QTransform *transform, const Node *start, const Node *end, const TimeRange &range)
{
transform_ = transform;
transform_start_ = start;
transform_now_ = nullptr;
GenerateTable(end, range);
transform_ = nullptr;
}
NodeValueTable NodeTraverser::ProcessInput(const Node* node, const QString& input, const TimeRange& range)
{
// If input is connected, retrieve value directly
if (node->IsInputConnectedForRender(input)) {
TimeRange adjusted_range = node->InputTimeAdjustment(input, -1, range, true);
// Value will equal something from the connected node, follow it
Node *output = node->GetConnectedRenderOutput(input);
NodeValueTable table = GenerateTable(output, adjusted_range, node);
return table;
} else {
// Store node
QVariant return_val;
bool is_array = node->InputIsArray(input);
if (is_array) {
// Value is an array, we will return a list of NodeValueTables
NodeValueTableArray array_tbl;
Node::ActiveElements a = node->GetActiveElementsAtTime(input, range);
if (a.mode() == Node::ActiveElements::kAllElements) {
int sz = node->InputArraySize(input);
for (int i=0; i<sz; i++) {
ProcessInputElement(array_tbl, node, input, i, range);
}
} else if (a.mode() == Node::ActiveElements::kSpecified) {
for (int ele : a.elements()) {
ProcessInputElement(array_tbl, node, input, ele, range);
}
}
return_val = QVariant::fromValue(array_tbl);
} else {
// Not connected or an array, just pull the immediate
TimeRange adjusted_range = node->InputTimeAdjustment(input, -1, range, true);
return_val = node->GetValueAtTime(input, adjusted_range.in());
}
NodeValueTable return_table;
return_table.Push(node->GetInputDataType(input), return_val, node, is_array);
return return_table;
}
}
void NodeTraverser::ProcessInputElement(NodeValueTableArray &array_tbl, const Node *node, const QString &input, int element, const TimeRange &range)
{
NodeValueTable& sub_tbl = array_tbl[element];
TimeRange adjusted_range = node->InputTimeAdjustment(input, element, range, true);
if (node->IsInputConnectedForRender(input, element)) {
Node *output = node->GetConnectedRenderOutput(input, element);
sub_tbl = GenerateTable(output, adjusted_range, node);
} else {
QVariant input_value = node->GetValueAtTime(input, adjusted_range.in(), element);
sub_tbl.Push(node->GetInputDataType(input), input_value, node);
}
}
NodeTraverser::NodeTraverser() :
cancel_(nullptr),
transform_(nullptr),
loop_mode_(LoopMode::kLoopModeOff)
{
}
class GTTTime
{
public:
GTTTime(const Node *n) { t = QDateTime::currentMSecsSinceEpoch(); node = n; }
~GTTTime() { qDebug() << "GT for" << node << "took" << (QDateTime::currentMSecsSinceEpoch() - t); }
qint64 t;
const Node *node;
};
NodeValueTable NodeTraverser::GenerateTable(const Node *n, const TimeRange& range, const Node *next_node)
{
// NOTE: Times how long a node takes to process, useful for profiling.
//GTTTime gtt(n);Q_UNUSED(gtt);
// Use table cache to skip processing where available
if (value_cache_.contains(n)) {
QHash<TimeRange, NodeValueTable> &node_value_map = value_cache_[n];
if (node_value_map.contains(range)) {
return node_value_map.value(range);
}
}
// Generate row for node
NodeValueDatabase database = GenerateDatabase(n, range);
// Check for bypass
bool is_enabled;
if (!database[Node::kEnabledInput].Has(NodeValue::kBoolean)) {
// Fallback if we couldn't find a bool value
is_enabled = true;
} else {
is_enabled = database[Node::kEnabledInput].Get(NodeValue::kBoolean).toBool();
}
NodeValueTable table;
if (is_enabled) {
NodeValueRow row = GenerateRow(&database, n, range);
// Generate output table
table = database.Merge();
// By this point, the node should have all the inputs it needs to render correctly
NodeGlobals globals(video_params_, audio_params_, range, loop_mode_);
n->Value(row, globals, &table);
// `transform_now_` is the next node in the path that needs to be traversed. It only ever goes
// "down" the graph so that any traversing going back up doesn't unnecessarily transform
// from unrelated nodes or the same node twice
if (transform_) {
if (transform_now_ == n || transform_start_ == n) {
if (transform_now_ == n) {
QTransform t = n->GizmoTransformation(row, globals);
if (!t.isIdentity()) {
(*transform_) *= t;
}
}
transform_now_ = next_node;
}
}
} else {
// If this node has an effect input, ensure that is pushed last
NodeValueTable primary;
if (!n->GetEffectInputID().isEmpty()) {
primary = database.Take(n->GetEffectInputID());
}
table = database.Merge();
table.Push(primary);
}
value_cache_[n][range] = table;
return table;
}
TexturePtr NodeTraverser::ProcessVideoCacheJob(const CacheJob *val)
{
return nullptr;
}
QVector2D NodeTraverser::GenerateResolution() const
{
return QVector2D(video_params_.square_pixel_width(), video_params_.height());
}
void NodeTraverser::ResolveJobs(NodeValue &val)
{
if (val.type() == NodeValue::kTexture) {
if (TexturePtr job_tex = val.toTexture()) {
if (AcceleratedJob *base_job = job_tex->job()) {
if (resolved_texture_cache_.contains(job_tex.get())) {
val.set_value(resolved_texture_cache_.value(job_tex.get()));
} else {
// Resolve any sub-jobs
for (auto it=base_job->GetValues().begin(); it!=base_job->GetValues().end(); it++) {
// Jobs will almost always be submitted with one of these types
NodeValue &subval = it.value();
ResolveJobs(subval);
}
if (CacheJob *cj = dynamic_cast<CacheJob*>(base_job)) {
TexturePtr tex = ProcessVideoCacheJob(cj);
if (tex) {
val.set_value(tex);
} else {
val.set_value(cj->GetFallback());
}
} else if (ColorTransformJob *ctj = dynamic_cast<ColorTransformJob*>(base_job)) {
VideoParams ctj_params = job_tex->params();
ctj_params.set_format(GetCacheVideoParams().format());
TexturePtr dest = CreateTexture(ctj_params);
// Resolve input texture
NodeValue v = ctj->GetInputTexture();
ResolveJobs(v);
ctj->SetInputTexture(v);
ProcessColorTransform(dest, val.source(), ctj);
val.set_value(dest);
} else if (ShaderJob *sj = dynamic_cast<ShaderJob*>(base_job)) {
VideoParams tex_params = job_tex->params();
TexturePtr tex = CreateTexture(tex_params);
ProcessShader(tex, val.source(), sj);
val.set_value(tex);
} else if (GenerateJob *gj = dynamic_cast<GenerateJob*>(base_job)) {
VideoParams tex_params = job_tex->params();
TexturePtr tex = CreateTexture(tex_params);
ProcessFrameGeneration(tex, val.source(), gj);
// Convert to reference space
const QString &colorspace = tex_params.colorspace();
if (!colorspace.isEmpty()) {
// Set format to primary format
tex_params.set_format(GetCacheVideoParams().format());
TexturePtr dest = CreateTexture(tex_params);
ConvertToReferenceSpace(dest, tex, colorspace);
tex = dest;
}
val.set_value(tex);
} else if (FootageJob *fj = dynamic_cast<FootageJob*>(base_job)) {
rational footage_time = Footage::AdjustTimeByLoopMode(fj->time().in(), fj->loop_mode(), fj->length(), fj->video_params().video_type(), fj->video_params().frame_rate_as_time_base());
TexturePtr tex;
if (footage_time.isNaN()) {
// Push dummy texture
tex = CreateDummyTexture(fj->video_params());
} else {
VideoParams managed_params = fj->video_params();
managed_params.set_format(GetCacheVideoParams().format());
tex = CreateTexture(managed_params);
ProcessVideoFootage(tex, fj, footage_time);
}
val.set_value(tex);
}
// Cache resolved value
resolved_texture_cache_.insert(job_tex.get(), val.toTexture());
}
}
}
} else if (val.type() == NodeValue::kSamples) {
if (val.canConvert<SampleJob>()) {
SampleJob job = val.value<SampleJob>();
SampleBuffer output_buffer = CreateSampleBuffer(job.samples().audio_params(), job.samples().sample_count());
ProcessSamples(output_buffer, val.source(), job.time(), job);
val.set_value(QVariant::fromValue(output_buffer));
} else if (val.canConvert<FootageJob>()) {
FootageJob job = val.value<FootageJob>();
SampleBuffer buffer = CreateSampleBuffer(GetCacheAudioParams(), job.time().length());
ProcessAudioFootage(buffer, &job, job.time());
val.set_value(buffer);
}
}
}
TexturePtr NodeTraverser::CreateDummyTexture(const VideoParams &p)
{
return std::make_shared<Texture>(p);
}
}
| 14,688
|
C++
|
.cpp
| 358
| 35.136872
| 193
| 0.668661
|
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
|
18,969
|
inputdragger.cpp
|
olive-editor_olive/app/node/inputdragger.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 "inputdragger.h"
#include "core.h"
#include "node.h"
#include "nodeundo.h"
namespace olive {
int NodeInputDragger::input_being_dragged = 0;
NodeInputDragger::NodeInputDragger()
{
}
bool NodeInputDragger::IsStarted() const
{
return input_.IsValid();
}
void NodeInputDragger::Start(const NodeKeyframeTrackReference &input, const rational &time, bool create_key_on_all_tracks)
{
Q_ASSERT(!IsStarted());
// Set up new drag
input_ = input;
time_ = time;
Node* node = input_.input().node();
// Cache current value
start_value_ = node->GetSplitValueAtTimeOnTrack(input_, time);
end_value_ = start_value_;
// Determine whether we are creating a keyframe or not
if (input_.input().IsKeyframing()) {
dragging_key_ = node->GetKeyframeAtTimeOnTrack(input_, time);
if (!dragging_key_) {
dragging_key_ = new NodeKeyframe(time,
start_value_,
node->GetBestKeyframeTypeForTimeOnTrack(input_, time),
input_.track(),
input_.input().element(),
input_.input().input(),
node);
created_keys_.append(dragging_key_);
if (create_key_on_all_tracks) {
int nb_tracks = NodeValue::get_number_of_keyframe_tracks(input.input().node()->GetInputDataType(input.input().input()));
for (int i=0; i<nb_tracks; i++) {
if (i != input.track()) {
NodeKeyframeTrackReference this_ref(input.input(), i);
created_keys_.append(new NodeKeyframe(time, node->GetSplitValueAtTimeOnTrack(this_ref, time),
node->GetBestKeyframeTypeForTimeOnTrack(this_ref, time),
i, input.input().element(), input.input().input(), node));
}
}
}
}
}
input_being_dragged++;
}
void NodeInputDragger::Drag(QVariant value)
{
Q_ASSERT(IsStarted());
Node* node = input_.input().node();
const QString& input = input_.input().input();
if (node->HasInputProperty(input, QStringLiteral("min"))) {
// Assumes the value is a double of some kind
double min = node->GetInputProperty(input, QStringLiteral("min")).toDouble();
double v = value.toDouble();
if (v < min) {
value = min;
}
}
if (node->HasInputProperty(input, QStringLiteral("max"))) {
double max = node->GetInputProperty(input, QStringLiteral("max")).toDouble();
double v = value.toDouble();
if (v > max) {
value = max;
}
}
end_value_ = value;
//input_->blockSignals(true);
if (input_.input().IsKeyframing()) {
dragging_key_->set_value(value);
} else {
node->SetSplitStandardValueOnTrack(input_, value);
}
//input_->blockSignals(false);
}
void NodeInputDragger::End(MultiUndoCommand* command)
{
if (!IsStarted()) {
return;
}
input_being_dragged--;
if (input_.input().node()->IsInputKeyframing(input_.input())) {
for (int i=0; i<created_keys_.size(); i++) {
// We created a keyframe in this process
command->add_child(new NodeParamInsertKeyframeCommand(input_.input().node(), created_keys_.at(i)));
}
// We just set a keyframe's value
// We do this even when inserting a keyframe because we don't actually perform an insert in this undo command
// so this will ensure the ValueChanged() signal is sent correctly
command->add_child(new NodeParamSetKeyframeValueCommand(dragging_key_, end_value_, start_value_));
} else {
// We just set the standard value
command->add_child(new NodeParamSetStandardValueCommand(input_, end_value_, start_value_));
}
input_.Reset();
created_keys_.clear();
}
}
| 4,526
|
C++
|
.cpp
| 116
| 32.258621
| 128
| 0.646024
|
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
|
18,970
|
param.cpp
|
olive-editor_olive/app/node/param.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 "param.h"
#include "node.h"
namespace olive {
QString NodeInput::name() const
{
if (IsValid()) {
return node_->GetInputName(input_);
} else {
return QString();
}
}
bool NodeInput::IsHidden() const
{
if (IsValid()) {
return node_->IsInputHidden(input_);
} else {
return false;
}
}
bool NodeInput::IsConnected() const
{
if (IsValid()) {
return node_->IsInputConnected(*this);
} else {
return false;
}
}
bool NodeInput::IsKeyframing() const
{
if (IsValid()) {
return node_->IsInputKeyframing(*this);
} else {
return false;
}
}
bool NodeInput::IsArray() const
{
if (IsValid()) {
return node_->InputIsArray(input_);
} else {
return false;
}
}
InputFlags NodeInput::GetFlags() const
{
if (IsValid()) {
return node_->GetInputFlags(input_);
} else {
return InputFlags(kInputFlagNormal);
}
}
QString NodeInput::GetInputName() const
{
if (IsValid()) {
return node_->GetInputName(input_);
} else {
return QString();
}
}
Node *NodeInput::GetConnectedOutput() const
{
if (IsValid()) {
return node_->GetConnectedOutput(*this);
} else {
return nullptr;
}
}
NodeValue::Type NodeInput::GetDataType() const
{
if (IsValid()) {
return node_->GetInputDataType(input_);
} else {
return NodeValue::kNone;
}
}
QVariant NodeInput::GetDefaultValue() const
{
if (IsValid()) {
return node_->GetDefaultValue(input_);
} else {
return QVariant();
}
}
QStringList NodeInput::GetComboBoxStrings() const
{
if (IsValid()) {
return node_->GetComboBoxStrings(input_);
} else {
return QStringList();
}
}
QVariant NodeInput::GetProperty(const QString &key) const
{
if (IsValid()) {
return node_->GetInputProperty(input_, key);
} else {
return QVariant();
}
}
QHash<QString, QVariant> NodeInput::GetProperties() const
{
if (IsValid()) {
return node_->GetInputProperties(input_);
} else {
return QHash<QString, QVariant>();
}
}
QVariant NodeInput::GetValueAtTime(const rational &time) const
{
if (IsValid()) {
return node_->GetValueAtTime(*this, time);
} else {
return QVariant();
}
}
NodeKeyframe* NodeInput::GetKeyframeAtTimeOnTrack(const rational &time, int track) const
{
if (IsValid()) {
return node_->GetKeyframeAtTimeOnTrack(*this, time, track);
} else {
return nullptr;
}
}
QVariant NodeInput::GetSplitDefaultValueForTrack(int track) const
{
if (IsValid()) {
return node_->GetSplitDefaultValueOnTrack(input_, track);
} else {
return QVariant();
}
}
int NodeInput::GetArraySize() const
{
if (IsValid() && element_ == -1) {
return node_->InputArraySize(input_);
} else {
return 0;
}
}
uint qHash(const NodeInput &i)
{
return qHash(i.node()) ^ qHash(i.input()) ^ ::qHash(i.element());
}
uint qHash(const NodeKeyframeTrackReference &i)
{
return qHash(i.input()) & ::qHash(i.track());
}
uint qHash(const NodeInputPair &i)
{
return qHash(i.node) & qHash(i.input);
}
}
| 3,717
|
C++
|
.cpp
| 166
| 19.60241
| 88
| 0.696763
|
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
|
18,971
|
keyframe.cpp
|
olive-editor_olive/app/node/keyframe.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 "keyframe.h"
#include "node.h"
namespace olive {
const NodeKeyframe::Type NodeKeyframe::kDefaultType = kLinear;
NodeKeyframe::NodeKeyframe(const rational &time, const QVariant &value, Type type, int track, int element, const QString &input, QObject *parent) :
time_(time),
value_(value),
type_(type),
bezier_control_in_(QPointF(0.0, 0.0)),
bezier_control_out_(QPointF(0.0, 0.0)),
input_(input),
track_(track),
element_(element),
previous_(nullptr),
next_(nullptr)
{
setParent(parent);
}
NodeKeyframe::NodeKeyframe()
{
type_ = NodeKeyframe::kLinear;
}
NodeKeyframe::~NodeKeyframe()
{
setParent(nullptr);
}
NodeKeyframe *NodeKeyframe::copy(int element, QObject *parent) const
{
NodeKeyframe* copy = new NodeKeyframe(time_, value_, type_, track_, element, input_, parent);
copy->bezier_control_in_ = bezier_control_in_;
copy->bezier_control_out_ = bezier_control_out_;
return copy;
}
NodeKeyframe *NodeKeyframe::copy(QObject* parent) const
{
return copy(element_, parent);
}
Node *NodeKeyframe::parent() const
{
return static_cast<Node*>(QObject::parent());
}
const rational &NodeKeyframe::time() const
{
return time_;
}
void NodeKeyframe::set_time(const rational &time)
{
time_ = time;
emit TimeChanged(time_);
}
const QVariant &NodeKeyframe::value() const
{
return value_;
}
void NodeKeyframe::set_value(const QVariant &value)
{
value_ = value;
emit ValueChanged(value_);
}
const NodeKeyframe::Type &NodeKeyframe::type() const
{
return type_;
}
void NodeKeyframe::set_type(const NodeKeyframe::Type &type)
{
if (type_ != type) {
set_type_no_bezier_adj(type);
if (type_ == kBezier) {
// Set some sane defaults if this keyframe existed in the track and was just changed
if (bezier_control_in_.isNull()) {
if (previous_) {
// Set the in point to be half way between
set_bezier_control_in(QPointF((previous_->time().toDouble() - this->time().toDouble()) * 0.5, 0.0));
} else {
set_bezier_control_in(QPointF(-1.0, 0.0));
}
}
if (bezier_control_out_.isNull()) {
if (next_) {
set_bezier_control_out(QPointF((next_->time().toDouble() - this->time().toDouble()) * 0.5, 0.0));
} else {
set_bezier_control_out(QPointF(1.0, 0.0));
}
}
}
}
}
void NodeKeyframe::set_type_no_bezier_adj(const Type &type)
{
type_ = type;
emit TypeChanged(type_);
}
const QPointF &NodeKeyframe::bezier_control_in() const
{
return bezier_control_in_;
}
void NodeKeyframe::set_bezier_control_in(const QPointF &control)
{
bezier_control_in_ = control;
emit BezierControlInChanged(bezier_control_in_);
}
const QPointF &NodeKeyframe::bezier_control_out() const
{
return bezier_control_out_;
}
void NodeKeyframe::set_bezier_control_out(const QPointF &control)
{
bezier_control_out_ = control;
emit BezierControlOutChanged(bezier_control_out_);
}
QPointF NodeKeyframe::valid_bezier_control_in() const
{
double t = time().toDouble();
qreal adjusted_x = t + bezier_control_in_.x();
if (previous_) {
// Limit to the point of that keyframe
adjusted_x = qMax(adjusted_x, previous_->time().toDouble());
}
return QPointF(adjusted_x - t, bezier_control_in_.y());
}
QPointF NodeKeyframe::valid_bezier_control_out() const
{
double t = time().toDouble();
qreal adjusted_x = t + bezier_control_out_.x();
if (next_) {
// Limit to the point of that keyframe
adjusted_x = qMin(adjusted_x, next_->time().toDouble());
}
return QPointF(adjusted_x - t, bezier_control_out_.y());
}
const QPointF &NodeKeyframe::bezier_control(NodeKeyframe::BezierType type) const
{
if (type == kInHandle) {
return bezier_control_in();
} else {
return bezier_control_out();
}
}
void NodeKeyframe::set_bezier_control(NodeKeyframe::BezierType type, const QPointF &control)
{
if (type == kInHandle) {
set_bezier_control_in(control);
} else {
set_bezier_control_out(control);
}
}
NodeKeyframe::BezierType NodeKeyframe::get_opposing_bezier_type(NodeKeyframe::BezierType type)
{
if (type == kInHandle) {
return kOutHandle;
} else {
return kInHandle;
}
}
bool NodeKeyframe::has_sibling_at_time(const rational &t) const
{
NodeKeyframe *k = parent()->GetKeyframeAtTimeOnTrack(input(), t, track(), element());
return k && k != this;
}
bool NodeKeyframe::load(QXmlStreamReader *reader, NodeValue::Type data_type)
{
QString key_input;
QPointF key_in_handle;
QPointF key_out_handle;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
key_input = attr.value().toString();
} else if (attr.name() == QStringLiteral("time")) {
this->set_time(rational::fromString(attr.value().toString().toStdString()));
} else if (attr.name() == QStringLiteral("type")) {
this->set_type_no_bezier_adj(static_cast<NodeKeyframe::Type>(attr.value().toInt()));
} else if (attr.name() == QStringLiteral("inhandlex")) {
key_in_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("inhandley")) {
key_in_handle.setY(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandlex")) {
key_out_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandley")) {
key_out_handle.setY(attr.value().toDouble());
}
}
this->set_value(NodeValue::StringToValue(data_type, reader->readElementText(), true));
this->set_bezier_control_in(key_in_handle);
this->set_bezier_control_out(key_out_handle);
return true;
}
void NodeKeyframe::save(QXmlStreamWriter *writer, NodeValue::Type data_type) const
{
writer->writeAttribute(QStringLiteral("input"), this->input());
writer->writeAttribute(QStringLiteral("time"), QString::fromStdString(this->time().toString()));
writer->writeAttribute(QStringLiteral("type"), QString::number(this->type()));
writer->writeAttribute(QStringLiteral("inhandlex"), QString::number(this->bezier_control_in().x()));
writer->writeAttribute(QStringLiteral("inhandley"), QString::number(this->bezier_control_in().y()));
writer->writeAttribute(QStringLiteral("outhandlex"), QString::number(this->bezier_control_out().x()));
writer->writeAttribute(QStringLiteral("outhandley"), QString::number(this->bezier_control_out().y()));
writer->writeCharacters(NodeValue::ValueToString(data_type, this->value(), true));
}
}
| 7,162
|
C++
|
.cpp
| 212
| 30.556604
| 147
| 0.704954
|
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
|
18,973
|
inputimmediate.cpp
|
olive-editor_olive/app/node/inputimmediate.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 "inputimmediate.h"
#include "common/lerp.h"
#include "common/tohex.h"
namespace olive {
NodeInputImmediate::NodeInputImmediate(NodeValue::Type type, const SplitValue &default_val) :
default_value_(default_val),
keyframing_(false)
{
set_data_type(type);
}
void NodeInputImmediate::set_standard_value_on_track(const QVariant &value, int track)
{
standard_value_.replace(track, value);
}
void NodeInputImmediate::set_split_standard_value(const SplitValue &value)
{
for (int i=0; i<value.size() && i<standard_value_.size(); i++) {
standard_value_[i] = value[i];
}
}
QVector<NodeKeyframe*> NodeInputImmediate::get_keyframe_at_time(const rational &time) const
{
QVector<NodeKeyframe*> keys;
for (int i=0;i<keyframe_tracks_.size();i++) {
NodeKeyframe* key_at_time = get_keyframe_at_time_on_track(time, i);
if (key_at_time) {
keys.append(key_at_time);
}
}
return keys;
}
NodeKeyframe* NodeInputImmediate::get_keyframe_at_time_on_track(const rational &time, int track) const
{
if (!is_using_standard_value(track)) {
foreach (NodeKeyframe* key, keyframe_tracks_.at(track)) {
if (key->time() == time) {
return key;
}
}
}
return nullptr;
}
NodeKeyframe* NodeInputImmediate::get_closest_keyframe_to_time_on_track(const rational &time, int track) const
{
if (is_using_standard_value(track)) {
return nullptr;
}
const NodeKeyframeTrack& key_track = keyframe_tracks_.at(track);
if (time <= key_track.first()->time()) {
return key_track.first();
}
if (time >= key_track.last()->time()) {
return key_track.last();
}
for (int i=1;i<key_track.size();i++) {
NodeKeyframe* prev_key = key_track.at(i-1);
NodeKeyframe* next_key = key_track.at(i);
if (prev_key->time() <= time && next_key->time() >= time) {
// Return whichever is closer
rational prev_diff = time - prev_key->time();
rational next_diff = next_key->time() - time;
if (next_diff < prev_diff) {
return next_key;
} else {
return prev_key;
}
}
}
return nullptr;
}
NodeKeyframe *NodeInputImmediate::get_closest_keyframe_before_time(const rational &time) const
{
NodeKeyframe* key = nullptr;
foreach (const NodeKeyframeTrack& track, keyframe_tracks_) {
foreach (NodeKeyframe* k, track) {
if (k->time() >= time) {
break;
} else if (!key || k->time() > key->time()) {
key = k;
}
}
}
return key;
}
NodeKeyframe* NodeInputImmediate::get_closest_keyframe_after_time(const rational &time) const
{
NodeKeyframe* key = nullptr;
foreach (const NodeKeyframeTrack& track, keyframe_tracks_) {
for (int i=track.size()-1;i>=0;i--) {
NodeKeyframe* k = track.at(i);
if (k->time() <= time) {
break;
} else if (!key || k->time() < key->time()) {
key = k;
}
}
}
return key;
}
NodeKeyframe::Type NodeInputImmediate::get_best_keyframe_type_for_time(const rational &time, int track) const
{
NodeKeyframe* closest_key = get_closest_keyframe_to_time_on_track(time, track);
if (closest_key) {
return closest_key->type();
}
return NodeKeyframe::kDefaultType;
}
bool NodeInputImmediate::has_keyframe_at_time(const rational &time) const
{
if (!is_keyframing()) {
return false;
}
// Loop through keyframes to see if any match
foreach (const NodeKeyframeTrack& track, keyframe_tracks_) {
foreach (NodeKeyframe* key, track) {
if (key->time() == time) {
return true;
}
}
}
// None match
return false;
}
void NodeInputImmediate::set_data_type(NodeValue::Type type)
{
int track_size = NodeValue::get_number_of_keyframe_tracks(type);
keyframe_tracks_.resize(track_size);
standard_value_.resize(track_size);
set_split_standard_value(default_value_);
}
NodeKeyframe *NodeInputImmediate::get_earliest_keyframe() const
{
NodeKeyframe* earliest = nullptr;
foreach (const NodeKeyframeTrack& track, keyframe_tracks_) {
if (!track.isEmpty()) {
NodeKeyframe* earliest_in_track = track.first();
if (!earliest
|| earliest_in_track->time() < earliest->time()) {
earliest = earliest_in_track;
}
}
}
return earliest;
}
NodeKeyframe *NodeInputImmediate::get_latest_keyframe() const
{
NodeKeyframe* latest = nullptr;
foreach (const NodeKeyframeTrack& track, keyframe_tracks_) {
if (!track.isEmpty()) {
NodeKeyframe* latest_in_track = track.last();
if (!latest
|| latest_in_track->time() > latest->time()) {
latest = latest_in_track;
}
}
}
return latest;
}
void NodeInputImmediate::insert_keyframe(NodeKeyframe* key)
{
NodeKeyframeTrack& key_track = keyframe_tracks_[key->track()];
int insert_index = key_track.size();
for (int i=0;i<key_track.size();i++) {
NodeKeyframe* compare = key_track.at(i);
// Ensure we aren't trying to insert two keyframes at the same time
Q_ASSERT(compare->time() != key->time());
if (compare->time() > key->time()) {
insert_index = i;
break;
}
}
key_track.insert(insert_index, key);
NodeKeyframe* previous = insert_index > 0 ? key_track.at(insert_index-1) : nullptr;
NodeKeyframe* next = insert_index < key_track.size()-1 ? key_track.at(insert_index+1) : nullptr;
key->set_previous(previous);
key->set_next(next);
if (previous) {
previous->set_next(key);
}
if (next) {
next->set_previous(key);
}
}
void NodeInputImmediate::remove_keyframe(NodeKeyframe *key)
{
if (key->previous()) {
key->previous()->set_next(key->next());
}
if (key->next()) {
key->next()->set_previous(key->previous());
}
key->set_previous(nullptr);
key->set_next(nullptr);
keyframe_tracks_[key->track()].removeOne(key);
}
void NodeInputImmediate::delete_all_keyframes(QObject* parent)
{
for (NodeKeyframeTrack& track : keyframe_tracks_) {
while (!track.isEmpty()) {
if (parent) {
track.first()->setParent(parent);
} else {
delete track.first();
}
}
}
}
}
| 6,802
|
C++
|
.cpp
| 222
| 26.599099
| 110
| 0.673983
|
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
|
18,974
|
valuedatabase.cpp
|
olive-editor_olive/app/node/valuedatabase.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 "valuedatabase.h"
namespace olive {
NodeValueTable NodeValueDatabase::Merge() const
{
QHash<QString, NodeValueTable> copy = tables_;
// Kinda hacky, but we don't need this table to slipstream
copy.remove(QStringLiteral("global"));
return NodeValueTable::Merge(copy.values());
}
}
| 1,014
|
C++
|
.cpp
| 24
| 39.458333
| 71
| 0.771195
|
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
|
18,975
|
project.cpp
|
olive-editor_olive/app/node/project.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 "project.h"
#include <QDir>
#include <QFileInfo>
#include "common/qtutils.h"
#include "common/xmlutils.h"
#include "core.h"
#include "dialog/progress/progress.h"
#include "node/color/ociobase/ociobase.h"
#include "node/factory.h"
#include "node/serializeddata.h"
#include "render/diskmanager.h"
#include "window/mainwindow/mainwindow.h"
namespace olive {
#define super QObject
const QString Project::kCacheLocationSettingKey = QStringLiteral("cachesetting");
const QString Project::kCachePathKey = QStringLiteral("customcachepath");
const QString Project::kColorConfigFilename = QStringLiteral("colorconfigfilename");
const QString Project::kDefaultInputColorSpaceKey = QStringLiteral("defaultinputcolorspace");
const QString Project::kColorReferenceSpace = QStringLiteral("colorreferencespace");
const QString Project::kRootKey = QStringLiteral("root");
const QString Project::kItemMimeType = QStringLiteral("application/x-oliveprojectitemdata");
Project::Project() :
root_(nullptr),
is_modified_(false),
autorecovery_saved_(true)
{
// Generate UUID for this project
RegenerateUuid();
// Initialize color manager
color_manager_ = new ColorManager(this);
color_manager_->Init();
}
Project::~Project()
{
Clear();
}
void Project::Initialize()
{
if (!root_) {
root_ = new Folder();
root_->setParent(this);
root_->SetLabel(tr("Root"));
settings_.insert(kRootKey, QString::number(reinterpret_cast<quintptr>(root_)));
}
}
void Project::Clear()
{
// By deleting the last nodes first, we assume that nodes that are most important are deleted last
// (e.g. Project's ColorManager or ProjectSettingsNode.
for (auto it=node_children_.cbegin(); it!=node_children_.cend(); it++) {
(*it)->SetCachesEnabled(false);
}
while (!node_children_.isEmpty()) {
delete node_children_.last();
}
}
SerializedData Project::Load(QXmlStreamReader *reader)
{
SerializedData data;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("uuid")) {
this->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("nodes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
QString id;
{
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
Node* node = NodeFactory::CreateFromID(id);
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
// Disable cache while node is being loaded (we'll re-enable it later)
node->SetCachesEnabled(false);
node->Load(reader, &data);
node->setParent(this);
}
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("settings")) {
while (XMLReadNextStartElement(reader)) {
QString key = reader->name().toString();
QString val = reader->readElementText();
SetSetting(key, val);
}
} else {
// Skip this
reader->skipCurrentElement();
}
}
// Resolve root if applicable
QString root = GetSetting(kRootKey);
if (!root.isEmpty()) {
quintptr r = root.toULongLong();
if (Node *n = data.node_ptrs.value(r)) {
Q_ASSERT(!root_);
root_ = dynamic_cast<Folder*>(n);
SetSetting(kRootKey, QString::number(reinterpret_cast<quintptr>(root_)));
}
}
return data;
}
void Project::Save(QXmlStreamWriter *writer) const
{
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
writer->writeTextElement(QStringLiteral("uuid"), this->GetUuid().toString());
if (!this->nodes().isEmpty()) {
writer->writeStartElement(QStringLiteral("nodes"));
foreach (Node* node, this->nodes()) {
writer->writeStartElement(QStringLiteral("node"));
node->Save(writer);
writer->writeEndElement(); // node
}
writer->writeEndElement(); // nodes
}
if (!this->settings_.isEmpty()) {
writer->writeStartElement(QStringLiteral("settings"));
for (auto it = this->settings_.cbegin(); it != this->settings_.cend(); it++) {
writer->writeTextElement(it.key(), it.value());
}
writer->writeEndElement(); // settings
}
}
int Project::GetNumberOfContextsNodeIsIn(Node *node, bool except_itself) const
{
int count = 0;
foreach (Node *ctx, node_children_) {
if (ctx->ContextContainsNode(node) && (!except_itself || ctx != node)) {
count++;
}
}
return count;
}
void Project::childEvent(QChildEvent *event)
{
super::childEvent(event);
Node* node = dynamic_cast<Node*>(event->child());
if (node) {
if (event->type() == QEvent::ChildAdded) {
node_children_.append(node);
// Connect signals
connect(node, &Node::InputConnected, this, &Project::InputConnected, Qt::DirectConnection);
connect(node, &Node::InputDisconnected, this, &Project::InputDisconnected, Qt::DirectConnection);
connect(node, &Node::ValueChanged, this, &Project::ValueChanged, Qt::DirectConnection);
connect(node, &Node::InputValueHintChanged, this, &Project::InputValueHintChanged, Qt::DirectConnection);
if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
connect(group, &NodeGroup::InputPassthroughAdded, this, &Project::GroupAddedInputPassthrough, Qt::DirectConnection);
connect(group, &NodeGroup::InputPassthroughRemoved, this, &Project::GroupRemovedInputPassthrough, Qt::DirectConnection);
connect(group, &NodeGroup::OutputPassthroughChanged, this, &Project::GroupChangedOutputPassthrough, Qt::DirectConnection);
}
emit NodeAdded(node);
emit node->AddedToGraph(this);
node->AddedToGraphEvent(this);
// Emit input connections
for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) {
if (nodes().contains(it->second)) {
emit InputConnected(it->second, it->first);
}
}
// Emit output connections
for (auto it=node->output_connections().cbegin(); it!=node->output_connections().cend(); it++) {
if (nodes().contains(it->second.node())) {
emit InputConnected(it->first, it->second);
}
}
} else if (event->type() == QEvent::ChildRemoved) {
node_children_.removeOne(node);
// Disconnect signals
disconnect(node, &Node::InputConnected, this, &Project::InputConnected);
disconnect(node, &Node::InputDisconnected, this, &Project::InputDisconnected);
disconnect(node, &Node::ValueChanged, this, &Project::ValueChanged);
disconnect(node, &Node::InputValueHintChanged, this, &Project::InputValueHintChanged);
if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
disconnect(group, &NodeGroup::InputPassthroughAdded, this, &Project::GroupAddedInputPassthrough);
disconnect(group, &NodeGroup::InputPassthroughRemoved, this, &Project::GroupRemovedInputPassthrough);
disconnect(group, &NodeGroup::OutputPassthroughChanged, this, &Project::GroupChangedOutputPassthrough);
}
emit NodeRemoved(node);
emit node->RemovedFromGraph(this);
node->RemovedFromGraphEvent(this);
// Remove from any contexts
foreach (Node *context, node_children_) {
context->RemoveNodeFromContext(node);
}
}
}
}
QString Project::name() const
{
if (filename_.isEmpty()) {
return tr("(untitled)");
} else {
return QFileInfo(filename_).completeBaseName();
}
}
const QString &Project::filename() const
{
return filename_;
}
QString Project::pretty_filename() const
{
QString fn = filename();
if (fn.isEmpty()) {
return tr("(untitled)");
} else {
return fn;
}
}
void Project::set_filename(const QString &s)
{
filename_ = s;
#ifdef Q_OS_WINDOWS
// Prevents filenames
filename_.replace('/', '\\');
#endif
emit NameChanged();
}
void Project::set_modified(bool e)
{
is_modified_ = e;
set_autorecovery_saved(!e);
emit ModifiedChanged(is_modified_);
}
bool Project::has_autorecovery_been_saved() const
{
return autorecovery_saved_;
}
void Project::set_autorecovery_saved(bool e)
{
autorecovery_saved_ = e;
}
bool Project::is_new() const
{
return !is_modified_ && filename_.isEmpty();
}
QString Project::get_cache_alongside_project_path() const
{
if (!filename_.isEmpty()) {
// Non-translated string so the path doesn't change if the language does
return QFileInfo(filename_).dir().filePath(QStringLiteral("cache"));
}
return QString();
}
QString Project::cache_path() const
{
CacheSetting setting = GetCacheLocationSetting();
switch (setting) {
case kCacheUseDefaultLocation:
break;
case kCacheCustomPath:
{
QString cache_path = GetCustomCachePath();
if (cache_path.isEmpty()) {
return cache_path;
}
break;
}
case kCacheStoreAlongsideProject:
{
QString alongside = get_cache_alongside_project_path();
if (!alongside.isEmpty()) {
return alongside;
}
break;
}
}
return DiskManager::instance()->GetDefaultCachePath();
}
void Project::RegenerateUuid()
{
uuid_ = QUuid::createUuid();
}
Project *Project::GetProjectFromObject(const QObject *o)
{
return QtUtils::GetParentOfType<Project>(o);
}
void Project::SetSetting(const QString &key, const QString &value)
{
settings_.insert(key, value);
emit SettingChanged(key, value);
if (key == kColorReferenceSpace) {
emit color_manager_->ReferenceSpaceChanged(value);
} else if (key == kColorConfigFilename) {
color_manager_->UpdateConfigFromFilename();
} else if (key == kDefaultInputColorSpaceKey) {
emit color_manager_->DefaultInputChanged(value);
}
}
}
| 10,833
|
C++
|
.cpp
| 316
| 29.541139
| 130
| 0.685961
|
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
|
18,976
|
value.cpp
|
olive-editor_olive/app/node/value.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 "value.h"
#include <QCoreApplication>
#include <QMatrix4x4>
#include <QVector2D>
#include <QVector3D>
#include <QVector4D>
#include "common/tohex.h"
#include "render/subtitleparams.h"
#include "render/videoparams.h"
namespace olive {
QString NodeValue::ValueToString(Type data_type, const QVariant &value, bool value_is_a_key_track)
{
if (!value_is_a_key_track && data_type == kVec2) {
QVector2D vec = value.value<QVector2D>();
return QStringLiteral("%1:%2").arg(QString::number(vec.x()),
QString::number(vec.y()));
} else if (!value_is_a_key_track && data_type == kVec3) {
QVector3D vec = value.value<QVector3D>();
return QStringLiteral("%1:%2:%3").arg(QString::number(vec.x()),
QString::number(vec.y()),
QString::number(vec.z()));
} else if (!value_is_a_key_track && data_type == kVec4) {
QVector4D vec = value.value<QVector4D>();
return QStringLiteral("%1:%2:%3:%4").arg(QString::number(vec.x()),
QString::number(vec.y()),
QString::number(vec.z()),
QString::number(vec.w()));
} else if (!value_is_a_key_track && data_type == kColor) {
Color c = value.value<Color>();
return QStringLiteral("%1:%2:%3:%4").arg(QString::number(c.red()),
QString::number(c.green()),
QString::number(c.blue()),
QString::number(c.alpha()));
} else if (!value_is_a_key_track && data_type == kBezier) {
Bezier b = value.value<Bezier>();
return QStringLiteral("%1:%2:%3:%4:%5:%6").arg(QString::number(b.x()),
QString::number(b.y()),
QString::number(b.cp1_x()),
QString::number(b.cp1_y()),
QString::number(b.cp2_x()),
QString::number(b.cp2_y()));
} else if (data_type == kRational) {
return QString::fromStdString(value.value<rational>().toString());
} else if (data_type == kTexture
|| data_type == kSamples
|| data_type == kNone) {
// These data types need no XML representation
return QString();
} else if (data_type == kInt) {
return QString::number(value.value<int64_t>());
} else if (data_type == kBinary) {
return value.toByteArray().toBase64();
} else {
if (value.canConvert<QString>()) {
return value.toString();
}
if (!value.isNull()) {
qWarning() << "Failed to convert type" << ToHex(data_type) << "to string";
}
return QString();
}
}
QVector<QVariant> NodeValue::split_normal_value_into_track_values(Type type, const QVariant &value)
{
QVector<QVariant> vals(get_number_of_keyframe_tracks(type));
switch (type) {
case kVec2:
{
QVector2D vec = value.value<QVector2D>();
vals.replace(0, vec.x());
vals.replace(1, vec.y());
break;
}
case kVec3:
{
QVector3D vec = value.value<QVector3D>();
vals.replace(0, vec.x());
vals.replace(1, vec.y());
vals.replace(2, vec.z());
break;
}
case kVec4:
{
QVector4D vec = value.value<QVector4D>();
vals.replace(0, vec.x());
vals.replace(1, vec.y());
vals.replace(2, vec.z());
vals.replace(3, vec.w());
break;
}
case kColor:
{
Color c = value.value<Color>();
vals.replace(0, c.red());
vals.replace(1, c.green());
vals.replace(2, c.blue());
vals.replace(3, c.alpha());
break;
}
case kBezier:
{
Bezier b = value.value<Bezier>();
vals.replace(0, b.x());
vals.replace(1, b.y());
vals.replace(2, b.cp1_x());
vals.replace(3, b.cp1_y());
vals.replace(4, b.cp2_x());
vals.replace(5, b.cp2_y());
break;
}
default:
vals.replace(0, value);
}
return vals;
}
QVariant NodeValue::combine_track_values_into_normal_value(Type type, const QVector<QVariant> &split)
{
if (split.isEmpty()) {
return QVariant();
}
switch (type) {
case kVec2:
{
return QVector2D(split.at(0).toFloat(),
split.at(1).toFloat());
}
case kVec3:
{
return QVector3D(split.at(0).toFloat(),
split.at(1).toFloat(),
split.at(2).toFloat());
}
case kVec4:
{
return QVector4D(split.at(0).toFloat(),
split.at(1).toFloat(),
split.at(2).toFloat(),
split.at(3).toFloat());
}
case kColor:
{
return QVariant::fromValue(Color(split.at(0).toFloat(),
split.at(1).toFloat(),
split.at(2).toFloat(),
split.at(3).toFloat()));
}
case kBezier:
return QVariant::fromValue(Bezier(split.at(0).toDouble(),
split.at(1).toDouble(),
split.at(2).toDouble(),
split.at(3).toDouble(),
split.at(4).toDouble(),
split.at(5).toDouble()));
default:
return split.first();
}
}
int NodeValue::get_number_of_keyframe_tracks(Type type)
{
switch (type) {
case NodeValue::kVec2:
return 2;
case NodeValue::kVec3:
return 3;
case NodeValue::kVec4:
case NodeValue::kColor:
return 4;
case NodeValue::kBezier:
return 6;
default:
return 1;
}
}
QVariant NodeValue::StringToValue(Type data_type, const QString &string, bool value_is_a_key_track)
{
if (!value_is_a_key_track && data_type == kVec2) {
QStringList vals = string.split(':');
ValidateVectorString(&vals, 2);
return QVector2D(vals.at(0).toFloat(), vals.at(1).toFloat());
} else if (!value_is_a_key_track && data_type == kVec3) {
QStringList vals = string.split(':');
ValidateVectorString(&vals, 3);
return QVector3D(vals.at(0).toFloat(), vals.at(1).toFloat(), vals.at(2).toFloat());
} else if (!value_is_a_key_track && data_type == kVec4) {
QStringList vals = string.split(':');
ValidateVectorString(&vals, 4);
return QVector4D(vals.at(0).toFloat(), vals.at(1).toFloat(), vals.at(2).toFloat(), vals.at(3).toFloat());
} else if (!value_is_a_key_track && data_type == kColor) {
QStringList vals = string.split(':');
ValidateVectorString(&vals, 4);
return QVariant::fromValue(Color(vals.at(0).toDouble(), vals.at(1).toDouble(), vals.at(2).toDouble(), vals.at(3).toDouble()));
} else if (!value_is_a_key_track && data_type == kBezier) {
QStringList vals = string.split(':');
ValidateVectorString(&vals, 6);
return QVariant::fromValue(Bezier(vals.at(0).toDouble(), vals.at(1).toDouble(), vals.at(2).toDouble(), vals.at(3).toDouble(), vals.at(4).toDouble(), vals.at(5).toDouble()));
} else if (data_type == kInt) {
return QVariant::fromValue(string.toLongLong());
} else if (data_type == kRational) {
return QVariant::fromValue(rational::fromString(string.toStdString()));
} else if (data_type == kBinary) {
return QByteArray::fromBase64(string.toLatin1());
} else {
return string;
}
}
void NodeValue::ValidateVectorString(QStringList* list, int count)
{
while (list->size() < count) {
list->append(QStringLiteral("0"));
}
}
QString NodeValue::GetPrettyDataTypeName(Type type)
{
switch (type) {
case kNone:
return QCoreApplication::translate("NodeValue", "None");
case kInt:
case kCombo:
return QCoreApplication::translate("NodeValue", "Integer");
case kFloat:
return QCoreApplication::translate("NodeValue", "Float");
case kRational:
return QCoreApplication::translate("NodeValue", "Rational");
case kBoolean:
return QCoreApplication::translate("NodeValue", "Boolean");
case kColor:
return QCoreApplication::translate("NodeValue", "Color");
case kMatrix:
return QCoreApplication::translate("NodeValue", "Matrix");
case kText:
return QCoreApplication::translate("NodeValue", "Text");
case kFont:
return QCoreApplication::translate("NodeValue", "Font");
case kFile:
return QCoreApplication::translate("NodeValue", "File");
case kTexture:
return QCoreApplication::translate("NodeValue", "Texture");
case kSamples:
return QCoreApplication::translate("NodeValue", "Samples");
case kVec2:
return QCoreApplication::translate("NodeValue", "Vector 2D");
case kVec3:
return QCoreApplication::translate("NodeValue", "Vector 3D");
case kVec4:
return QCoreApplication::translate("NodeValue", "Vector 4D");
case kBezier:
return QCoreApplication::translate("NodeValue", "Bezier");
case kVideoParams:
return QCoreApplication::translate("NodeValue", "Video Parameters");
case kAudioParams:
return QCoreApplication::translate("NodeValue", "Audio Parameters");
case kSubtitleParams:
return QCoreApplication::translate("NodeValue", "Subtitle Parameters");
case kBinary:
return QCoreApplication::translate("NodeValue", "Binary");
case kDataTypeCount:
break;
}
return QCoreApplication::translate("NodeValue", "Unknown");
}
QString NodeValue::GetDataTypeName(Type type)
{
switch (type) {
case kNone:
return QStringLiteral("none");
case kInt:
return QStringLiteral("int");
case kCombo:
return QStringLiteral("combo");
case kFloat:
return QStringLiteral("float");
case kRational:
return QStringLiteral("rational");
case kBoolean:
return QStringLiteral("bool");
case kColor:
return QStringLiteral("color");
case kMatrix:
return QStringLiteral("matrix");
case kText:
return QStringLiteral("text");
case kFont:
return QStringLiteral("font");
case kFile:
return QStringLiteral("file");
case kTexture:
return QStringLiteral("texture");
case kSamples:
return QStringLiteral("samples");
case kVec2:
return QStringLiteral("vec2");
case kVec3:
return QStringLiteral("vec3");
case kVec4:
return QStringLiteral("vec4");
case kBezier:
return QStringLiteral("bezier");
case kVideoParams:
return QStringLiteral("vparam");
case kAudioParams:
return QStringLiteral("aparam");
case kSubtitleParams:
return QStringLiteral("sparam");
case kBinary:
return QStringLiteral("binary");
case kDataTypeCount:
break;
}
return QString();
}
NodeValue::Type NodeValue::GetDataTypeFromName(const QString &n)
{
// Slow but easy to maintain
for (int i=0; i<kDataTypeCount; i++) {
Type t = static_cast<Type>(i);
if (GetDataTypeName(t) == n) {
return t;
}
}
return NodeValue::kNone;
}
NodeValue NodeValueTable::Get(const QVector<NodeValue::Type> &type, const QString &tag) const
{
int value_index = GetValueIndex(type, tag);
if (value_index >= 0) {
return values_.at(value_index);
}
return NodeValue();
}
NodeValue NodeValueTable::Take(const QVector<NodeValue::Type> &type, const QString &tag)
{
int value_index = GetValueIndex(type, tag);
if (value_index >= 0) {
return values_.takeAt(value_index);
}
return NodeValue();
}
bool NodeValueTable::Has(NodeValue::Type type) const
{
for (int i=values_.size() - 1;i>=0;i--) {
const NodeValue& v = values_.at(i);
if (v.type() & type) {
return true;
}
}
return false;
}
void NodeValueTable::Remove(const NodeValue &v)
{
for (int i=values_.size() - 1;i>=0;i--) {
const NodeValue& compare = values_.at(i);
if (compare == v) {
values_.removeAt(i);
return;
}
}
}
NodeValueTable NodeValueTable::Merge(QList<NodeValueTable> tables)
{
if (tables.size() == 1) {
return tables.first();
}
int row = 0;
NodeValueTable merged_table;
// Slipstreams all tables together
while (true) {
bool all_merged = true;
foreach (const NodeValueTable& t, tables) {
if (row < t.Count()) {
all_merged = false;
} else {
continue;
}
int row_index = t.Count() - 1 - row;
merged_table.Prepend(t.at(row_index));
}
row++;
if (all_merged) {
break;
}
}
return merged_table;
}
int NodeValueTable::GetValueIndex(const QVector<NodeValue::Type>& types, const QString &tag) const
{
int index = -1;
for (int i=values_.size() - 1;i>=0;i--) {
const NodeValue& v = values_.at(i);
if (types.contains(v.type())) {
index = i;
if (tag.isEmpty() || tag == v.tag()) {
break;
}
}
}
return index;
}
}
| 13,485
|
C++
|
.cpp
| 412
| 26.419903
| 177
| 0.619117
|
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
|
18,977
|
serializeddata.cpp
|
olive-editor_olive/app/node/serializeddata.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 Olive Studios LLC
This program is free software: you can 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 "serializeddata.h"
namespace olive {
}
| 769
|
C++
|
.cpp
| 17
| 42.352941
| 71
| 0.774194
|
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
|
18,978
|
nodeundo.cpp
|
olive-editor_olive/app/node/nodeundo.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 Olive Studios LLC
This program is free software: you can 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 "nodeundo.h"
namespace olive {
void NodeSetPositionCommand::redo()
{
added_ = !context_->ContextContainsNode(node_);
if (!added_) {
old_pos_ = context_->GetNodePositionDataInContext(node_);
}
context_->SetNodePositionInContext(node_, pos_);
}
void NodeSetPositionCommand::undo()
{
if (added_) {
context_->RemoveNodeFromContext(node_);
} else {
context_->SetNodePositionInContext(node_, old_pos_);
}
}
void NodeRemovePositionFromContextCommand::redo()
{
contained_ = context_->ContextContainsNode(node_);
if (contained_) {
old_pos_ = context_->GetNodePositionDataInContext(node_);
context_->RemoveNodeFromContext(node_);
}
}
void NodeRemovePositionFromContextCommand::undo()
{
if (contained_) {
context_->SetNodePositionInContext(node_, old_pos_);
}
}
void NodeRemovePositionFromAllContextsCommand::redo()
{
Project *graph = node_->parent();
foreach (Node* context, graph->nodes()) {
if (context->ContextContainsNode(node_)) {
contexts_.insert({context, context->GetNodePositionInContext(node_)});
context->RemoveNodeFromContext(node_);
}
}
}
void NodeRemovePositionFromAllContextsCommand::undo()
{
for (auto it = contexts_.crbegin(); it != contexts_.crend(); it++) {
it->first->SetNodePositionInContext(node_, it->second);
}
contexts_.clear();
}
void NodeSetPositionAndDependenciesRecursivelyCommand::prepare()
{
move_recursively(node_, pos_.position - context_->GetNodePositionDataInContext(node_).position);
}
void NodeSetPositionAndDependenciesRecursivelyCommand::redo()
{
for (auto it=commands_.cbegin(); it!=commands_.cend(); it++) {
(*it)->redo_now();
}
}
void NodeSetPositionAndDependenciesRecursivelyCommand::undo()
{
for (auto it=commands_.crbegin(); it!=commands_.crend(); it++) {
(*it)->undo_now();
}
}
void NodeSetPositionAndDependenciesRecursivelyCommand::move_recursively(Node *node, const QPointF &diff)
{
Node::Position pos = context_->GetNodePositionDataInContext(node);
pos += diff;
commands_.append(new NodeSetPositionCommand(node_, context_, pos));
for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) {
Node *output = it->second;
if (context_->ContextContainsNode(output)) {
move_recursively(output, diff);
}
}
}
NodeEdgeAddCommand::NodeEdgeAddCommand(Node *output, const NodeInput &input) :
output_(output),
input_(input),
remove_command_(nullptr)
{
}
NodeEdgeAddCommand::~NodeEdgeAddCommand()
{
delete remove_command_;
}
void NodeEdgeAddCommand::redo()
{
if (input_.IsConnected()) {
if (!remove_command_) {
remove_command_ = new NodeEdgeRemoveCommand(input_.GetConnectedOutput(), input_);
}
remove_command_->redo_now();
}
Node::ConnectEdge(output_, input_);
}
void NodeEdgeAddCommand::undo()
{
Node::DisconnectEdge(output_, input_);
if (remove_command_) {
remove_command_->undo_now();
}
}
Project *NodeEdgeAddCommand::GetRelevantProject() const
{
return output_->project();
}
NodeEdgeRemoveCommand::NodeEdgeRemoveCommand(Node *output, const NodeInput &input) :
output_(output),
input_(input)
{
}
void NodeEdgeRemoveCommand::redo()
{
Node::DisconnectEdge(output_, input_);
}
void NodeEdgeRemoveCommand::undo()
{
Node::ConnectEdge(output_, input_);
}
Project *NodeEdgeRemoveCommand::GetRelevantProject() const
{
return output_->project();
}
NodeAddCommand::NodeAddCommand(Project *graph, Node *node) :
graph_(graph),
node_(node)
{
// Ensures that when this command is destroyed, if redo() is never called again, the node will be destroyed too
node_->setParent(&memory_manager_);
}
void NodeAddCommand::PushToThread(QThread *thread)
{
memory_manager_.moveToThread(thread);
}
void NodeAddCommand::redo()
{
node_->setParent(graph_);
}
void NodeAddCommand::undo()
{
node_->setParent(&memory_manager_);
}
Project *NodeAddCommand::GetRelevantProject() const
{
return graph_;
}
void NodeRemoveAndDisconnectCommand::prepare()
{
command_ = new MultiUndoCommand();
// If this is a block, remove all links
if (node_->HasLinks()) {
command_->add_child(new NodeUnlinkAllCommand(node_));
}
// Disconnect everything
for (auto it=node_->input_connections().cbegin(); it!=node_->input_connections().cend(); it++) {
command_->add_child(new NodeEdgeRemoveCommand(it->second, it->first));
}
for (const Node::OutputConnection& conn : node_->output_connections()) {
command_->add_child(new NodeEdgeRemoveCommand(conn.first, conn.second));
}
command_->add_child(new NodeRemovePositionFromAllContextsCommand(node_));
}
void NodeRenameCommand::AddNode(Node *node, const QString &new_name)
{
nodes_.append(node);
new_labels_.append(new_name);
old_labels_.append(node->GetLabel());
}
void NodeRenameCommand::redo()
{
for (int i=0; i<nodes_.size(); i++) {
nodes_.at(i)->SetLabel(new_labels_.at(i));
}
}
void NodeRenameCommand::undo()
{
for (int i=0; i<nodes_.size(); i++) {
nodes_.at(i)->SetLabel(old_labels_.at(i));
}
}
Project *NodeRenameCommand::GetRelevantProject() const
{
return nodes_.isEmpty() ? nullptr : nodes_.first()->project();
}
NodeOverrideColorCommand::NodeOverrideColorCommand(Node *node, int index) :
node_(node),
new_index_(index)
{
}
Project *NodeOverrideColorCommand::GetRelevantProject() const
{
return node_->project();
}
void NodeOverrideColorCommand::redo()
{
old_index_ = node_->GetOverrideColor();
node_->SetOverrideColor(new_index_);
}
void NodeOverrideColorCommand::undo()
{
node_->SetOverrideColor(old_index_);
}
NodeViewDeleteCommand::NodeViewDeleteCommand()
{
}
void NodeViewDeleteCommand::AddNode(Node *node, Node *context)
{
if (ContainsNode(node, context)) {
return;
}
Node::ContextPair p = {node, context};
nodes_.append(p);
for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) {
if (context->ContextContainsNode(it->second)) {
AddEdge(it->second, it->first);
}
}
for (auto it=node->output_connections().cbegin(); it!=node->output_connections().cend(); it++) {
if (context->ContextContainsNode(it->second.node())) {
AddEdge(it->first, it->second);
}
}
}
void NodeViewDeleteCommand::AddEdge(Node *output, const NodeInput &input)
{
foreach (const Node::OutputConnection &edge, edges_) {
if (edge.first == output && edge.second == input) {
return;
}
}
edges_.append({output, input});
}
bool NodeViewDeleteCommand::ContainsNode(Node *node, Node *context)
{
foreach (const Node::ContextPair &pair, nodes_) {
if (pair.node == node && pair.context == context) {
return true;
}
}
return false;
}
Project *NodeViewDeleteCommand::GetRelevantProject() const
{
if (!nodes_.isEmpty()) {
return nodes_.first().node->project();
}
if (!edges_.isEmpty()) {
return edges_.first().first->project();
}
return nullptr;
}
void NodeViewDeleteCommand::redo()
{
foreach (const Node::OutputConnection &edge, edges_) {
Node::DisconnectEdge(edge.first, edge.second);
}
foreach (const Node::ContextPair &pair, nodes_) {
RemovedNode rn;
rn.node = pair.node;
rn.context = pair.context;
rn.pos = rn.context->GetNodePositionInContext(rn.node);
rn.context->RemoveNodeFromContext(rn.node);
// If node is no longer in any contexts and is not connected to anything, remove it
if (rn.node->parent()->GetNumberOfContextsNodeIsIn(rn.node, true) == 0
&& rn.node->input_connections().empty()
&& rn.node->output_connections().empty()) {
rn.removed_from_graph = rn.node->parent();
rn.node->setParent(&memory_manager_);
} else {
rn.removed_from_graph = nullptr;
}
removed_nodes_.append(rn);
}
}
void NodeViewDeleteCommand::undo()
{
for (auto rn=removed_nodes_.crbegin(); rn!=removed_nodes_.crend(); rn++) {
if (rn->removed_from_graph) {
rn->node->setParent(rn->removed_from_graph);
}
rn->context->SetNodePositionInContext(rn->node, rn->pos);
}
removed_nodes_.clear();
for (auto edge=edges_.crbegin(); edge!=edges_.crend(); edge++) {
Node::ConnectEdge(edge->first, edge->second);
}
}
NodeParamSetKeyframingCommand::NodeParamSetKeyframingCommand(const NodeInput &input, bool setting) :
input_(input),
new_setting_(setting)
{
}
Project *NodeParamSetKeyframingCommand::GetRelevantProject() const
{
return input_.node()->project();
}
void NodeParamSetKeyframingCommand::redo()
{
old_setting_ = input_.IsKeyframing();
input_.node()->SetInputIsKeyframing(input_, new_setting_);
}
void NodeParamSetKeyframingCommand::undo()
{
input_.node()->SetInputIsKeyframing(input_, old_setting_);
}
NodeParamSetKeyframeValueCommand::NodeParamSetKeyframeValueCommand(NodeKeyframe* key, const QVariant& value) :
key_(key),
old_value_(key_->value()),
new_value_(value)
{
}
NodeParamSetKeyframeValueCommand::NodeParamSetKeyframeValueCommand(NodeKeyframe* key, const QVariant &new_value, const QVariant &old_value) :
key_(key),
old_value_(old_value),
new_value_(new_value)
{
}
Project *NodeParamSetKeyframeValueCommand::GetRelevantProject() const
{
return key_->parent()->project();
}
void NodeParamSetKeyframeValueCommand::redo()
{
key_->set_value(new_value_);
}
void NodeParamSetKeyframeValueCommand::undo()
{
key_->set_value(old_value_);
}
NodeParamInsertKeyframeCommand::NodeParamInsertKeyframeCommand(Node* node, NodeKeyframe* keyframe) :
input_(node),
keyframe_(keyframe)
{
// Take ownership of the keyframe
undo();
}
Project *NodeParamInsertKeyframeCommand::GetRelevantProject() const
{
return input_->project();
}
void NodeParamInsertKeyframeCommand::redo()
{
keyframe_->setParent(input_);
}
void NodeParamInsertKeyframeCommand::undo()
{
keyframe_->setParent(&memory_manager_);
}
NodeParamRemoveKeyframeCommand::NodeParamRemoveKeyframeCommand(NodeKeyframe* keyframe) :
input_(keyframe->parent()),
keyframe_(keyframe)
{
}
Project *NodeParamRemoveKeyframeCommand::GetRelevantProject() const
{
return input_->project();
}
void NodeParamRemoveKeyframeCommand::redo()
{
// Removes from input
keyframe_->setParent(&memory_manager_);
}
void NodeParamRemoveKeyframeCommand::undo()
{
keyframe_->setParent(input_);
}
NodeParamSetKeyframeTimeCommand::NodeParamSetKeyframeTimeCommand(NodeKeyframe* key, const rational &time) :
key_(key),
old_time_(key->time()),
new_time_(time)
{
}
NodeParamSetKeyframeTimeCommand::NodeParamSetKeyframeTimeCommand(NodeKeyframe* key, const rational &new_time, const rational &old_time) :
key_(key),
old_time_(old_time),
new_time_(new_time)
{
}
Project *NodeParamSetKeyframeTimeCommand::GetRelevantProject() const
{
return key_->parent()->project();
}
void NodeParamSetKeyframeTimeCommand::redo()
{
key_->set_time(new_time_);
}
void NodeParamSetKeyframeTimeCommand::undo()
{
key_->set_time(old_time_);
}
NodeParamSetStandardValueCommand::NodeParamSetStandardValueCommand(const NodeKeyframeTrackReference& input, const QVariant &value) :
ref_(input),
old_value_(ref_.input().node()->GetStandardValue(ref_.input())),
new_value_(value)
{
}
NodeParamSetStandardValueCommand::NodeParamSetStandardValueCommand(const NodeKeyframeTrackReference& input, const QVariant &new_value, const QVariant &old_value) :
ref_(input),
old_value_(old_value),
new_value_(new_value)
{
}
Project *NodeParamSetStandardValueCommand::GetRelevantProject() const
{
return ref_.input().node()->project();
}
void NodeParamSetStandardValueCommand::redo()
{
ref_.input().node()->SetSplitStandardValueOnTrack(ref_, new_value_);
}
void NodeParamSetStandardValueCommand::undo()
{
ref_.input().node()->SetSplitStandardValueOnTrack(ref_, old_value_);
}
NodeParamArrayAppendCommand::NodeParamArrayAppendCommand(Node *node, const QString &input) :
node_(node),
input_(input)
{
}
Project *NodeParamArrayAppendCommand::GetRelevantProject() const
{
return node_->project();
}
void NodeParamArrayAppendCommand::redo()
{
node_->InputArrayAppend(input_);
}
void NodeParamArrayAppendCommand::undo()
{
node_->InputArrayRemoveLast(input_);
}
void NodeSetValueHintCommand::redo()
{
old_hint_ = input_.node()->GetValueHintForInput(input_.input(), input_.element());
input_.node()->SetValueHintForInput(input_.input(), new_hint_, input_.element());
}
void NodeSetValueHintCommand::undo()
{
input_.node()->SetValueHintForInput(input_.input(), old_hint_, input_.element());
}
Project *NodeArrayInsertCommand::GetRelevantProject() const
{
return node_->project();
}
Project *NodeArrayRemoveCommand::GetRelevantProject() const
{
return node_->project();
}
Project *NodeArrayResizeCommand::GetRelevantProject() const
{
return node_->project();
}
void NodeImmediateRemoveAllKeyframesCommand::prepare()
{
for (const NodeKeyframeTrack& track : immediate_->keyframe_tracks()) {
keys_.append(track);
}
}
void NodeImmediateRemoveAllKeyframesCommand::redo()
{
for (auto it=keys_.cbegin(); it!=keys_.cend(); it++) {
(*it)->setParent(&memory_manager_);
}
}
void NodeImmediateRemoveAllKeyframesCommand::undo()
{
for (auto it=keys_.crbegin(); it!=keys_.crend(); it++) {
(*it)->setParent(&memory_manager_);
}
}
}
| 13,976
|
C++
|
.cpp
| 487
| 26.119097
| 163
| 0.73613
|
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
|
18,979
|
valuenode.cpp
|
olive-editor_olive/app/node/input/value/valuenode.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 "valuenode.h"
namespace olive {
const QString ValueNode::kTypeInput = QStringLiteral("type_in");
const QString ValueNode::kValueInput = QStringLiteral("value_in");
const QVector<NodeValue::Type> ValueNode::kSupportedTypes = {
NodeValue::kFloat,
NodeValue::kInt,
NodeValue::kRational,
NodeValue::kVec2,
NodeValue::kVec3,
NodeValue::kVec4,
NodeValue::kColor,
NodeValue::kText,
NodeValue::kMatrix,
NodeValue::kFont,
NodeValue::kBoolean,
};
#define super Node
ValueNode::ValueNode()
{
AddInput(kTypeInput, NodeValue::kCombo, 0, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kValueInput, kSupportedTypes.first(), QVariant(), InputFlags(kInputFlagNotConnectable));
}
void ValueNode::Retranslate()
{
super::Retranslate();
SetInputName(kTypeInput, QStringLiteral("Type"));
SetInputName(kValueInput, QStringLiteral("Value"));
QStringList type_names;
type_names.reserve(kSupportedTypes.size());
foreach (NodeValue::Type type, kSupportedTypes) {
type_names.append(NodeValue::GetPrettyDataTypeName(type));
}
SetComboBoxStrings(kTypeInput, type_names);
}
void ValueNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
Q_UNUSED(globals)
// Ensure value is pushed onto the table
table->Push(value[kValueInput]);
}
void ValueNode::InputValueChangedEvent(const QString &input, int element)
{
if (input == kTypeInput) {
SetInputDataType(kValueInput, kSupportedTypes.at(GetStandardValue(kTypeInput).toInt()));
}
super::InputValueChangedEvent(input, element);
}
}
| 2,314
|
C++
|
.cpp
| 63
| 34.063492
| 110
| 0.77957
|
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
|
18,980
|
timeinput.cpp
|
olive-editor_olive/app/node/input/time/timeinput.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 "timeinput.h"
namespace olive {
#define super Node
TimeInput::TimeInput()
{
}
QString TimeInput::Name() const
{
return tr("Time");
}
QString TimeInput::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.time");
}
QVector<Node::CategoryID> TimeInput::Category() const
{
return {kCategoryTime};
}
QString TimeInput::Description() const
{
return tr("Generates the time (in seconds) at this frame.");
}
void TimeInput::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
table->Push(NodeValue::kFloat,
globals.time().in().toDouble(),
this,
false,
QStringLiteral("time"));
}
}
| 1,420
|
C++
|
.cpp
| 45
| 28.222222
| 105
| 0.7375
|
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
|
18,981
|
multicamnode.cpp
|
olive-editor_olive/app/node/input/multicam/multicamnode.cpp
|
#include "multicamnode.h"
#include "node/project/sequence/sequence.h"
namespace olive {
#define super Node
const QString MultiCamNode::kCurrentInput = QStringLiteral("current_in");
const QString MultiCamNode::kSourcesInput = QStringLiteral("sources_in");
const QString MultiCamNode::kSequenceInput = QStringLiteral("sequence_in");
const QString MultiCamNode::kSequenceTypeInput = QStringLiteral("sequence_type_in");
MultiCamNode::MultiCamNode()
{
AddInput(kCurrentInput, NodeValue::kCombo, InputFlags(kInputFlagStatic));
AddInput(kSourcesInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable | kInputFlagArray));
SetInputProperty(kSourcesInput, QStringLiteral("arraystart"), 1);
AddInput(kSequenceInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
AddInput(kSequenceTypeInput, NodeValue::kCombo, InputFlags(kInputFlagStatic | kInputFlagHidden));
sequence_ = nullptr;
}
QString MultiCamNode::Name() const
{
return tr("Multi-Cam");
}
QString MultiCamNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.multicam");
}
QVector<Node::CategoryID> MultiCamNode::Category() const
{
return {kCategoryTimeline};
}
QString MultiCamNode::Description() const
{
return tr("Allows easy switching between multiple sources.");
}
Node::ActiveElements MultiCamNode::GetActiveElementsAtTime(const QString &input, const TimeRange &r) const
{
if (input == kSourcesInput) {
int src = GetCurrentSource();
if (src >= 0 && src < GetSourceCount()) {
Node::ActiveElements a;
a.add(src);
return a;
} else {
return ActiveElements::kNoElements;
}
} else {
return super::GetActiveElementsAtTime(input, r);
}
}
void MultiCamNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
NodeValueArray arr = value[kSourcesInput].toArray();
if (!arr.empty()) {
table->Push(arr.begin()->second);
}
}
void MultiCamNode::IndexToRowCols(int index, int total_rows, int total_cols, int *row, int *col)
{
Q_UNUSED(total_rows)
*col = index%total_cols;
*row = index/total_cols;
}
Node *MultiCamNode::GetConnectedRenderOutput(const QString &input, int element) const
{
if (sequence_ && input == kSourcesInput && element >= 0 && element < GetSourceCount()) {
return GetTrackList()->GetTrackAt(element);
} else {
return Node::GetConnectedRenderOutput(input, element);
}
}
bool MultiCamNode::IsInputConnectedForRender(const QString &input, int element) const
{
if (sequence_ && input == kSourcesInput && element >= 0 && element < GetSourceCount()) {
return true;
} else {
return Node::IsInputConnectedForRender(input, element);
}
}
QVector<QString> MultiCamNode::IgnoreInputsForRendering() const
{
return {kSequenceInput};
}
void MultiCamNode::InputConnectedEvent(const QString &input, int element, Node *output)
{
if (input == kSequenceInput) {
if (Sequence *s = dynamic_cast<Sequence*>(output)) {
SetInputFlag(kSequenceTypeInput, kInputFlagHidden, false);
sequence_ = s;
}
}
}
void MultiCamNode::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
if (input == kSequenceInput) {
SetInputFlag(kSequenceTypeInput, kInputFlagHidden, true);
sequence_ = nullptr;
}
}
TrackList *MultiCamNode::GetTrackList() const
{
return sequence_->track_list(static_cast<Track::Type>(GetStandardValue(kSequenceTypeInput).toInt()));
}
void MultiCamNode::Retranslate()
{
super::Retranslate();
SetInputName(kCurrentInput, tr("Current"));
SetInputName(kSourcesInput, tr("Sources"));
SetInputName(kSequenceInput, tr("Sequence"));
SetInputName(kSequenceTypeInput, tr("Sequence Type"));
SetComboBoxStrings(kSequenceTypeInput, {tr("Video"), tr("Audio")});
QStringList names;
int name_count = GetSourceCount();
names.reserve(name_count);
for (int i=0; i<name_count; i++) {
QString src_name;
if (Node *n = GetConnectedRenderOutput(kSourcesInput, i)) {
src_name = n->Name();
}
names.append(tr("%1: %2").arg(QString::number(i+1), src_name));
}
SetComboBoxStrings(kCurrentInput, names);
}
int MultiCamNode::GetSourceCount() const
{
if (sequence_) {
return GetTrackList()->GetTrackCount();
} else {
return InputArraySize(kSourcesInput);
}
}
void MultiCamNode::GetRowsAndColumns(int sources, int *rows_in, int *cols_in)
{
int &rows = *rows_in;
int &cols = *cols_in;
rows = 1;
cols = 1;
while (rows*cols < sources) {
if (rows < cols) {
rows++;
} else {
cols++;
}
}
}
}
| 4,560
|
C++
|
.cpp
| 144
| 28.729167
| 108
| 0.736038
|
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
|
18,982
|
noise.cpp
|
olive-editor_olive/app/node/generator/noise/noise.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 "noise.h"
#include "widget/slider/floatslider.h"
namespace olive {
const QString NoiseGeneratorNode::kBaseIn = QStringLiteral("base_in");
const QString NoiseGeneratorNode::kColorInput = QStringLiteral("color_in");
const QString NoiseGeneratorNode::kStrengthInput = QStringLiteral("strength_in");
#define super Node
NoiseGeneratorNode::NoiseGeneratorNode()
{
AddInput(kBaseIn, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
AddInput(kStrengthInput, NodeValue::kFloat, 0.2);
SetInputProperty(kStrengthInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetInputProperty(kStrengthInput, QStringLiteral("min"), 0);
AddInput(kColorInput, NodeValue::kBoolean, false);
SetEffectInput(kBaseIn);
SetFlag(kVideoEffect);
}
QString NoiseGeneratorNode::Name() const
{
return tr("Noise");
}
QString NoiseGeneratorNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.noise");
}
QVector<Node::CategoryID> NoiseGeneratorNode::Category() const
{
return {kCategoryGenerator};
}
QString NoiseGeneratorNode::Description() const
{
return tr("Generates noise patterns");
}
void NoiseGeneratorNode::Retranslate()
{
super::Retranslate();
SetInputName(kBaseIn, tr("Base"));
SetInputName(kStrengthInput, tr("Strength"));
SetInputName(kColorInput, tr("Color"));
}
ShaderCode NoiseGeneratorNode::GetShaderCode(const ShaderRequest &request) const
{
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/noise.frag"));
}
void NoiseGeneratorNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
ShaderJob job(value);
job.Insert(value);
job.Insert(QStringLiteral("time_in"), NodeValue(NodeValue::kFloat, globals.time().in().toDouble(), this));
TexturePtr base = value[kBaseIn].toTexture();
table->Push(NodeValue::kTexture, Texture::Job(base ? base->params() : globals.vparams(), job), this);
}
}
| 2,631
|
C++
|
.cpp
| 67
| 36.910448
| 114
| 0.784561
|
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
|
18,983
|
textv2.cpp
|
olive-editor_olive/app/node/generator/text/textv2.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 "textv2.h"
#include <olive/core/core.h>
#include <QAbstractTextDocumentLayout>
#include <QDateTime>
#include <QTextDocument>
namespace olive {
#define super ShapeNodeBase
enum TextVerticalAlign {
kVerticalAlignTop,
kVerticalAlignCenter,
kVerticalAlignBottom,
};
const QString TextGeneratorV2::kTextInput = QStringLiteral("text_in");
const QString TextGeneratorV2::kHtmlInput = QStringLiteral("html_in");
const QString TextGeneratorV2::kVAlignInput = QStringLiteral("valign_in");
const QString TextGeneratorV2::kFontInput = QStringLiteral("font_in");
const QString TextGeneratorV2::kFontSizeInput = QStringLiteral("font_size_in");
TextGeneratorV2::TextGeneratorV2()
{
AddInput(kTextInput, NodeValue::kText, tr("Sample Text"));
AddInput(kHtmlInput, NodeValue::kBoolean, false);
AddInput(kVAlignInput, NodeValue::kCombo, kVerticalAlignTop);
AddInput(kFontInput, NodeValue::kFont);
AddInput(kFontSizeInput, NodeValue::kFloat, 72.0f);
SetStandardValue(kColorInput, QVariant::fromValue(Color(1.0f, 1.0f, 1.0)));
SetStandardValue(kSizeInput, QVector2D(400, 300));
SetFlag(kDontShowInCreateMenu);
}
QString TextGeneratorV2::Name() const
{
return tr("Text (Legacy)");
}
QString TextGeneratorV2::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.text2");
}
QVector<Node::CategoryID> TextGeneratorV2::Category() const
{
return {kCategoryGenerator};
}
QString TextGeneratorV2::Description() const
{
return tr("Generate rich text.");
}
void TextGeneratorV2::Retranslate()
{
super::Retranslate();
SetInputName(kTextInput, tr("Text"));
SetInputName(kHtmlInput, tr("Enable HTML"));
SetInputName(kFontInput, tr("Font"));
SetInputName(kFontSizeInput, tr("Font Size"));
SetInputName(kVAlignInput, tr("Vertical Align"));
SetComboBoxStrings(kVAlignInput, {tr("Top"), tr("Center"), tr("Bottom")});
}
void TextGeneratorV2::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
if (!value[kTextInput].toString().isEmpty()) {
GenerateJob job(value);
auto text_params = globals.vparams();
text_params.set_format(PixelFormat::F32);
table->Push(NodeValue::kTexture, Texture::Job(text_params, job), this);
}
}
void TextGeneratorV2::GenerateFrame(FramePtr frame, const GenerateJob& job) const
{
// This could probably be more optimized, but for now we use Qt to draw to a QImage.
// QImages only support integer pixels and we use float pixels, so what we do here is draw onto
// a single-channel QImage (alpha only) and then transplant that alpha channel to our float buffer
// with correct float RGB.
QImage img(frame->width(), frame->height(), QImage::Format_Grayscale8);
img.fill(Qt::transparent);
// 72 DPI in DPM (72 / 2.54 * 100)
const int dpm = 2835;
img.setDotsPerMeterX(dpm);
img.setDotsPerMeterY(dpm);
QTextDocument text_doc;
text_doc.documentLayout()->setPaintDevice(&img);
// Set default font
QFont default_font;
default_font.setFamily(job.Get(kFontInput).toString());
default_font.setPointSizeF(job.Get(kFontSizeInput).toDouble());
text_doc.setDefaultFont(default_font);
QString html = job.Get(kTextInput).toString();
if (job.Get(kHtmlInput).toBool()) {
html.replace('\n', QStringLiteral("<br>"));
text_doc.setHtml(html);
} else {
text_doc.setPlainText(html);
}
QVector2D size = job.Get(kSizeInput).toVec2();
text_doc.setTextWidth(size.x());
// Draw rich text onto image
QPainter p(&img);
p.scale(1.0 / frame->video_params().divider(), 1.0 / frame->video_params().divider());
QVector2D pos = job.Get(kPositionInput).toVec2();
p.translate(pos.x() - size.x()/2, pos.y() - size.y()/2);
p.translate(frame->video_params().width()/2, frame->video_params().height()/2);
p.setClipRect(0, 0, size.x(), size.y());
TextVerticalAlign valign = static_cast<TextVerticalAlign>(job.Get(kVAlignInput).toInt());
int doc_height = text_doc.size().height();
switch (valign) {
case kVerticalAlignTop:
// Do nothing
break;
case kVerticalAlignCenter:
// Center align
p.translate(0, size.y() / 2 - doc_height / 2);
break;
case kVerticalAlignBottom:
p.translate(0, size.y() - doc_height);
break;
}
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.palette.setColor(QPalette::Text, Qt::white);
text_doc.documentLayout()->draw(&p, ctx);
// Transplant alpha channel to frame
Color rgba = job.Get(kColorInput).toColor();
#if defined(Q_PROCESSOR_X86) || defined(Q_PROCESSOR_ARM)
__m128 sse_color = _mm_loadu_ps(rgba.data());
#endif
float *frame_dst = reinterpret_cast<float*>(frame->data());
for (int y=0; y<frame->height(); y++) {
uchar *src_y = img.bits() + img.bytesPerLine() * y;
float *dst_y = frame_dst + y*frame->linesize_pixels()*VideoParams::kRGBAChannelCount;
for (int x=0; x<frame->width(); x++) {
float alpha = float(src_y[x]) / 255.0f;
float *dst = dst_y + x*VideoParams::kRGBAChannelCount;
#if defined(Q_PROCESSOR_X86) || defined(Q_PROCESSOR_ARM)
__m128 sse_alpha = _mm_load1_ps(&alpha);
__m128 sse_res = _mm_mul_ps(sse_color, sse_alpha);
_mm_store_ps(dst, sse_res);
#else
for (int i=0; i<VideoParams::kRGBAChannelCount; i++) {
dst[i] = rgba.data()[i] * alpha;
}
#endif
}
}
}
}
| 6,017
|
C++
|
.cpp
| 154
| 35.928571
| 111
| 0.728648
|
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
|
18,984
|
textv3.cpp
|
olive-editor_olive/app/node/generator/text/textv3.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 "textv3.h"
#include <QAbstractTextDocumentLayout>
#include <QDateTime>
#include <QTextDocument>
#include "common/html.h"
#include "core.h"
#include "node/project.h"
#include "node/nodeundo.h"
namespace olive {
#define super ShapeNodeBase
enum TextVerticalAlign {
kVerticalAlignTop,
kVerticalAlignCenter,
kVerticalAlignBottom,
};
const QString TextGeneratorV3::kTextInput = QStringLiteral("text_in");
const QString TextGeneratorV3::kVerticalAlignmentInput = QStringLiteral("valign_in");
const QString TextGeneratorV3::kUseArgsInput = QStringLiteral("use_args_in");
const QString TextGeneratorV3::kArgsInput = QStringLiteral("args_in");
TextGeneratorV3::TextGeneratorV3() :
ShapeNodeBase(false),
dont_emit_valign_(false)
{
AddInput(kTextInput, NodeValue::kText, QStringLiteral("<p style='font-size: 72pt; color: white;'>%1</p>").arg(tr("Sample Text")));
SetInputProperty(kTextInput, QStringLiteral("vieweronly"), true);
SetStandardValue(kSizeInput, QVector2D(400, 300));
AddInput(kVerticalAlignmentInput, NodeValue::kCombo, InputFlags(kInputFlagHidden | kInputFlagStatic));
AddInput(kUseArgsInput, NodeValue::kBoolean, true, InputFlags(kInputFlagHidden | kInputFlagStatic));
AddInput(kArgsInput, NodeValue::kText, InputFlags(kInputFlagArray));
SetInputProperty(kArgsInput, QStringLiteral("arraystart"), 1);
text_gizmo_ = new TextGizmo(this);
text_gizmo_->SetInput(NodeInput(this, kTextInput));
connect(text_gizmo_, &TextGizmo::Activated, this, &TextGeneratorV3::GizmoActivated);
connect(text_gizmo_, &TextGizmo::Deactivated, this, &TextGeneratorV3::GizmoDeactivated);
}
QString TextGeneratorV3::Name() const
{
return tr("Text");
}
QString TextGeneratorV3::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.text3");
}
QVector<Node::CategoryID> TextGeneratorV3::Category() const
{
return {kCategoryGenerator};
}
QString TextGeneratorV3::Description() const
{
return tr("Generate rich text.");
}
void TextGeneratorV3::Retranslate()
{
super::Retranslate();
SetInputName(kTextInput, tr("Text"));
SetInputName(kVerticalAlignmentInput, tr("Vertical Alignment"));
SetComboBoxStrings(kVerticalAlignmentInput, {tr("Top"), tr("Middle"), tr("Bottom")});
SetInputName(kArgsInput, tr("Arguments"));
}
void TextGeneratorV3::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
QString text = value[kTextInput].toString();
if (value[kUseArgsInput].toBool()) {
auto args = value[kArgsInput].toArray();
if (!args.empty()) {
QStringList list;
list.reserve(args.size());
for (size_t i=0; i<args.size(); i++) {
list.append(args[i].toString());
}
text = FormatString(text, list);
}
}
if (!text.isEmpty()) {
TexturePtr base = value[kTextInput].toTexture();
VideoParams text_params = base ? base->params() : globals.vparams();
text_params.set_format(PixelFormat::U8);
text_params.set_colorspace(project()->color_manager()->GetDefaultInputColorSpace());
GenerateJob job(value);
job.Insert(kTextInput, NodeValue(NodeValue::kText, text));
PushMergableJob(value, Texture::Job(text_params, job), table);
} else if (value[kBaseInput].toTexture()) {
table->Push(value[kBaseInput]);
}
}
void TextGeneratorV3::GenerateFrame(FramePtr frame, const GenerateJob& job) const
{
QImage img(reinterpret_cast<uchar*>(frame->data()), frame->width(), frame->height(), frame->linesize_bytes(), QImage::Format_RGBA8888_Premultiplied);
img.fill(Qt::transparent);
// 96 DPI in DPM (96 / 2.54 * 100)
const int dpm = 3780;
img.setDotsPerMeterX(dpm);
img.setDotsPerMeterY(dpm);
QTextDocument text_doc;
text_doc.documentLayout()->setPaintDevice(&img);
QString html = job.Get(kTextInput).toString();
Html::HtmlToDoc(&text_doc, html);
QVector2D size = job.Get(kSizeInput).toVec2();
text_doc.setTextWidth(size.x());
// Draw rich text onto image
QPainter p(&img);
p.scale(1.0 / frame->video_params().divider(), 1.0 / frame->video_params().divider());
QVector2D pos = job.Get(kPositionInput).toVec2();
p.translate(pos.x() - size.x()/2, pos.y() - size.y()/2);
p.translate(frame->video_params().width()/2, frame->video_params().height()/2);
p.setClipRect(0, 0, size.x(), size.y());
switch (static_cast<VerticalAlignment>(job.Get(kVerticalAlignmentInput).toInt())) {
case kVAlignTop:
// Do nothing
break;
case kVAlignMiddle:
p.translate(0, size.y()/2-text_doc.size().height()/2);
break;
case kVAlignBottom:
p.translate(0, size.y()-text_doc.size().height());
break;
}
// Ensure default text color is white
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.palette.setColor(QPalette::Text, Qt::white);
text_doc.documentLayout()->draw(&p, ctx);
}
void TextGeneratorV3::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals)
{
super::UpdateGizmoPositions(row, globals);
QRectF rect = poly_gizmo()->GetPolygon().boundingRect();
text_gizmo_->SetRect(rect);
text_gizmo_->SetHtml(row[kTextInput].toString());
}
Qt::Alignment TextGeneratorV3::GetQtAlignmentFromOurs(VerticalAlignment v)
{
switch (v) {
case kVAlignTop:
return Qt::AlignTop;
case kVAlignMiddle:
return Qt::AlignVCenter;
case kVAlignBottom:
return Qt::AlignBottom;
}
return Qt::Alignment();
}
TextGeneratorV3::VerticalAlignment TextGeneratorV3::GetOurAlignmentFromQts(Qt::Alignment v)
{
switch (v) {
case Qt::AlignTop:
return kVAlignTop;
case Qt::AlignVCenter:
return kVAlignMiddle;
case Qt::AlignBottom:
return kVAlignBottom;
}
return kVAlignTop;
}
QString TextGeneratorV3::FormatString(const QString &input, const QStringList &args)
{
QString output;
output.reserve(input.size());
for (int i=0; i<input.size(); i++) {
const QChar &this_char = input.at(i);
if (i < input.size()-1 && this_char == '%') {
const QChar &next_char = input.at(i+1);
if (next_char == '%') {
// Double percent, append a single percent
output.append('%');
i++;
} else if (next_char.isDigit()) {
// Find length of number
QString num;
i++;
while (i < input.size() && input.at(i).isDigit()) {
num.append(input.at(i));
i++;
}
i--;
int index = num.toInt()-1;
if (index >= 0 && index < args.size()) {
output.append(args.at(index));
}
} else {
output.append(this_char);
}
} else {
output.append(this_char);
}
}
return output;
}
void TextGeneratorV3::InputValueChangedEvent(const QString &input, int element)
{
if (input == kVerticalAlignmentInput && !dont_emit_valign_) {
text_gizmo_->SetVerticalAlignment(GetQtAlignmentFromOurs(GetVerticalAlignment()));
}
super::InputValueChangedEvent(input, element);
}
void TextGeneratorV3::GizmoActivated()
{
SetStandardValue(kUseArgsInput, false);
connect(text_gizmo_, &TextGizmo::VerticalAlignmentChanged, this, &TextGeneratorV3::SetVerticalAlignmentUndoable);
dont_emit_valign_ = true;
}
void TextGeneratorV3::GizmoDeactivated()
{
SetStandardValue(kUseArgsInput, true);
disconnect(text_gizmo_, &TextGizmo::VerticalAlignmentChanged, this, &TextGeneratorV3::SetVerticalAlignmentUndoable);
dont_emit_valign_ = true;
}
void TextGeneratorV3::SetVerticalAlignmentUndoable(Qt::Alignment a)
{
Core::instance()->undo_stack()->push(new NodeParamSetStandardValueCommand(NodeInput(this, kVerticalAlignmentInput), GetOurAlignmentFromQts(a)), tr("Set Text Vertical Alignment"));
}
}
| 8,314
|
C++
|
.cpp
| 225
| 33.373333
| 181
| 0.72725
|
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
|
18,985
|
textv1.cpp
|
olive-editor_olive/app/node/generator/text/textv1.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 "textv1.h"
#include <QAbstractTextDocumentLayout>
#include <QTextDocument>
namespace olive {
enum TextVerticalAlign {
kVerticalAlignTop,
kVerticalAlignCenter,
kVerticalAlignBottom,
};
const QString TextGeneratorV1::kTextInput = QStringLiteral("text_in");
const QString TextGeneratorV1::kHtmlInput = QStringLiteral("html_in");
const QString TextGeneratorV1::kColorInput = QStringLiteral("color_in");
const QString TextGeneratorV1::kVAlignInput = QStringLiteral("valign_in");
const QString TextGeneratorV1::kFontInput = QStringLiteral("font_in");
const QString TextGeneratorV1::kFontSizeInput = QStringLiteral("font_size_in");
#define super Node
TextGeneratorV1::TextGeneratorV1()
{
AddInput(kTextInput, NodeValue::kText, tr("Sample Text"));
AddInput(kHtmlInput, NodeValue::kBoolean, false);
AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(1.0f, 1.0f, 1.0)));
AddInput(kVAlignInput, NodeValue::kCombo, 1);
AddInput(kFontInput, NodeValue::kFont);
AddInput(kFontSizeInput, NodeValue::kFloat, 72.0f);
SetFlag(kDontShowInCreateMenu);
}
QString TextGeneratorV1::Name() const
{
return tr("Text (Legacy)");
}
QString TextGeneratorV1::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.textgenerator");
}
QVector<Node::CategoryID> TextGeneratorV1::Category() const
{
return {kCategoryGenerator};
}
QString TextGeneratorV1::Description() const
{
return tr("Generate rich text.");
}
void TextGeneratorV1::Retranslate()
{
super::Retranslate();
SetInputName(kTextInput, tr("Text"));
SetInputName(kHtmlInput, tr("Enable HTML"));
SetInputName(kFontInput, tr("Font"));
SetInputName(kFontSizeInput, tr("Font Size"));
SetInputName(kColorInput, tr("Color"));
SetInputName(kVAlignInput, tr("Vertical Align"));
SetComboBoxStrings(kVAlignInput, {tr("Top"), tr("Center"), tr("Bottom")});
}
void TextGeneratorV1::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
if (!value[kTextInput].toString().isEmpty()) {
table->Push(NodeValue::kTexture, Texture::Job(globals.vparams(), GenerateJob(value)), this);
}
}
void TextGeneratorV1::GenerateFrame(FramePtr frame, const GenerateJob& job) const
{
// This could probably be more optimized, but for now we use Qt to draw to a QImage.
// QImages only support integer pixels and we use float pixels, so what we do here is draw onto
// a single-channel QImage (alpha only) and then transplant that alpha channel to our float buffer
// with correct float RGB.
QImage img(frame->width(), frame->height(), QImage::Format_Grayscale8);
img.fill(0);
QTextDocument text_doc;
// Set default font
QFont default_font;
default_font.setFamily(job.Get(kFontInput).toString());
default_font.setPointSizeF(job.Get(kFontSizeInput).toDouble());
text_doc.setDefaultFont(default_font);
// Center by default
text_doc.setDefaultTextOption(QTextOption(Qt::AlignCenter));
QString html = job.Get(kTextInput).toString();
if (job.Get(kHtmlInput).toBool()) {
html.replace('\n', QStringLiteral("<br>"));
text_doc.setHtml(html);
} else {
text_doc.setPlainText(html);
}
// Align to 80% width because that's considered the "title safe" area
int tenth_of_width = frame->video_params().width() / 10;
text_doc.setTextWidth(tenth_of_width * 8);
// Draw rich text onto image
QPainter p(&img);
p.scale(1.0 / frame->video_params().divider(), 1.0 / frame->video_params().divider());
// Push 10% inwards to compensate for title safe area
p.translate(tenth_of_width, 0);
TextVerticalAlign valign = static_cast<TextVerticalAlign>(job.Get(kVAlignInput).toInt());
int doc_height = text_doc.size().height();
switch (valign) {
case kVerticalAlignTop:
// Push 10% inwards for title safe area
p.translate(0, frame->video_params().height() / 10);
break;
case kVerticalAlignCenter:
// Center align
p.translate(0, frame->video_params().height() / 2 - doc_height / 2);
break;
case kVerticalAlignBottom:
// Push 10% inwards for title safe area
p.translate(0, frame->video_params().height() - doc_height - frame->video_params().height() / 10);
break;
}
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.palette.setColor(QPalette::Text, Qt::white);
text_doc.documentLayout()->draw(&p, ctx);
// Transplant alpha channel to frame
Color rgb = job.Get(kColorInput).toColor();
for (int x=0; x<frame->width(); x++) {
for (int y=0; y<frame->height(); y++) {
uchar src_alpha = img.bits()[img.bytesPerLine() * y + x];
float alpha = float(src_alpha) / 255.0f;
frame->set_pixel(x, y, Color(rgb.red() * alpha, rgb.green() * alpha, rgb.blue() * alpha, alpha));
}
}
}
}
| 5,449
|
C++
|
.cpp
| 134
| 37.656716
| 111
| 0.739007
|
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
|
18,986
|
polygon.cpp
|
olive-editor_olive/app/node/generator/polygon/polygon.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 "polygon.h"
#include <QGuiApplication>
#include <QVector2D>
namespace olive {
const QString PolygonGenerator::kPointsInput = QStringLiteral("points_in");
const QString PolygonGenerator::kColorInput = QStringLiteral("color_in");
#define super GeneratorWithMerge
PolygonGenerator::PolygonGenerator()
{
AddInput(kPointsInput, NodeValue::kBezier, QVector2D(0, 0), InputFlags(kInputFlagArray));
AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(1.0, 1.0, 1.0)));
const int kMiddleX = 135;
const int kMiddleY = 45;
const int kBottomX = 90;
const int kBottomY = 120;
const int kTopY = 135;
// The Default Pentagon(tm)
InputArrayResize(kPointsInput, 5);
SetSplitStandardValueOnTrack(kPointsInput, 0, 0, 0);
SetSplitStandardValueOnTrack(kPointsInput, 1, -kTopY, 0);
SetSplitStandardValueOnTrack(kPointsInput, 0, kMiddleX, 1);
SetSplitStandardValueOnTrack(kPointsInput, 1, -kMiddleY, 1);
SetSplitStandardValueOnTrack(kPointsInput, 0, kBottomX, 2);
SetSplitStandardValueOnTrack(kPointsInput, 1, kBottomY, 2);
SetSplitStandardValueOnTrack(kPointsInput, 0, -kBottomX, 3);
SetSplitStandardValueOnTrack(kPointsInput, 1, kBottomY, 3);
SetSplitStandardValueOnTrack(kPointsInput, 0, -kMiddleX, 4);
SetSplitStandardValueOnTrack(kPointsInput, 1, -kMiddleY, 4);
// Initiate gizmos
poly_gizmo_ = new PathGizmo(this);
}
QString PolygonGenerator::Name() const
{
return tr("Polygon");
}
QString PolygonGenerator::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.polygon");
}
QVector<Node::CategoryID> PolygonGenerator::Category() const
{
return {kCategoryGenerator};
}
QString PolygonGenerator::Description() const
{
return tr("Generate a 2D polygon of any amount of points.");
}
void PolygonGenerator::Retranslate()
{
super::Retranslate();
SetInputName(kPointsInput, tr("Points"));
SetInputName(kColorInput, tr("Color"));
}
ShaderJob PolygonGenerator::GetGenerateJob(const NodeValueRow &value, const VideoParams ¶ms) const
{
VideoParams p = params;
p.set_format(PixelFormat::U8);
auto job = Texture::Job(p, GenerateJob(value));
// Conversion to RGB
ShaderJob rgb;
rgb.SetShaderID(QStringLiteral("rgb"));
rgb.Insert(QStringLiteral("texture_in"), NodeValue(NodeValue::kTexture, job, this));
rgb.Insert(QStringLiteral("color_in"), value[kColorInput]);
return rgb;
}
void PolygonGenerator::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
PushMergableJob(value, Texture::Job(globals.vparams(), GetGenerateJob(value, globals.vparams())), table);
}
void PolygonGenerator::GenerateFrame(FramePtr frame, const GenerateJob &job) const
{
// This could probably be more optimized, but for now we use Qt to draw to a QImage.
// QImages only support integer pixels and we use float pixels, so what we do here is draw onto
// a single-channel QImage (alpha only) and then transplant that alpha channel to our float buffer
// with correct float RGB.
QImage img((uchar *) frame->data(), frame->width(), frame->height(), frame->linesize_bytes(), QImage::Format_RGBA8888_Premultiplied);
img.fill(Qt::transparent);
auto points = job.Get(kPointsInput).toArray();
QPainterPath path = GeneratePath(points, InputArraySize(kPointsInput));
QPainter p(&img);
double par = frame->video_params().pixel_aspect_ratio().toDouble();
p.scale(1.0 / frame->video_params().divider() / par, 1.0 / frame->video_params().divider());
p.translate(frame->video_params().width()/2 * par, frame->video_params().height()/2);
p.setBrush(Qt::white);
p.setPen(Qt::NoPen);
p.drawPath(path);
}
template<typename T>
NodeGizmo *PolygonGenerator::CreateAppropriateGizmo()
{
return new T(this);
}
template<>
NodeGizmo *PolygonGenerator::CreateAppropriateGizmo<PointGizmo>()
{
return AddDraggableGizmo<PointGizmo>();
}
template<typename T>
void PolygonGenerator::ValidateGizmoVectorSize(QVector<T*> &vec, int new_sz)
{
int old_sz = vec.size();
if (old_sz != new_sz) {
if (old_sz > new_sz) {
for (int i=new_sz; i<old_sz; i++) {
delete vec.at(i);
}
}
vec.resize(new_sz);
if (old_sz < new_sz) {
for (int i=old_sz; i<new_sz; i++) {
vec[i] = static_cast<T*>(CreateAppropriateGizmo<T>());
}
}
}
}
void PolygonGenerator::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals)
{
QVector2D res;
if (TexturePtr tex = row[kBaseInput].toTexture()) {
res = tex->virtual_resolution();
} else {
res = globals.square_resolution();
}
Imath::V2d half_res(res.x()/2, res.y()/2);
auto points = row[kPointsInput].toArray();
int current_pos_sz = gizmo_position_handles_.size();
ValidateGizmoVectorSize(gizmo_position_handles_, points.size());
ValidateGizmoVectorSize(gizmo_bezier_handles_, points.size() * 2);
ValidateGizmoVectorSize(gizmo_bezier_lines_, points.size() * 2);
for (int i=current_pos_sz; i<gizmo_position_handles_.size(); i++) {
gizmo_position_handles_.at(i)->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 0));
gizmo_position_handles_.at(i)->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 1));
PointGizmo *bez_gizmo1 = gizmo_bezier_handles_.at(i*2+0);
bez_gizmo1->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 2));
bez_gizmo1->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 3));
bez_gizmo1->SetShape(PointGizmo::kCircle);
bez_gizmo1->SetSmaller(true);
PointGizmo *bez_gizmo2 = gizmo_bezier_handles_.at(i*2+1);
bez_gizmo2->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 4));
bez_gizmo2->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPointsInput, i), 5));
bez_gizmo2->SetShape(PointGizmo::kCircle);
bez_gizmo2->SetSmaller(true);
}
int pts_sz = InputArraySize(kPointsInput);
if (!points.empty()) {
for (int i=0; i<pts_sz; i++) {
const Bezier &pt = points.at(i).toBezier();
Imath::V2d main = pt.to_vec() + half_res;
Imath::V2d cp1 = main + pt.control_point_1_to_vec();
Imath::V2d cp2 = main + pt.control_point_2_to_vec();
gizmo_position_handles_[i]->SetPoint(QPointF(main.x, main.y));
gizmo_bezier_handles_[i*2]->SetPoint(QPointF(cp1.x, cp1.y));
gizmo_bezier_lines_[i*2]->SetLine(QLineF(QPointF(main.x, main.y), QPointF(cp1.x, cp1.y)));
gizmo_bezier_handles_[i*2+1]->SetPoint(QPointF(cp2.x, cp2.y));
gizmo_bezier_lines_[i*2+1]->SetLine(QLineF(QPointF(main.x, main.y), QPointF(cp2.x, cp2.y)));
}
}
poly_gizmo_->SetPath(GeneratePath(points, pts_sz).translated(QPointF(half_res.x, half_res.y)));
}
ShaderCode PolygonGenerator::GetShaderCode(const ShaderRequest &request) const
{
if (request.id == QStringLiteral("rgb")) {
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/rgb.frag"));
} else {
return super::GetShaderCode(request);
}
}
void PolygonGenerator::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers)
{
DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender());
if (gizmo == poly_gizmo_) {
// FIXME: Drag all points
} else {
NodeInputDragger &x_drag = gizmo->GetDraggers()[0];
NodeInputDragger &y_drag = gizmo->GetDraggers()[1];
x_drag.Drag(x_drag.GetStartValue().toDouble() + x);
y_drag.Drag(y_drag.GetStartValue().toDouble() + y);
}
}
void PolygonGenerator::AddPointToPath(QPainterPath *path, const Bezier &before, const Bezier &after)
{
Imath::V2d a = before.to_vec() + before.control_point_2_to_vec();
Imath::V2d b = after.to_vec() + after.control_point_1_to_vec();
Imath::V2d c = after.to_vec();
path->cubicTo(QPointF(a.x, a.y), QPointF(b.x, b.y), QPointF(c.x, c.y));
}
QPainterPath PolygonGenerator::GeneratePath(const NodeValueArray &points, int size)
{
QPainterPath path;
if (!points.empty()) {
const Bezier &first_pt = points.at(0).toBezier();
Imath::V2d v = first_pt.to_vec();
path.moveTo(QPointF(v.x, v.y));
for (int i=1; i<size; i++) {
AddPointToPath(&path, points.at(i-1).toBezier(), points.at(i).toBezier());
}
AddPointToPath(&path, points.at(size-1).toBezier(), first_pt);
}
return path;
}
}
| 8,971
|
C++
|
.cpp
| 215
| 38.409302
| 135
| 0.727576
|
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
|
18,987
|
solid.cpp
|
olive-editor_olive/app/node/generator/solid/solid.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 "solid.h"
namespace olive {
const QString SolidGenerator::kColorInput = QStringLiteral("color_in");
#define super Node
SolidGenerator::SolidGenerator()
{
// Default to a color that isn't black
AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(1.0f, 0.0f, 0.0f, 1.0f)));
}
QString SolidGenerator::Name() const
{
return tr("Solid");
}
QString SolidGenerator::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.solidgenerator");
}
QVector<Node::CategoryID> SolidGenerator::Category() const
{
return {kCategoryGenerator};
}
QString SolidGenerator::Description() const
{
return tr("Generate a solid color.");
}
void SolidGenerator::Retranslate()
{
super::Retranslate();
SetInputName(kColorInput, tr("Color"));
}
void SolidGenerator::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
table->Push(NodeValue::kTexture, Texture::Job(globals.vparams(), ShaderJob(value)), this);
}
ShaderCode SolidGenerator::GetShaderCode(const ShaderRequest &request) const
{
Q_UNUSED(request)
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/solid.frag"));
}
}
| 1,876
|
C++
|
.cpp
| 54
| 32.518519
| 110
| 0.776915
|
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
|
18,988
|
matrix.cpp
|
olive-editor_olive/app/node/generator/matrix/matrix.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 "matrix.h"
#include <QMatrix4x4>
#include <QVector2D>
#include "widget/slider/floatslider.h"
namespace olive {
const QString MatrixGenerator::kPositionInput = QStringLiteral("pos_in");
const QString MatrixGenerator::kRotationInput = QStringLiteral("rot_in");
const QString MatrixGenerator::kScaleInput = QStringLiteral("scale_in");
const QString MatrixGenerator::kUniformScaleInput = QStringLiteral("uniform_scale_in");
const QString MatrixGenerator::kAnchorInput = QStringLiteral("anchor_in");
#define super Node
MatrixGenerator::MatrixGenerator()
{
AddInput(kPositionInput, NodeValue::kVec2, QVector2D(0.0, 0.0));
AddInput(kRotationInput, NodeValue::kFloat, 0.0);
AddInput(kScaleInput, NodeValue::kVec2, QVector2D(1.0f, 1.0f));
SetInputProperty(kScaleInput, QStringLiteral("min"), QVector2D(0, 0));
SetInputProperty(kScaleInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetInputProperty(kScaleInput, QStringLiteral("disable1"), true);
AddInput(kUniformScaleInput, NodeValue::kBoolean, true, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kAnchorInput, NodeValue::kVec2, QVector2D(0.0, 0.0));
}
QString MatrixGenerator::Name() const
{
return tr("Orthographic Matrix");
}
QString MatrixGenerator::ShortName() const
{
return tr("Ortho");
}
QString MatrixGenerator::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.ortho");
}
QVector<Node::CategoryID> MatrixGenerator::Category() const
{
return {kCategoryGenerator, kCategoryMath};
}
QString MatrixGenerator::Description() const
{
return tr("Generate an orthographic matrix using position, rotation, and scale.");
}
void MatrixGenerator::Retranslate()
{
super::Retranslate();
SetInputName(kPositionInput, tr("Position"));
SetInputName(kRotationInput, tr("Rotation"));
SetInputName(kScaleInput, tr("Scale"));
SetInputName(kUniformScaleInput, tr("Uniform Scale"));
SetInputName(kAnchorInput, tr("Anchor Point"));
}
void MatrixGenerator::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
// Push matrix output
QMatrix4x4 mat = GenerateMatrix(value, false, false, false, QMatrix4x4());
table->Push(NodeValue::kMatrix, mat, this);
}
QMatrix4x4 MatrixGenerator::GenerateMatrix(const NodeValueRow &value, bool ignore_anchor, bool ignore_position, bool ignore_scale, const QMatrix4x4 &mat) const
{
QVector2D anchor;
QVector2D position;
QVector2D scale;
if (!ignore_anchor) {
anchor = value[kAnchorInput].toVec2();
}
if (!ignore_scale) {
scale = value[kScaleInput].toVec2();
}
if (!ignore_position) {
position = value[kPositionInput].toVec2();
}
return GenerateMatrix(position,
value[kRotationInput].toDouble(),
scale,
value[kUniformScaleInput].toBool(),
anchor,
mat);
}
QMatrix4x4 MatrixGenerator::GenerateMatrix(const QVector2D& pos,
const float& rot,
const QVector2D& scale,
bool uniform_scale,
const QVector2D& anchor,
QMatrix4x4 mat)
{
// Position
mat.translate(pos.x(), pos.y());
// Rotation
mat.rotate(rot, 0, 0, 1);
// Scale (convert to a QVector3D so that the identity matrix is preserved if all values are 1.0f)
QVector3D full_scale;
if (uniform_scale) {
full_scale = QVector3D(scale.x(), scale.x(), 1.0f);
} else {
full_scale = QVector3D(scale, 1.0f);
}
mat.scale(full_scale);
// Anchor Point
mat.translate(-anchor.x(), -anchor.y());
return mat;
}
void MatrixGenerator::InputValueChangedEvent(const QString &input, int element)
{
Q_UNUSED(element)
if (input == kUniformScaleInput) {
SetInputProperty(kScaleInput, QStringLiteral("disable1"), GetStandardValue(kUniformScaleInput).toBool());
}
}
}
| 4,746
|
C++
|
.cpp
| 123
| 33.390244
| 159
| 0.713694
|
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
|
18,989
|
shapenodebase.cpp
|
olive-editor_olive/app/node/generator/shape/shapenodebase.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 "shapenodebase.h"
#include <QtMath>
#include <QVector2D>
#include "common/util.h"
#include "core.h"
#include "node/nodeundo.h"
namespace olive {
#define super GeneratorWithMerge
const QString ShapeNodeBase::kPositionInput = QStringLiteral("pos_in");
const QString ShapeNodeBase::kSizeInput = QStringLiteral("size_in");
const QString ShapeNodeBase::kColorInput = QStringLiteral("color_in");
ShapeNodeBase::ShapeNodeBase(bool create_color_input)
{
AddInput(kPositionInput, NodeValue::kVec2, QVector2D(0, 0));
AddInput(kSizeInput, NodeValue::kVec2, QVector2D(100, 100));
SetInputProperty(kSizeInput, QStringLiteral("min"), QVector2D(0, 0));
if (create_color_input) {
AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(1.0, 0.0, 0.0, 1.0)));
}
// Initiate gizmos
QVector<NodeKeyframeTrackReference> pos_n_sz = {
NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0),
NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1),
NodeKeyframeTrackReference(NodeInput(this, kSizeInput), 0),
NodeKeyframeTrackReference(NodeInput(this, kSizeInput), 1)
};
poly_gizmo_ = AddDraggableGizmo<PolygonGizmo>({
NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0),
NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1),
});
for (int i=0; i<kGizmoScaleCount; i++) {
point_gizmo_[i] = AddDraggableGizmo<PointGizmo>(pos_n_sz, PointGizmo::kAbsolute);
}
}
void ShapeNodeBase::Retranslate()
{
super::Retranslate();
SetInputName(kPositionInput, tr("Position"));
SetInputName(kSizeInput, tr("Size"));
if (HasInputWithID(kColorInput)) {
SetInputName(kColorInput, tr("Color"));
}
}
void ShapeNodeBase::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals)
{
// Use offsets to make the appearance of values that start in the top left, even though we
// really anchor around the center
QVector2D center_pt = globals.square_resolution() * 0.5;
SetInputProperty(kPositionInput, QStringLiteral("offset"), center_pt);
QVector2D pos = row[kPositionInput].toVec2();
QVector2D sz = row[kSizeInput].toVec2();
QVector2D half_sz = sz * 0.5;
double left_pt = pos.x() + center_pt.x() - half_sz.x();
double top_pt = pos.y() + center_pt.y() - half_sz.y();
double right_pt = left_pt + sz.x();
double bottom_pt = top_pt + sz.y();
double center_x_pt = mid(left_pt, right_pt);
double center_y_pt = mid(top_pt, bottom_pt);
point_gizmo_[kGizmoScaleTopLeft]->SetPoint(QPointF(left_pt, top_pt));
point_gizmo_[kGizmoScaleTopCenter]->SetPoint(QPointF(center_x_pt, top_pt));
point_gizmo_[kGizmoScaleTopRight]->SetPoint(QPointF(right_pt, top_pt));
point_gizmo_[kGizmoScaleBottomLeft]->SetPoint(QPointF(left_pt, bottom_pt));
point_gizmo_[kGizmoScaleBottomCenter]->SetPoint(QPointF(center_x_pt, bottom_pt));
point_gizmo_[kGizmoScaleBottomRight]->SetPoint(QPointF(right_pt, bottom_pt));
point_gizmo_[kGizmoScaleCenterLeft]->SetPoint(QPointF(left_pt, center_y_pt));
point_gizmo_[kGizmoScaleCenterRight]->SetPoint(QPointF(right_pt, center_y_pt));
poly_gizmo_->SetPolygon(QRectF(left_pt, top_pt, right_pt - left_pt, bottom_pt - top_pt));
}
void ShapeNodeBase::SetRect(QRectF rect, const VideoParams &sequence_res, MultiUndoCommand *command)
{
// Normalize around center of sequence
rect.translate(-sequence_res.width()*0.5, -sequence_res.height()*0.5);
rect.translate(rect.width()*0.5, rect.height()*0.5);
NodeInput pos(this, ShapeNodeBase::kPositionInput);
NodeInput sz(this, ShapeNodeBase::kSizeInput);
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(sz, 0), rect.width()));
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(sz, 1), rect.height()));
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(pos, 0), rect.x()));
command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(pos, 1), rect.y()));
}
void ShapeNodeBase::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers)
{
DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender());
NodeInputDragger &x_drag = gizmo->GetDraggers()[0];
NodeInputDragger &y_drag = gizmo->GetDraggers()[1];
if (gizmo == poly_gizmo_) {
x_drag.Drag(x_drag.GetStartValue().toDouble() + x);
y_drag.Drag(y_drag.GetStartValue().toDouble() + y);
} else {
bool from_center = modifiers & Qt::AltModifier;
bool keep_ratio = modifiers & Qt::ShiftModifier;
NodeInputDragger &w_drag = gizmo->GetDraggers()[2];
NodeInputDragger &h_drag = gizmo->GetDraggers()[3];
QVector2D gizmo_sz_start(w_drag.GetStartValue().toDouble(), h_drag.GetStartValue().toDouble());
QVector2D gizmo_pos_start(x_drag.GetStartValue().toDouble(), y_drag.GetStartValue().toDouble());
QVector2D gizmo_half_res = gizmo->GetGlobals().square_resolution()/2;
QVector2D adjusted_pt(x, y);
QVector2D new_size;
QVector2D new_pos;
QVector2D anchor;
static const int kXYCount = 2;
bool negative[kXYCount] = {false};
double original_ratio;
if (keep_ratio) {
original_ratio = w_drag.GetStartValue().toDouble() / h_drag.GetStartValue().toDouble();
}
// Calculate new size
if (from_center) {
// Calculate new size by using distance from center and doubling it
new_size = (adjusted_pt - gizmo_half_res - gizmo_pos_start) * 2;
if (IsGizmoTop(gizmo)) {
new_size.setY(-new_size.y());
}
if (IsGizmoLeft(gizmo)) {
new_size.setX(-new_size.x());
}
} else {
// Calculate new size by using distance from "anchor" - i.e. the opposite point of the shape
// from the gizmo being dragged
adjusted_pt -= gizmo_half_res;
anchor = GenerateGizmoAnchor(gizmo_pos_start, gizmo_sz_start, gizmo, &adjusted_pt) + gizmo_half_res;
adjusted_pt += gizmo_half_res;
// Calculate size and position
new_size = adjusted_pt - anchor;
// Abs size so neither coord is negative
for (int i=0; i<kXYCount; i++) {
if (new_size[i] < 0) {
negative[i] = true;
new_size[i] = -new_size[i];
}
}
}
// Restrict sizes by constraints
if (IsGizmoVerticalCenter(gizmo)) {
if (keep_ratio) {
// Calculate width from new height
new_size.setX(new_size.y() * original_ratio);
} else {
// Constrain to original width
new_size.setX(gizmo_sz_start.x());
}
}
if (IsGizmoHorizontalCenter(gizmo)) {
if (keep_ratio) {
// Calculate height from new width
new_size.setY(new_size.x() / original_ratio);
} else {
// Constrain to original height
new_size.setY(gizmo_sz_start.y());
}
}
if (IsGizmoCorner(gizmo)) {
if (keep_ratio) {
float hypot = std::hypot(new_size.x(), new_size.y());
float original_angle = std::atan2(gizmo_sz_start.x(), gizmo_sz_start.y());
// Calculate new size based on original angle and hypotenuse
new_size.setX(std::sin(original_angle) * hypot);
new_size.setY(std::cos(original_angle) * hypot);
}
}
// Calculate position
if (from_center) {
new_pos = gizmo_pos_start;
} else {
QVector2D using_size = new_size;
// Un-abs size
for (int i=0; i<kXYCount; i++) {
if (negative[i]) {
using_size[i] = -using_size[i];
}
}
// I'm pretty sure there's an algorithmic way of doing this, but I'm tired and this works
if (IsGizmoHorizontalCenter(gizmo)) {
using_size.setY(0);
}
if (IsGizmoVerticalCenter(gizmo)) {
using_size.setX(0);
}
new_pos = GenerateGizmoAnchor(gizmo_pos_start, gizmo_sz_start, gizmo) + using_size / 2;
}
x_drag.Drag(new_pos.x());
y_drag.Drag(new_pos.y());
w_drag.Drag(new_size.x());
h_drag.Drag(new_size.y());
}
}
QVector2D ShapeNodeBase::GenerateGizmoAnchor(const QVector2D &pos, const QVector2D &size, NodeGizmo *gizmo, QVector2D *pt) const
{
QVector2D anchor = pos;
QVector2D half_sz = size/2;
if (IsGizmoLeft(gizmo)) {
anchor.setX(anchor.x() + half_sz.x());
if (pt && pt->x() > anchor.x()) {
pt->setX(anchor.x());
}
}
if (IsGizmoRight(gizmo)) {
anchor.setX(anchor.x() - half_sz.x());
if (pt && pt->x() < anchor.x()) {
pt->setX(anchor.x());
}
}
if (IsGizmoTop(gizmo)) {
anchor.setY(anchor.y() + half_sz.y());
if (pt && pt->y() > anchor.y()) {
pt->setY(anchor.y());
}
}
if (IsGizmoBottom(gizmo)) {
anchor.setY(anchor.y() - half_sz.y());
if (pt && pt->y() < anchor.y()) {
pt->setY(anchor.y());
}
}
return anchor;
}
bool ShapeNodeBase::IsGizmoTop(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleTopCenter] || g == point_gizmo_[kGizmoScaleTopLeft] || g == point_gizmo_[kGizmoScaleTopRight];
}
bool ShapeNodeBase::IsGizmoBottom(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleBottomCenter] || g == point_gizmo_[kGizmoScaleBottomLeft] || g == point_gizmo_[kGizmoScaleBottomRight];
}
bool ShapeNodeBase::IsGizmoLeft(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleTopLeft] || g == point_gizmo_[kGizmoScaleCenterLeft] || g == point_gizmo_[kGizmoScaleBottomLeft];
}
bool ShapeNodeBase::IsGizmoRight(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleTopRight] || g == point_gizmo_[kGizmoScaleCenterRight] || g == point_gizmo_[kGizmoScaleBottomRight];
}
bool ShapeNodeBase::IsGizmoHorizontalCenter(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleCenterLeft] || g == point_gizmo_[kGizmoScaleCenterRight];
}
bool ShapeNodeBase::IsGizmoVerticalCenter(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleTopCenter] || g == point_gizmo_[kGizmoScaleBottomCenter];
}
bool ShapeNodeBase::IsGizmoCorner(NodeGizmo *g) const
{
return g == point_gizmo_[kGizmoScaleTopLeft] || g == point_gizmo_[kGizmoScaleTopRight]
|| g == point_gizmo_[kGizmoScaleBottomRight] || g == point_gizmo_[kGizmoScaleBottomLeft];
}
}
| 10,839
|
C++
|
.cpp
| 260
| 37.2
| 141
| 0.695036
|
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
|
18,990
|
shapenode.cpp
|
olive-editor_olive/app/node/generator/shape/shapenode.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 "shapenode.h"
namespace olive {
#define super ShapeNodeBase
QString ShapeNode::kTypeInput = QStringLiteral("type_in");
QString ShapeNode::kRadiusInput = QStringLiteral("radius_in");
ShapeNode::ShapeNode()
{
PrependInput(kTypeInput, NodeValue::kCombo);
AddInput(kRadiusInput, NodeValue::kFloat, 20.0);
SetInputProperty(kRadiusInput, QStringLiteral("min"), 0.0);
}
QString ShapeNode::Name() const
{
return tr("Shape");
}
QString ShapeNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.shape");
}
QVector<Node::CategoryID> ShapeNode::Category() const
{
return {kCategoryGenerator};
}
QString ShapeNode::Description() const
{
return tr("Generate a 2D primitive shape.");
}
void ShapeNode::Retranslate()
{
super::Retranslate();
SetInputName(kTypeInput, tr("Type"));
SetInputName(kRadiusInput, tr("Radius"));
// Coordinate with Type enum
SetComboBoxStrings(kTypeInput, {tr("Rectangle"), tr("Ellipse"), tr("Rounded Rectangle")});
}
ShaderCode ShapeNode::GetShaderCode(const ShaderRequest &request) const
{
if (request.id == QStringLiteral("shape")) {
return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/shape.frag")));
} else {
return super::GetShaderCode(request);
}
}
void ShapeNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
TexturePtr base = value[kBaseInput].toTexture();
ShaderJob job(value);
job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, base ? base->virtual_resolution() : globals.square_resolution(), this));
job.SetShaderID(QStringLiteral("shape"));
PushMergableJob(value, Texture::Job(base ? base->params() : globals.vparams(), job), table);
}
void ShapeNode::InputValueChangedEvent(const QString &input, int element)
{
if (input == kTypeInput) {
SetInputFlag(kRadiusInput, kInputFlagHidden, (GetStandardValue(kTypeInput).toInt() != kRoundedRectangle));
}
super::InputValueChangedEvent(input, element);
}
}
| 2,727
|
C++
|
.cpp
| 73
| 34.890411
| 146
| 0.766071
|
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
|
18,991
|
generatorwithmerge.cpp
|
olive-editor_olive/app/node/generator/shape/generatorwithmerge.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 "generatorwithmerge.h"
#include "node/math/merge/merge.h"
namespace olive {
#define super Node
const QString GeneratorWithMerge::kBaseInput = QStringLiteral("base_in");
GeneratorWithMerge::GeneratorWithMerge()
{
AddInput(kBaseInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
SetEffectInput(kBaseInput);
SetFlag(kVideoEffect);
}
void GeneratorWithMerge::Retranslate()
{
super::Retranslate();
SetInputName(kBaseInput, tr("Base"));
}
ShaderCode GeneratorWithMerge::GetShaderCode(const ShaderRequest &request) const
{
if (request.id == QStringLiteral("mrg")) {
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/alphaover.frag"));
}
return ShaderCode();
}
void GeneratorWithMerge::PushMergableJob(const NodeValueRow &value, TexturePtr job, NodeValueTable *table) const
{
if (TexturePtr base = value[kBaseInput].toTexture()) {
// Push as merge node
ShaderJob merge;
merge.SetShaderID(QStringLiteral("mrg"));
merge.Insert(MergeNode::kBaseIn, value[kBaseInput]);
merge.Insert(MergeNode::kBlendIn, NodeValue(NodeValue::kTexture, job, this));
table->Push(NodeValue::kTexture, base->toJob(merge), this);
} else {
// Just push generate job
table->Push(NodeValue::kTexture, job, this);
}
}
}
| 2,000
|
C++
|
.cpp
| 52
| 35.519231
| 112
| 0.767755
|
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
|
18,992
|
group.cpp
|
olive-editor_olive/app/node/group/group.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 "group.h"
#include "node/serializeddata.h"
namespace olive {
#define super Node
NodeGroup::NodeGroup() :
output_passthrough_(nullptr)
{
SetFlag(kDontShowInCreateMenu);
}
QString NodeGroup::Name() const
{
return tr("Group");
}
QString NodeGroup::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.group");
}
QVector<Node::CategoryID> NodeGroup::Category() const
{
return {kCategoryUnknown};
}
QString NodeGroup::Description() const
{
return tr("A group of nodes that is represented as a single node.");
}
void NodeGroup::Retranslate()
{
super::Retranslate();
for (auto it=GetContextPositions().cbegin(); it!=GetContextPositions().cend(); it++) {
it.key()->Retranslate();
}
}
bool NodeGroup::LoadCustom(QXmlStreamReader *reader, SerializedData *data)
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthroughs")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthrough")) {
SerializedData::GroupLink link;
link.group = this;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
link.input_node = reader->readElementText().toULongLong();
} else if (reader->name() == QStringLiteral("input")) {
link.input_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("element")) {
link.input_element = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("id")) {
link.passthrough_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("name")) {
link.custom_name = reader->readElementText();
} else if (reader->name() == QStringLiteral("flags")) {
link.custom_flags = InputFlags(reader->readElementText().toULongLong());
} else if (reader->name() == QStringLiteral("type")) {
link.data_type = NodeValue::GetDataTypeFromName(reader->readElementText());
} else if (reader->name() == QStringLiteral("default")) {
link.default_val = NodeValue::StringToValue(link.data_type, reader->readElementText(), false);
} else if (reader->name() == QStringLiteral("properties")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("property")) {
QString key;
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
key = reader->readElementText();
} else if (reader->name() == QStringLiteral("value")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
if (!key.isEmpty()) {
link.custom_properties.insert(key, value);
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
data->group_input_links.append(link);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("outputpassthrough")) {
data->group_output_links.insert(this, reader->readElementText().toULongLong());
} else {
reader->skipCurrentElement();
}
}
return true;
}
void NodeGroup::SaveCustom(QXmlStreamWriter *writer) const
{
writer->writeStartElement(QStringLiteral("inputpassthroughs"));
foreach (const NodeGroup::InputPassthrough &ip, this->GetInputPassthroughs()) {
writer->writeStartElement(QStringLiteral("inputpassthrough"));
// Reference to inner input
writer->writeTextElement(QStringLiteral("node"), QString::number(reinterpret_cast<quintptr>(ip.second.node())));
writer->writeTextElement(QStringLiteral("input"), ip.second.input());
writer->writeTextElement(QStringLiteral("element"), QString::number(ip.second.element()));
// ID of passthrough
writer->writeTextElement(QStringLiteral("id"), ip.first);
// Passthrough-specific details
const QString &input = ip.first;
writer->writeTextElement(QStringLiteral("name"), this->Node::GetInputName(input));
writer->writeTextElement(QStringLiteral("flags"), QString::number((GetInputFlags(input) & ~ip.second.GetFlags()).value()));
NodeValue::Type data_type = GetInputDataType(input);
writer->writeTextElement(QStringLiteral("type"), NodeValue::GetDataTypeName(data_type));
writer->writeTextElement(QStringLiteral("default"), NodeValue::ValueToString(data_type, GetDefaultValue(input), false));
writer->writeStartElement(QStringLiteral("properties"));
auto p = GetInputProperties(input);
for (auto it=p.cbegin(); it!=p.cend(); it++) {
writer->writeStartElement(QStringLiteral("property"));
writer->writeTextElement(QStringLiteral("key"), it.key());
writer->writeTextElement(QStringLiteral("value"), it.value().toString());
writer->writeEndElement(); // property
}
writer->writeEndElement(); // properties
writer->writeEndElement(); // input
}
writer->writeEndElement(); // inputpassthroughs
writer->writeTextElement(QStringLiteral("outputpassthrough"), QString::number(reinterpret_cast<quintptr>(this->GetOutputPassthrough())));
}
void NodeGroup::PostLoadEvent(SerializedData *data)
{
super::PostLoadEvent(data);
foreach (const SerializedData::GroupLink &l, data->group_input_links) {
if (Node *input_node = data->node_ptrs.value(l.input_node)) {
NodeInput resolved(input_node, l.input_id, l.input_element);
l.group->AddInputPassthrough(resolved, l.passthrough_id);
l.group->SetInputFlag(l.passthrough_id, InputFlag(l.custom_flags.value()));
if (!l.custom_name.isEmpty()) {
l.group->SetInputName(l.passthrough_id, l.custom_name);
}
l.group->SetInputDataType(l.passthrough_id, l.data_type);
l.group->SetDefaultValue(l.passthrough_id, l.default_val);
for (auto it=l.custom_properties.cbegin(); it!=l.custom_properties.cend(); it++) {
l.group->SetInputProperty(l.passthrough_id, it.key(), it.value());
}
}
}
for (auto it=data->group_output_links.cbegin(); it!=data->group_output_links.cend(); it++) {
if (Node *output_node = data->node_ptrs.value(it.value())) {
it.key()->SetOutputPassthrough(output_node);
}
}
}
QString NodeGroup::AddInputPassthrough(const NodeInput &input, const QString &force_id)
{
Q_ASSERT(ContextContainsNode(input.node()));
for (auto it=input_passthroughs_.cbegin(); it!=input_passthroughs_.cend(); it++) {
if (it->second == input) {
// Already passing this input through
return it->first;
}
}
// Add input
QString id;
if (force_id.isEmpty()) {
id = input.input();
int i = 2;
while (HasInputWithID(id)) {
id = QStringLiteral("%1_%2").arg(input.name(), QString::number(i));
i++;
}
} else {
id = force_id;
bool already_exists = false;
for (auto it=input_passthroughs_.cbegin(); it!=input_passthroughs_.cend(); it++) {
if (it->first == id) {
already_exists = true;
break;
}
}
Q_ASSERT(!already_exists);
}
AddInput(id, input.GetDataType(), input.GetDefaultValue(), input.GetFlags());
input_passthroughs_.append({id, input});
emit InputPassthroughAdded(this, input);
return id;
}
void NodeGroup::RemoveInputPassthrough(const NodeInput &input)
{
for (auto it=input_passthroughs_.begin(); it!=input_passthroughs_.end(); it++) {
if (it->second == input) {
RemoveInput(it->first);
emit InputPassthroughRemoved(this, it->second);
input_passthroughs_.erase(it);
break;
}
}
}
void NodeGroup::SetOutputPassthrough(Node *node)
{
Q_ASSERT(!node || ContextContainsNode(node));
output_passthrough_ = node;
emit OutputPassthroughChanged(this, output_passthrough_);
}
bool NodeGroup::ContainsInputPassthrough(const NodeInput &input) const
{
for (auto it=input_passthroughs_.cbegin(); it!=input_passthroughs_.cend(); it++) {
if (it->second == input) {
return true;
}
}
return false;
}
QString NodeGroup::GetInputName(const QString &id) const
{
// If an override name was set, use that
QString override = super::GetInputName(id);
if (!override.isEmpty()) {
return override;
}
// Call GetInputName of passed through node, which may be another group
NodeInput pass = GetInputFromID(id);
return pass.node()->GetInputName(pass.input());
}
NodeInput NodeGroup::ResolveInput(NodeInput input)
{
while (GetInner(&input)) {}
return input;
}
bool NodeGroup::GetInner(NodeInput *input)
{
if (NodeGroup *g = dynamic_cast<NodeGroup*>(input->node())) {
const NodeInput &passthrough = g->GetInputFromID(input->input());
if (!passthrough.IsValid()) {
return false;
}
input->set_node(passthrough.node());
input->set_input(passthrough.input());
return true;
} else {
return false;
}
}
void NodeGroupAddInputPassthrough::redo()
{
if (!group_->ContainsInputPassthrough(input_)) {
group_->AddInputPassthrough(input_, force_id_);
actually_added_ = true;
} else {
actually_added_ = false;
}
}
void NodeGroupAddInputPassthrough::undo()
{
if (actually_added_) {
group_->RemoveInputPassthrough(input_);
}
}
void NodeGroupSetOutputPassthrough::redo()
{
old_output_ = group_->GetOutputPassthrough();
group_->SetOutputPassthrough(new_output_);
}
void NodeGroupSetOutputPassthrough::undo()
{
group_->SetOutputPassthrough(old_output_);
}
}
| 10,629
|
C++
|
.cpp
| 280
| 32.089286
| 139
| 0.66524
|
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
|
18,993
|
ociobase.cpp
|
olive-editor_olive/app/node/color/ociobase/ociobase.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 "ociobase.h"
#include "node/color/colormanager/colormanager.h"
#include "node/project.h"
namespace olive {
const QString OCIOBaseNode::kTextureInput = QStringLiteral("tex_in");
OCIOBaseNode::OCIOBaseNode() :
manager_(nullptr),
processor_(nullptr)
{
AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
SetEffectInput(kTextureInput);
SetFlag(kVideoEffect);
}
void OCIOBaseNode::AddedToGraphEvent(Project *p)
{
manager_ = p->color_manager();
connect(manager_, &ColorManager::ConfigChanged, this, &OCIOBaseNode::ConfigChanged);
ConfigChanged();
}
void OCIOBaseNode::RemovedFromGraphEvent(Project *p)
{
if (manager_) {
disconnect(manager_, &ColorManager::ConfigChanged, this, &OCIOBaseNode::ConfigChanged);
manager_ = nullptr;
}
}
void OCIOBaseNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
auto tex_met = value[kTextureInput];
TexturePtr t = tex_met.toTexture();
if (t && processor_) {
ColorTransformJob job;
job.SetColorProcessor(processor_);
job.SetInputTexture(tex_met);
table->Push(NodeValue::kTexture, t->toJob(job), this);
}
}
}
| 1,899
|
C++
|
.cpp
| 52
| 33.711538
| 108
| 0.765992
|
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
|
18,994
|
displaytransform.cpp
|
olive-editor_olive/app/node/color/displaytransform/displaytransform.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 "displaytransform.h"
#include "node/color/colormanager/colormanager.h"
namespace olive {
const QString DisplayTransformNode::kDisplayInput = QStringLiteral("display_in");
const QString DisplayTransformNode::kViewInput = QStringLiteral("view_in");
const QString DisplayTransformNode::kDirectionInput = QStringLiteral("dir_in");
#define super OCIOBaseNode
DisplayTransformNode::DisplayTransformNode()
{
AddInput(kDisplayInput, NodeValue::kCombo, 0, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable));
AddInput(kViewInput, NodeValue::kCombo, 0, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable));
AddInput(kDirectionInput, NodeValue::kCombo, 0, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable));
}
QString DisplayTransformNode::Name() const
{
return tr("Display Transform");
}
QString DisplayTransformNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.displaytransform");
}
QVector<Node::CategoryID> DisplayTransformNode::Category() const
{
return {kCategoryColor};
}
QString DisplayTransformNode::Description() const
{
return tr("Converts an image to or from a display color space.");
}
void DisplayTransformNode::Retranslate()
{
super::Retranslate();
SetInputName(kTextureInput, tr("Input"));
SetInputName(kDisplayInput, tr("Display"));
SetInputName(kViewInput, tr("View"));
SetInputName(kDirectionInput, tr("Direction"));
SetComboBoxStrings(kDirectionInput, {tr("Forward"), tr("Inverse")});
}
void DisplayTransformNode::InputValueChangedEvent(const QString &input, int element)
{
Q_UNUSED(element);
if (input == kDisplayInput || input == kDirectionInput || input == kViewInput) {
if (input == kDisplayInput) {
UpdateViews();
}
GenerateProcessor();
}
}
QString DisplayTransformNode::GetDisplay() const
{
if (manager()) {
int index = GetStandardValue(kDisplayInput).toInt();
if (index < manager()->ListAvailableDisplays().size()) {
return manager()->ListAvailableDisplays().at(index);
}
}
return QString();
}
QString DisplayTransformNode::GetView() const
{
if (manager()) {
QString display = GetDisplay();
if (!display.isEmpty()) {
int index = GetStandardValue(kViewInput).toInt();
QStringList views = manager()->ListAvailableViews(display);
if (index < views.size()) {
return views.at(index);
}
}
}
return QString();
}
ColorProcessor::Direction DisplayTransformNode::GetDirection() const
{
return static_cast<ColorProcessor::Direction>(GetStandardValue(kDirectionInput).toInt());;
}
void DisplayTransformNode::UpdateDisplays()
{
if (manager()) {
SetComboBoxStrings(kDisplayInput, manager()->ListAvailableDisplays());
}
}
void DisplayTransformNode::UpdateViews()
{
if (manager()) {
SetComboBoxStrings(kViewInput, manager()->ListAvailableViews(GetDisplay()));
}
}
void DisplayTransformNode::ConfigChanged()
{
UpdateDisplays();
UpdateViews();
GenerateProcessor();
}
void DisplayTransformNode::GenerateProcessor()
{
if (manager()) {
ColorTransform transform(GetDisplay(), GetView(), QString());
set_processor(ColorProcessor::Create(manager(), manager()->GetReferenceColorSpace(), transform, GetDirection()));
}
}
}
| 3,974
|
C++
|
.cpp
| 116
| 31.431034
| 117
| 0.762663
|
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
|
18,995
|
ociogradingtransformlinear.cpp
|
olive-editor_olive/app/node/color/ociogradingtransformlinear/ociogradingtransformlinear.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 "ociogradingtransformlinear.h"
#include <iostream>
#include "common/ocioutils.h"
#include "node/project.h"
#include "render/colorprocessor.h"
#include "widget/slider/floatslider.h"
namespace olive {
const QString OCIOGradingTransformLinearNode::kContrastInput = QStringLiteral("ocio_grading_primary_contrast");
const QString OCIOGradingTransformLinearNode::kOffsetInput = QStringLiteral("ocio_grading_primary_offset");
const QString OCIOGradingTransformLinearNode::kExposureInput = QStringLiteral("ocio_grading_primary_exposure");
const QString OCIOGradingTransformLinearNode::kSaturationInput = QStringLiteral("ocio_grading_primary_saturation");
const QString OCIOGradingTransformLinearNode::kPivotInput = QStringLiteral("ocio_grading_primary_pivot");
const QString OCIOGradingTransformLinearNode::kClampBlackEnableInput = QStringLiteral("clamp_black_enable_in");
const QString OCIOGradingTransformLinearNode::kClampBlackInput = QStringLiteral("ocio_grading_primary_clampBlack");
const QString OCIOGradingTransformLinearNode::kClampWhiteEnableInput = QStringLiteral("clamp_white_enable_in");
const QString OCIOGradingTransformLinearNode::kClampWhiteInput = QStringLiteral("ocio_grading_primary_clampWhite");
#define super OCIOBaseNode
OCIOGradingTransformLinearNode::OCIOGradingTransformLinearNode()
{
AddInput(kContrastInput, NodeValue::kVec4, QVector4D{1.0, 1.0, 1.0, 1.0});
// Minimum based on OCIO::GradingPrimary::validate
SetInputProperty(kContrastInput, QStringLiteral("min"), QVector4D{0.01f, 0.01f, 0.01f, 0.01f});
SetInputProperty(kContrastInput, QStringLiteral("base"), 0.01);
SetVec4InputColors(kContrastInput);
AddInput(kOffsetInput, NodeValue::kVec4, QVector4D{0.0, 0.0, 0.0, 0.0});
SetInputProperty(kOffsetInput, QStringLiteral("base"), 0.01);
SetVec4InputColors(kOffsetInput);
AddInput(kExposureInput, NodeValue::kVec4, QVector4D{0.0, 0.0, 0.0, 0.0});
SetInputProperty(kExposureInput, QStringLiteral("base"), 0.01);
SetVec4InputColors(kExposureInput);
AddInput(kSaturationInput, NodeValue::kFloat, 1.0);
SetInputProperty(kSaturationInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetInputProperty(kSaturationInput, QStringLiteral("min"), 0.0);
AddInput(kPivotInput, NodeValue::kFloat, 0.18); // Default listed in OCIO::GradingPrimary
SetInputProperty(kPivotInput, QStringLiteral("base"), 0.01);
AddInput(kClampBlackEnableInput, NodeValue::kBoolean, false);
AddInput(kClampBlackInput, NodeValue::kFloat, 0.0);
SetInputProperty(kClampBlackInput, QStringLiteral("enabled"), GetStandardValue(kClampBlackEnableInput).toBool());
SetInputProperty(kClampBlackInput, QStringLiteral("base"), 0.01);
AddInput(kClampWhiteEnableInput, NodeValue::kBoolean, false);
AddInput(kClampWhiteInput, NodeValue::kFloat, 1.0);
SetInputProperty(kClampWhiteInput, QStringLiteral("enabled"), GetStandardValue(kClampWhiteEnableInput).toBool());
SetInputProperty(kClampWhiteInput, QStringLiteral("base"), 0.01);
// FIXME: Temporarily disabled. This will break if "clamp black" is keyframed or connected to
// something and there's currently no solution to remedy that. If there is in the future,
// we can look into re-enabling this.
//SetInputProperty(kClampWhiteInput, QStringLiteral("min"), GetStandardValue(kClampBlackInput).toDouble() + 0.000001);
}
QString OCIOGradingTransformLinearNode::Name() const
{
return tr("OCIO Color Grading (Linear)");
}
QString OCIOGradingTransformLinearNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.ociogradingtransformlinear");
}
QVector<Node::CategoryID> OCIOGradingTransformLinearNode::Category() const
{
return {kCategoryColor};
}
QString OCIOGradingTransformLinearNode::Description() const
{
return tr("Simple linear color grading using OpenColorIO.");
}
void OCIOGradingTransformLinearNode::Retranslate()
{
super::Retranslate();
SetInputName(kTextureInput, tr("Input"));
SetInputName(kContrastInput, tr("Contrast"));
SetInputName(kOffsetInput, tr("Offset"));
SetInputName(kExposureInput, tr("Exposure"));
SetInputProperty(kExposureInput, QStringLiteral("tooltip"), tr("Exposure increments in stops."));
SetInputName(kSaturationInput, tr("Saturation"));
SetInputName(kPivotInput, tr("Pivot"));
SetInputName(kClampBlackEnableInput, tr("Enable Black Clamp"));
SetInputName(kClampBlackInput, tr("Black Clamp"));
SetInputName(kClampWhiteEnableInput, tr("Enable White Clamp"));
SetInputName(kClampWhiteInput, tr("White Clamp"));
}
void OCIOGradingTransformLinearNode::InputValueChangedEvent(const QString &input, int element)
{
Q_UNUSED(element);
if (input == kClampWhiteEnableInput) {
SetInputProperty(kClampWhiteInput, QStringLiteral("enabled"), GetStandardValue(kClampWhiteEnableInput).toBool());
} else if (input == kClampBlackEnableInput) {
SetInputProperty(kClampBlackInput, QStringLiteral("enabled"), GetStandardValue(kClampBlackEnableInput).toBool());
} else if (input == kClampBlackInput) {
// Ensure the white clamp is always greater than the black clamp as per OCIO::GradingPrimary::validate
// FIXME: Temporarily disabled. This will break if "clamp black" is keyframed or connected to
// something and there's currently no solution to remedy that. If there is in the future,
// we can look into re-enabling this.
//SetInputProperty(kClampWhiteInput, QStringLiteral("min"), GetStandardValue(kClampBlackInput).toDouble() + 0.000001);
}
GenerateProcessor();
}
void OCIOGradingTransformLinearNode::GenerateProcessor()
{
if (manager()) {
OCIO::GradingPrimaryTransformRcPtr gp = OCIO::GradingPrimaryTransform::Create(OCIO::GRADING_LIN);
gp->makeDynamic();
gp->setDirection(OCIO::TransformDirection::TRANSFORM_DIR_FORWARD);
try {
set_processor(ColorProcessor::Create(manager()->GetConfig()->getProcessor(gp)));
} catch (const OCIO::Exception &e) {
std::cerr << std::endl << e.what() << std::endl;
}
}
}
void OCIOGradingTransformLinearNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
if (TexturePtr tex = value[kTextureInput].toTexture()) {
if (processor()) {
ColorTransformJob job(value);
job.SetColorProcessor(processor());
job.SetInputTexture(value[kTextureInput]);
const int MASTER_CHANNEL = 0;
const int RED_CHANNEL = 1;
const int GREEN_CHANNEL = 2;
const int BLUE_CHANNEL = 3;
// Oddly, OCIO uses RGBMs when setting the GradingPrimary on the CPU, but uses vec3s on the GPU.
// Even more oddly, the conversion from RGBM to vec3 does not appear to have a public API.
// Therefore, this code has been duplicated from OCIO here:
// https://github.com/AcademySoftwareFoundation/OpenColorIO/blob/3abbe5b20521169580fcfe3692aca81859859953/src/OpenColorIO/ops/gradingprimary/GradingPrimary.cpp#L157
QVector4D offset = value[kOffsetInput].toVec4();
offset[RED_CHANNEL] += offset[MASTER_CHANNEL];
offset[GREEN_CHANNEL] += offset[MASTER_CHANNEL];
offset[BLUE_CHANNEL] += offset[MASTER_CHANNEL];
job.Insert(kOffsetInput, NodeValue(NodeValue::kVec3, QVector3D(offset[RED_CHANNEL], offset[GREEN_CHANNEL], offset[BLUE_CHANNEL])));
QVector4D exposure = value[kExposureInput].toVec4();
exposure[RED_CHANNEL] = std::pow(2.0f, exposure[MASTER_CHANNEL] + exposure[RED_CHANNEL]);
exposure[GREEN_CHANNEL] = std::pow(2.0f, exposure[MASTER_CHANNEL] + exposure[GREEN_CHANNEL]);
exposure[BLUE_CHANNEL] = std::pow(2.0f, exposure[MASTER_CHANNEL] + exposure[BLUE_CHANNEL]);
job.Insert(kExposureInput, NodeValue(NodeValue::kVec3, QVector3D(exposure[RED_CHANNEL], exposure[GREEN_CHANNEL], exposure[BLUE_CHANNEL])));
QVector4D contrast = value[kContrastInput].toVec4();
contrast[RED_CHANNEL] *= contrast[MASTER_CHANNEL];
contrast[GREEN_CHANNEL] *= contrast[MASTER_CHANNEL];
contrast[BLUE_CHANNEL] *= contrast[MASTER_CHANNEL];
job.Insert(kContrastInput, NodeValue(NodeValue::kVec3, QVector3D(contrast[RED_CHANNEL], contrast[GREEN_CHANNEL], contrast[BLUE_CHANNEL])));
if (!value[kClampBlackEnableInput].toBool()) {
job.Insert(kClampBlackInput, NodeValue(NodeValue::kFloat, OCIO::GradingPrimary::NoClampBlack()));
}
if (!value[kClampWhiteEnableInput].toBool()) {
job.Insert(kClampWhiteInput, NodeValue(NodeValue::kFloat, OCIO::GradingPrimary::NoClampWhite()));
}
table->Push(NodeValue::kTexture, tex->toJob(job), this);
}
}
}
void OCIOGradingTransformLinearNode::ConfigChanged()
{
GenerateProcessor();
}
void OCIOGradingTransformLinearNode::SetVec4InputColors(const QString &input)
{
SetInputProperty(input, QStringLiteral("color0"), QColor(192, 192, 192).name());
SetInputProperty(input, QStringLiteral("color1"), QColor(255, 0, 0).name());
SetInputProperty(input, QStringLiteral("color2"), QColor(0, 255, 0).name());
SetInputProperty(input, QStringLiteral("color3"), QColor(0, 0, 255).name());
}
}
| 9,758
|
C++
|
.cpp
| 174
| 52.436782
| 170
| 0.770021
|
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
|
18,996
|
colormanager.cpp
|
olive-editor_olive/app/node/color/colormanager/colormanager.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 "colormanager.h"
#include <QDir>
#include <QStandardPaths>
#include "common/define.h"
#include "common/filefunctions.h"
#include "config/config.h"
#include "core.h"
namespace olive {
#define super Node
OCIO::ConstConfigRcPtr ColorManager::default_config_ = nullptr;
ColorManager::ColorManager(Project *project) :
QObject(project),
config_(nullptr)
{
}
void ColorManager::Init()
{
// Set config to our built-in default
config_ = GetDefaultConfig();
SetDefaultInputColorSpace(config_->getCanonicalName(OCIO::ROLE_DEFAULT));
project()->SetColorReferenceSpace(OCIO::ROLE_SCENE_LINEAR);
}
OCIO::ConstConfigRcPtr ColorManager::GetConfig() const
{
return config_;
}
OCIO::ConstConfigRcPtr ColorManager::CreateConfigFromFile(const QString &filename)
{
return OCIO::Config::CreateFromFile(filename.toUtf8());
}
QString ColorManager::GetConfigFilename() const
{
return project()->GetColorConfigFilename();
}
OCIO::ConstConfigRcPtr ColorManager::GetDefaultConfig()
{
return default_config_;
}
void ColorManager::SetUpDefaultConfig()
{
if (!qEnvironmentVariableIsEmpty("OCIO")) {
// Attempt to set config from "OCIO" environment variable
try {
default_config_ = OCIO::Config::CreateFromEnv();
return;
} catch (OCIO::Exception& e) {
qWarning() << "Failed to load config from OCIO environment variable config:" << e.what();
}
}
// Extract OCIO config - kind of hacky, but it'll work
QString dir = QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).filePath(QStringLiteral("ocioconf"));
FileFunctions::CopyDirectory(QStringLiteral(":/ocioconf"),
dir,
true);
qDebug() << "Extracting default OCIO config to" << dir;
default_config_ = CreateConfigFromFile(QDir(dir).filePath(QStringLiteral("config.ocio")));
}
void ColorManager::SetConfigFilename(const QString &filename)
{
project()->SetColorConfigFilename(filename);
}
QStringList ColorManager::ListAvailableDisplays()
{
QStringList displays;
int number_of_displays = config_->getNumDisplays();
for (int i=0;i<number_of_displays;i++) {
displays.append(config_->getDisplay(i));
}
return displays;
}
QString ColorManager::GetDefaultDisplay()
{
return config_->getDefaultDisplay();
}
QStringList ColorManager::ListAvailableViews(QString display)
{
QStringList views;
int number_of_views = config_->getNumViews(display.toUtf8());
for (int i=0;i<number_of_views;i++) {
views.append(config_->getView(display.toUtf8(), i));
}
return views;
}
QString ColorManager::GetDefaultView(const QString &display)
{
return config_->getDefaultView(display.toUtf8());
}
QStringList ColorManager::ListAvailableLooks()
{
QStringList looks;
int number_of_looks = config_->getNumLooks();
for (int i=0;i<number_of_looks;i++) {
looks.append(config_->getLookNameByIndex(i));
}
return looks;
}
QStringList ColorManager::ListAvailableColorspaces() const
{
return ListAvailableColorspaces(config_);
}
QString ColorManager::GetDefaultInputColorSpace() const
{
return project()->GetDefaultInputColorSpace();
}
void ColorManager::SetDefaultInputColorSpace(const QString &s)
{
project()->SetDefaultInputColorSpace(s);
}
QString ColorManager::GetReferenceColorSpace() const
{
return project()->GetColorReferenceSpace();
}
QString ColorManager::GetCompliantColorSpace(const QString &s)
{
if (ListAvailableColorspaces().contains(s)) {
return s;
} else {
return GetDefaultInputColorSpace();
}
}
ColorTransform ColorManager::GetCompliantColorSpace(const ColorTransform &transform, bool force_display)
{
if (transform.is_display() || force_display) {
// Get display information
QString display = transform.display();
QString view = transform.view();
QString look = transform.look();
// Check if display still exists in config
if (!ListAvailableDisplays().contains(display)) {
display = GetDefaultDisplay();
}
// Check if view still exists in display
if (!ListAvailableViews(display).contains(view)) {
view = GetDefaultView(display);
}
// Check if looks still exists
if (!ListAvailableLooks().contains(look)) {
look.clear();
}
return ColorTransform(display, view, look);
} else {
QString output = transform.output();
if (!ListAvailableColorspaces().contains(output)) {
output = GetDefaultInputColorSpace();
}
return ColorTransform(output);
}
}
QStringList ColorManager::ListAvailableColorspaces(OCIO::ConstConfigRcPtr config)
{
QStringList spaces;
if (config) {
int number_of_colorspaces = config->getNumColorSpaces();
for (int i=0;i<number_of_colorspaces;i++) {
spaces.append(config->getColorSpaceNameByIndex(i));
}
}
return spaces;
}
void ColorManager::GetDefaultLumaCoefs(double *rgb) const
{
config_->getDefaultLumaCoefs(rgb);
}
Project *ColorManager::project() const
{
return static_cast<Project*>(parent());
}
void ColorManager::UpdateConfigFromFilename()
{
try {
QString config_filename = GetConfigFilename();
QString old_default_cs = GetDefaultInputColorSpace();
config_ = OCIO::Config::CreateFromFile(config_filename.toUtf8());
// Set new default colorspace appropriately
QString new_default = old_default_cs;
QStringList available_cs = ListAvailableColorspaces();
for (int i=0; i<available_cs.size(); i++) {
const QString &c = available_cs.at(i);
if (c.compare(old_default_cs, Qt::CaseInsensitive)) {
new_default = c;
break;
}
}
SetDefaultInputColorSpace(new_default);
emit ConfigChanged(config_filename);
} catch (OCIO::Exception&) {}
}
}
| 6,451
|
C++
|
.cpp
| 202
| 28.470297
| 123
| 0.740016
|
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
|
18,997
|
opacityeffect.cpp
|
olive-editor_olive/app/node/effect/opacity/opacityeffect.cpp
|
#include "opacityeffect.h"
#include "node/math/math/math.h"
#include "widget/slider/floatslider.h"
namespace olive {
#define super Node
const QString OpacityEffect::kTextureInput = QStringLiteral("tex_in");
const QString OpacityEffect::kValueInput = QStringLiteral("opacity_in");
OpacityEffect::OpacityEffect()
{
MathNode *math = new MathNode();
math->SetOperation(MathNode::kOpMultiply);
SetNodePositionInContext(math, QPointF(0, 0));
AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
AddInput(kValueInput, NodeValue::kFloat, 1.0);
SetInputProperty(kValueInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetInputProperty(kValueInput, QStringLiteral("min"), 0.0);
SetInputProperty(kValueInput, QStringLiteral("max"), 1.0);
SetFlag(kVideoEffect);
SetEffectInput(kTextureInput);
}
void OpacityEffect::Retranslate()
{
super::Retranslate();
SetInputName(kTextureInput, tr("Texture"));
SetInputName(kValueInput, tr("Opacity"));
}
ShaderCode OpacityEffect::GetShaderCode(const ShaderRequest &request) const
{
if (request.id == QStringLiteral("rgbmult")) {
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/opacity_rgb.frag"));
} else {
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/opacity.frag"));
}
}
void OpacityEffect::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
// If there's no texture, no need to run an operation
if (TexturePtr tex = value[kTextureInput].toTexture()) {
if (TexturePtr opacity_tex = value[kValueInput].toTexture()) {
ShaderJob job(value);
job.SetShaderID(QStringLiteral("rgbmult"));
table->Push(NodeValue::kTexture, tex->toJob(job), this);
} else if (!qFuzzyCompare(value[kValueInput].toDouble(), 1.0)) {
table->Push(NodeValue::kTexture, tex->toJob(ShaderJob(value)), this);
} else {
// 1.0 float is a no-op, so just push the texture
table->Push(value[kTextureInput]);
}
}
}
}
| 2,025
|
C++
|
.cpp
| 51
| 36.490196
| 109
| 0.750383
|
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
|
18,998
|
timeformat.cpp
|
olive-editor_olive/app/node/time/timeformat/timeformat.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 "timeformat.h"
#include <QDateTime>
namespace olive {
#define super Node
const QString TimeFormatNode::kTimeInput = QStringLiteral("time_in");
const QString TimeFormatNode::kFormatInput = QStringLiteral("format_in");
const QString TimeFormatNode::kLocalTimeInput = QStringLiteral("localtime_in");
TimeFormatNode::TimeFormatNode()
{
AddInput(kTimeInput, NodeValue::kFloat);
AddInput(kFormatInput, NodeValue::kText, QStringLiteral("hh:mm:ss"));
AddInput(kLocalTimeInput, NodeValue::kBoolean);
}
QString TimeFormatNode::Name() const
{
return tr("Time Format");
}
QString TimeFormatNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.timeformat");
}
QVector<Node::CategoryID> TimeFormatNode::Category() const
{
return {kCategoryGenerator};
}
QString TimeFormatNode::Description() const
{
return tr("Format time (in Unix epoch seconds) into a string.");
}
void TimeFormatNode::Retranslate()
{
super::Retranslate();
SetInputName(kTimeInput, tr("Time"));
SetInputName(kFormatInput, tr("Format"));
SetInputName(kLocalTimeInput, tr("Interpret time as local time"));
}
void TimeFormatNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
qint64 ms_since_epoch = value[kTimeInput].toDouble()*1000;
bool time_is_local = value[kLocalTimeInput].toBool();
QDateTime dt = QDateTime::fromMSecsSinceEpoch(ms_since_epoch, time_is_local ? Qt::LocalTime : Qt::UTC);
QString format = value[kFormatInput].toString();
QString output = dt.toString(format);
table->Push(NodeValue(NodeValue::kText, output, this));
}
}
| 2,321
|
C++
|
.cpp
| 60
| 36.4
| 110
| 0.777431
|
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
|
18,999
|
timeremap.cpp
|
olive-editor_olive/app/node/time/timeremap/timeremap.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 "timeremap.h"
#include "widget/slider/rationalslider.h"
namespace olive {
const QString TimeRemapNode::kTimeInput = QStringLiteral("time_in");
const QString TimeRemapNode::kInputInput = QStringLiteral("input_in");
#define super Node
TimeRemapNode::TimeRemapNode()
{
AddInput(kTimeInput, NodeValue::kRational, QVariant::fromValue(rational(0)), InputFlags(kInputFlagNotConnectable));
SetInputProperty(kTimeInput, QStringLiteral("view"), RationalSlider::kTime);
SetInputProperty(kTimeInput, QStringLiteral("viewlock"), true);
AddInput(kInputInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
}
QString TimeRemapNode::Name() const
{
return tr("Time Remap");
}
QString TimeRemapNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.timeremap");
}
QVector<Node::CategoryID> TimeRemapNode::Category() const
{
return {kCategoryTime};
}
QString TimeRemapNode::Description() const
{
return tr("Arbitrarily remap time through the nodes.");
}
TimeRange TimeRemapNode::InputTimeAdjustment(const QString &input, int element, const TimeRange &input_time, bool clamp) const
{
if (input == kInputInput) {
return TimeRange(GetRemappedTime(input_time.in()), GetRemappedTime(input_time.out()));
} else {
return super::InputTimeAdjustment(input, element, input_time, clamp);
}
}
TimeRange TimeRemapNode::OutputTimeAdjustment(const QString &input, int element, const TimeRange &input_time) const
{
/*if (input == kInputInput) {
rational target_time = GetValueAtTime(kTimeInput, input_time.in()).value<rational>();
return TimeRange(target_time, target_time + input_time.length());
} else {
return super::OutputTimeAdjustment(input, element, input_time);
}*/
return super::OutputTimeAdjustment(input, element, input_time);
}
void TimeRemapNode::Retranslate()
{
super::Retranslate();
SetInputName(kTimeInput, QStringLiteral("Time"));
SetInputName(kInputInput, QStringLiteral("Input"));
}
void TimeRemapNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
table->Push(value[kInputInput]);
}
rational TimeRemapNode::GetRemappedTime(const rational &input) const
{
return GetValueAtTime(kTimeInput, input).value<rational>();
}
}
| 2,972
|
C++
|
.cpp
| 76
| 36.684211
| 126
| 0.779944
|
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,000
|
timeoffsetnode.cpp
|
olive-editor_olive/app/node/time/timeoffset/timeoffsetnode.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 "timeoffsetnode.h"
#include "widget/slider/rationalslider.h"
namespace olive {
const QString TimeOffsetNode::kTimeInput = QStringLiteral("time_in");
const QString TimeOffsetNode::kInputInput = QStringLiteral("input_in");
#define super Node
TimeOffsetNode::TimeOffsetNode()
{
AddInput(kTimeInput, NodeValue::kRational, QVariant::fromValue(rational(0)), InputFlags(kInputFlagNotConnectable));
SetInputProperty(kTimeInput, QStringLiteral("view"), RationalSlider::kTime);
SetInputProperty(kTimeInput, QStringLiteral("viewlock"), true);
AddInput(kInputInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
}
void TimeOffsetNode::Retranslate()
{
super::Retranslate();
SetInputName(kTimeInput, QStringLiteral("Time"));
SetInputName(kInputInput, QStringLiteral("Input"));
}
TimeRange TimeOffsetNode::InputTimeAdjustment(const QString &input, int element, const TimeRange &input_time, bool clamp) const
{
if (input == kInputInput) {
return TimeRange(GetRemappedTime(input_time.in()), GetRemappedTime(input_time.out()));
} else {
return super::InputTimeAdjustment(input, element, input_time, clamp);
}
}
TimeRange TimeOffsetNode::OutputTimeAdjustment(const QString &input, int element, const TimeRange &input_time) const
{
/*if (input == kInputInput) {
rational target_time = GetValueAtTime(kTimeInput, input_time.in()).value<rational>();
return TimeRange(target_time, target_time + input_time.length());
} else {
return super::OutputTimeAdjustment(input, element, input_time);
}*/
return super::OutputTimeAdjustment(input, element, input_time);
}
void TimeOffsetNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
table->Push(value[kInputInput]);
}
rational TimeOffsetNode::GetRemappedTime(const rational &input) const
{
return input + GetValueAtTime(kTimeInput, input).value<rational>();
}
}
| 2,627
|
C++
|
.cpp
| 60
| 41.183333
| 127
| 0.780526
|
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,001
|
volume.cpp
|
olive-editor_olive/app/node/audio/volume/volume.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 "volume.h"
#include "widget/slider/floatslider.h"
namespace olive {
const QString VolumeNode::kSamplesInput = QStringLiteral("samples_in");
const QString VolumeNode::kVolumeInput = QStringLiteral("volume_in");
#define super MathNodeBase
VolumeNode::VolumeNode()
{
AddInput(kSamplesInput, NodeValue::kSamples, InputFlags(kInputFlagNotKeyframable));
AddInput(kVolumeInput, NodeValue::kFloat, 1.0);
SetInputProperty(kVolumeInput, QStringLiteral("min"), 0.0);
SetInputProperty(kVolumeInput, QStringLiteral("view"), FloatSlider::kDecibel);
SetFlag(kAudioEffect);
SetEffectInput(kSamplesInput);
}
QString VolumeNode::Name() const
{
return tr("Volume");
}
QString VolumeNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.volume");
}
QVector<Node::CategoryID> VolumeNode::Category() const
{
return {kCategoryFilter};
}
QString VolumeNode::Description() const
{
return tr("Adjusts the volume of an audio source.");
}
void VolumeNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
// Create a sample job
SampleBuffer buffer = value[kSamplesInput].toSamples();
if (buffer.is_allocated()) {
// If the input is static, we can just do it now which will be faster
if (IsInputStatic(kVolumeInput)) {
auto volume = value[kVolumeInput].toDouble();
if (!qFuzzyCompare(volume, 1.0)) {
buffer.transform_volume(volume);
}
table->Push(NodeValue::kSamples, QVariant::fromValue(buffer), this);
} else {
// Requires job
SampleJob job(globals.time(), kSamplesInput, value);
job.Insert(kVolumeInput, value);
table->Push(NodeValue::kSamples, QVariant::fromValue(job), this);
}
}
}
void VolumeNode::ProcessSamples(const NodeValueRow &values, const SampleBuffer &input, SampleBuffer &output, int index) const
{
return ProcessSamplesInternal(values, kOpMultiply, kSamplesInput, kVolumeInput, input, output, index);
}
void VolumeNode::Retranslate()
{
super::Retranslate();
SetInputName(kSamplesInput, tr("Samples"));
SetInputName(kVolumeInput, tr("Volume"));
}
}
| 2,842
|
C++
|
.cpp
| 76
| 34.328947
| 125
| 0.759212
|
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,002
|
pan.cpp
|
olive-editor_olive/app/node/audio/pan/pan.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 "pan.h"
#include "widget/slider/floatslider.h"
namespace olive {
const QString PanNode::kSamplesInput = QStringLiteral("samples_in");
const QString PanNode::kPanningInput = QStringLiteral("panning_in");
#define super Node
PanNode::PanNode()
{
AddInput(kSamplesInput, NodeValue::kSamples, InputFlags(kInputFlagNotKeyframable));
AddInput(kPanningInput, NodeValue::kFloat, 0.0);
SetInputProperty(kPanningInput, QStringLiteral("min"), -1.0);
SetInputProperty(kPanningInput, QStringLiteral("max"), 1.0);
SetInputProperty(kPanningInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetFlag(kAudioEffect);
SetEffectInput(kSamplesInput);
}
QString PanNode::Name() const
{
return tr("Pan");
}
QString PanNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.pan");
}
QVector<Node::CategoryID> PanNode::Category() const
{
return {kCategoryFilter};
}
QString PanNode::Description() const
{
return tr("Adjust the stereo panning of an audio source.");
}
void PanNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
// Create a sample job
SampleBuffer samples = value[kSamplesInput].toSamples();
if (samples.is_allocated()) {
// This node is only compatible with stereo audio
if (samples.audio_params().channel_count() == 2) {
// If the input is static, we can just do it now which will be faster
if (IsInputStatic(kPanningInput)) {
float pan_volume = value[kPanningInput].toDouble();
if (!qIsNull(pan_volume)) {
if (pan_volume > 0) {
samples.transform_volume_for_channel(0, 1.0f - pan_volume);
} else {
samples.transform_volume_for_channel(1, 1.0f + pan_volume);
}
}
table->Push(NodeValue(NodeValue::kSamples, samples, this));
} else {
// Requires job
table->Push(NodeValue::kSamples, SampleJob(globals.time(), kSamplesInput, value), this);
}
} else {
// Pass right through
table->Push(value[kSamplesInput]);
}
}
}
void PanNode::ProcessSamples(const NodeValueRow &values, const SampleBuffer &input, SampleBuffer &output, int index) const
{
float pan_val = values[kPanningInput].toDouble();
for (int i=0;i<input.audio_params().channel_count();i++) {
output.data(i)[index] = input.data(i)[index];
}
if (pan_val > 0) {
output.data(0)[index] *= (1.0F - pan_val);
} else if (pan_val < 0) {
output.data(1)[index] *= (1.0F - qAbs(pan_val));
}
}
void PanNode::Retranslate()
{
super::Retranslate();
SetInputName(kSamplesInput, tr("Samples"));
SetInputName(kPanningInput, tr("Pan"));
}
}
| 3,385
|
C++
|
.cpp
| 93
| 32.569892
| 122
| 0.714111
|
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,003
|
viewer.cpp
|
olive-editor_olive/app/node/output/viewer/viewer.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 "viewer.h"
#include "config/config.h"
#include "core.h"
#include "node/traverser.h"
namespace olive {
const QString ViewerOutput::kVideoParamsInput = QStringLiteral("video_param_in");
const QString ViewerOutput::kAudioParamsInput = QStringLiteral("audio_param_in");
const QString ViewerOutput::kSubtitleParamsInput = QStringLiteral("subtitle_param_in");
const QString ViewerOutput::kTextureInput = QStringLiteral("tex_in");
const QString ViewerOutput::kSamplesInput = QStringLiteral("samples_in");
const SampleFormat ViewerOutput::kDefaultSampleFormat = SampleFormat::F32P;
#define super Node
ViewerOutput::ViewerOutput(bool create_buffer_inputs, bool create_default_streams) :
last_length_(0),
video_length_(0),
audio_length_(0),
autocache_input_video_(false),
autocache_input_audio_(false),
waveform_requests_enabled_(false)
{
AddInput(kVideoParamsInput, NodeValue::kVideoParams, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable | kInputFlagArray | kInputFlagHidden));
AddInput(kAudioParamsInput, NodeValue::kAudioParams, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable | kInputFlagArray | kInputFlagHidden));
AddInput(kSubtitleParamsInput, NodeValue::kSubtitleParams, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable | kInputFlagArray | kInputFlagHidden));
if (create_buffer_inputs) {
AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
AddInput(kSamplesInput, NodeValue::kSamples, InputFlags(kInputFlagNotKeyframable));
}
if (create_default_streams) {
AddStream(Track::kVideo, QVariant());
AddStream(Track::kAudio, QVariant());
set_default_parameters();
}
SetFlag(kDontShowInParamView);
workarea_ = new TimelineWorkArea(this);
markers_ = new TimelineMarkerList(this);
}
QString ViewerOutput::Name() const
{
return tr("Viewer");
}
QString ViewerOutput::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.vieweroutput");
}
QVector<Node::CategoryID> ViewerOutput::Category() const
{
return {kCategoryOutput};
}
QString ViewerOutput::Description() const
{
return tr("Interface between a Viewer panel and the node system.");
}
QVariant ViewerOutput::data(const DataType &d) const
{
switch (d) {
case DURATION:
{
rational using_timebase;
Timecode::Display using_display = Core::instance()->GetTimecodeDisplay();
// Get first enabled streams
VideoParams video = GetFirstEnabledVideoStream();
AudioParams audio = GetFirstEnabledAudioStream();
SubtitleParams sub = GetFirstEnabledSubtitleStream();
if (video.is_valid() && video.video_type() != VideoParams::kVideoTypeStill) {
// Prioritize video
using_timebase = video.frame_rate_as_time_base();
} else if (audio.is_valid()) {
// Use audio as a backup
// If we're showing in a timecode, we prefer showing audio in seconds instead
if (using_display == Timecode::kTimecodeDropFrame
|| using_display == Timecode::kTimecodeNonDropFrame) {
using_display = Timecode::kTimecodeSeconds;
}
using_timebase = audio.sample_rate_as_time_base();
} else if (sub.is_valid()) {
using_timebase = OLIVE_CONFIG("DefaultSequenceFrameRate").value<rational>();
}
if (!using_timebase.isNull()) {
// Return time transformed to timecode
return QString::fromStdString(Timecode::time_to_timecode(GetLength(), using_timebase, using_display));
}
break;
}
case FREQUENCY_RATE:
{
VideoParams video_stream;
if (HasEnabledVideoStreams()
&& (video_stream = GetFirstEnabledVideoStream()).video_type() != VideoParams::kVideoTypeStill) {
// This is a video editor, prioritize video streams
return tr("%1 FPS").arg(video_stream.frame_rate().toDouble());
} else if (HasEnabledAudioStreams()) {
// No video streams, return audio
AudioParams audio_stream = GetFirstEnabledAudioStream();
return tr("%1 Hz").arg(audio_stream.sample_rate());
}
break;
}
default:
break;
}
return super::data(d);
}
bool ViewerOutput::HasEnabledVideoStreams() const
{
return GetFirstEnabledVideoStream().is_valid();
}
bool ViewerOutput::HasEnabledAudioStreams() const
{
return GetFirstEnabledAudioStream().is_valid();
}
bool ViewerOutput::HasEnabledSubtitleStreams() const
{
return GetFirstEnabledSubtitleStream().is_valid();
}
VideoParams ViewerOutput::GetFirstEnabledVideoStream() const
{
int sz = GetVideoStreamCount();
for (int i=0; i<sz; i++) {
VideoParams vp = GetVideoParams(i);
if (vp.enabled()) {
return vp;
}
}
return VideoParams();
}
AudioParams ViewerOutput::GetFirstEnabledAudioStream() const
{
int sz = GetAudioStreamCount();
for (int i=0; i<sz; i++) {
AudioParams ap = GetAudioParams(i);
if (ap.enabled()) {
return ap;
}
}
return AudioParams();
}
SubtitleParams ViewerOutput::GetFirstEnabledSubtitleStream() const
{
int sz = GetSubtitleStreamCount();
for (int i=0; i<sz; i++) {
SubtitleParams sp = GetSubtitleParams(i);
if (sp.enabled()) {
return sp;
}
}
return SubtitleParams();
}
void ViewerOutput::set_default_parameters()
{
int width = OLIVE_CONFIG("DefaultSequenceWidth").toInt();
int height = OLIVE_CONFIG("DefaultSequenceHeight").toInt();
SetVideoParams(VideoParams(
width,
height,
OLIVE_CONFIG("DefaultSequenceFrameRate").value<rational>(),
static_cast<PixelFormat::Format>(OLIVE_CONFIG("OfflinePixelFormat").toInt()),
VideoParams::kInternalChannelCount,
OLIVE_CONFIG("DefaultSequencePixelAspect").value<rational>(),
OLIVE_CONFIG("DefaultSequenceInterlacing").value<VideoParams::Interlacing>(),
VideoParams::generate_auto_divider(width, height)
));
SetAudioParams(AudioParams(
OLIVE_CONFIG("DefaultSequenceAudioFrequency").toInt(),
OLIVE_CONFIG("DefaultSequenceAudioLayout").toULongLong(),
kDefaultSampleFormat
));
}
void ViewerOutput::InvalidateCache(const TimeRange& range, const QString& from, int element, InvalidateCacheOptions options)
{
Q_UNUSED(element)
if (Node *connected = GetConnectedOutput(from, element)) {
if (from == kTextureInput) {
//connected->thumbnail_cache()->Request(range.Intersected(max_range), PlaybackCache::kPreviewsOnly);
if (autocache_input_video_) {
TimeRange max_range = InputTimeAdjustment(from, element, TimeRange(0, GetVideoLength()), false);
connected->video_frame_cache()->Request(this, range.Intersected(max_range));
}
} else if (from == kSamplesInput) {
TimeRange max_range = InputTimeAdjustment(from, element, TimeRange(0, GetAudioLength()), false);
if (waveform_requests_enabled_) {
connected->waveform_cache()->Request(this, range.Intersected(max_range));
}
if (autocache_input_audio_) {
connected->audio_playback_cache()->Request(this, range.Intersected(max_range));
}
}
}
VerifyLength();
super::InvalidateCache(range, from, element, options);
}
QVector<Track::Reference> ViewerOutput::GetEnabledStreamsAsReferences() const
{
QVector<Track::Reference> refs;
{
int vp_sz = GetVideoStreamCount();
for (int i=0; i<vp_sz; i++) {
if (GetVideoParams(i).enabled()) {
refs.append(Track::Reference(Track::kVideo, i));
}
}
}
{
int ap_sz = GetAudioStreamCount();
for (int i=0; i<ap_sz; i++) {
if (GetAudioParams(i).enabled()) {
refs.append(Track::Reference(Track::kAudio, i));
}
}
}
{
int sp_sz = GetSubtitleStreamCount();
for (int i=0; i<sp_sz; i++) {
if (GetSubtitleParams(i).enabled()) {
refs.append(Track::Reference(Track::kSubtitle, i));
}
}
}
return refs;
}
void ViewerOutput::Retranslate()
{
super::Retranslate();
SetInputName(kVideoParamsInput, tr("Video Parameters"));
SetInputName(kAudioParamsInput, tr("Audio Parameters"));
SetInputName(kSubtitleParamsInput, tr("Subtitle Parameters"));
if (HasInputWithID(kTextureInput)) {
SetInputName(kTextureInput, tr("Texture"));
}
if (HasInputWithID(kSamplesInput)) {
SetInputName(kSamplesInput, tr("Samples"));
}
}
void ViewerOutput::VerifyLength()
{
video_length_ = VerifyLengthInternal(Track::kVideo);
audio_length_ = VerifyLengthInternal(Track::kAudio);
rational subtitle_length = VerifyLengthInternal(Track::kSubtitle);
rational real_length = qMax(subtitle_length, qMax(video_length_, audio_length_));
if (real_length != last_length_) {
last_length_ = real_length;
emit LengthChanged(last_length_);
}
}
void ViewerOutput::SetPlayhead(const rational &t)
{
playhead_ = t;
emit PlayheadChanged(t);
}
void ViewerOutput::InputConnectedEvent(const QString &input, int element, Node *output)
{
if (input == kTextureInput) {
emit TextureInputChanged();
} else if (input == kSamplesInput) {
connect(output->waveform_cache(), &AudioWaveformCache::Validated, this, &ViewerOutput::ConnectedWaveformChanged);
}
super::InputConnectedEvent(input, element, output);
}
void ViewerOutput::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
if (input == kTextureInput) {
emit TextureInputChanged();
} else if (input == kSamplesInput) {
disconnect(output->waveform_cache(), &AudioWaveformCache::Validated, this, &ViewerOutput::ConnectedWaveformChanged);
}
super::InputDisconnectedEvent(input, element, output);
}
rational ViewerOutput::VerifyLengthInternal(Track::Type type) const
{
NodeTraverser traverser;
switch (type) {
case Track::kVideo:
if (IsInputConnected(kTextureInput)) {
NodeValueTable t = traverser.GenerateTable(GetConnectedOutput(kTextureInput), TimeRange(0, 0));
rational r = t.Get(NodeValue::kRational, QStringLiteral("length")).toRational();
if (!r.isNaN()) {
return r;
}
}
break;
case Track::kAudio:
if (IsInputConnected(kSamplesInput)) {
NodeValueTable t = traverser.GenerateTable(GetConnectedOutput(kSamplesInput), TimeRange(0, 0));
rational r = t.Get(NodeValue::kRational, QStringLiteral("length")).toRational();
if (!r.isNaN()) {
return r;
}
}
break;
case Track::kNone:
case Track::kSubtitle:
case Track::kCount:
break;
}
return 0;
}
Node *ViewerOutput::GetConnectedTextureOutput()
{
return GetConnectedOutput(kTextureInput);
}
Node::ValueHint ViewerOutput::GetConnectedTextureValueHint()
{
return GetValueHintForInput(kTextureInput);
}
Node *ViewerOutput::GetConnectedSampleOutput()
{
return GetConnectedOutput(kSamplesInput);
}
Node::ValueHint ViewerOutput::GetConnectedSampleValueHint()
{
return GetValueHintForInput(kSamplesInput);
}
void ViewerOutput::SetWaveformEnabled(bool e)
{
if ((waveform_requests_enabled_ = e)) {
if (Node *connected = this->GetConnectedSampleOutput()) {
TimeRange max_range = InputTimeAdjustment(kSamplesInput, -1, TimeRange(0, GetAudioLength()), false);
TimeRangeList invalid = connected->waveform_cache()->GetInvalidatedRanges(max_range);
for (const TimeRange &r : invalid) {
connected->waveform_cache()->Request(this, r);
}
}
}
}
void ViewerOutput::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
if (HasInputWithID(kTextureInput)) {
NodeValue repush = value[kTextureInput];
repush.set_tag(Track::Reference(Track::kVideo, 0).ToString());
table->Push(repush);
}
if (HasInputWithID(kSamplesInput)) {
NodeValue repush = value[kSamplesInput];
repush.set_tag(Track::Reference(Track::kAudio, 0).ToString());
table->Push(value[kSamplesInput]);
}
}
bool ViewerOutput::LoadCustom(QXmlStreamReader *reader, SerializedData *data)
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("markers")) {
if (!this->GetMarkers()->load(reader)) {
return false;
}
} else if (reader->name() == QStringLiteral("workarea")) {
if (!this->GetWorkArea()->load(reader)) {
return false;
}
} else {
reader->skipCurrentElement();
}
}
return true;
}
void ViewerOutput::SaveCustom(QXmlStreamWriter *writer) const
{
writer->writeStartElement(QStringLiteral("workarea"));
this->GetWorkArea()->save(writer);
writer->writeEndElement(); // workarea
writer->writeStartElement(QStringLiteral("markers"));
this->GetMarkers()->save(writer);
writer->writeEndElement(); // markers
}
void ViewerOutput::InputValueChangedEvent(const QString &input, int element)
{
if (element == 0) {
if (input == kVideoParamsInput) {
VideoParams new_video_params = GetVideoParams();
bool size_changed = cached_video_params_.width() != new_video_params.width() || cached_video_params_.height() != new_video_params.height();
bool frame_rate_changed = cached_video_params_.frame_rate() != new_video_params.frame_rate();
bool pixel_aspect_changed = cached_video_params_.pixel_aspect_ratio() != new_video_params.pixel_aspect_ratio();
bool interlacing_changed = cached_video_params_.interlacing() != new_video_params.interlacing();
if (size_changed) {
emit SizeChanged(new_video_params.width(), new_video_params.height());
}
if (pixel_aspect_changed) {
emit PixelAspectChanged(new_video_params.pixel_aspect_ratio());
}
if (interlacing_changed) {
emit InterlacingChanged(new_video_params.interlacing());
}
if (frame_rate_changed) {
emit FrameRateChanged(new_video_params.frame_rate());
}
emit VideoParamsChanged();
cached_video_params_ = new_video_params;
} else if (input == kAudioParamsInput) {
AudioParams new_audio_params = GetAudioParams();
bool sample_rate_changed = new_audio_params.sample_rate() != cached_audio_params_.sample_rate();
if (sample_rate_changed) {
emit SampleRateChanged(new_audio_params.sample_rate());
}
emit AudioParamsChanged();
cached_audio_params_ = new_audio_params;
}
}
super::InputValueChangedEvent(input, element);
}
void ViewerOutput::set_parameters_from_footage(const QVector<ViewerOutput *> footage)
{
foreach (ViewerOutput* f, footage) {
QVector<VideoParams> video_streams = f->GetEnabledVideoStreams();
QVector<AudioParams> audio_streams = f->GetEnabledAudioStreams();
for (int i=0; i<video_streams.size(); i++) {
const VideoParams& s = video_streams.at(i);
bool found_video_params = false;
rational using_timebase;
if (s.video_type() == VideoParams::kVideoTypeStill) {
// If this is a still image, we'll use it's resolution but won't set
// `found_video_params` in case something with a frame rate comes along which we'll
// prioritize
if (i > 0) {
// Ignore still images past stream 0
continue;
}
using_timebase = GetVideoParams().time_base();
} else {
using_timebase = s.frame_rate_as_time_base();
found_video_params = true;
}
SetVideoParams(VideoParams(s.width(),
s.height(),
using_timebase,
static_cast<PixelFormat::Format>(OLIVE_CONFIG("OfflinePixelFormat").toInt()),
VideoParams::kInternalChannelCount,
s.pixel_aspect_ratio(),
s.interlacing(),
VideoParams::generate_auto_divider(s.width(), s.height())));
if (found_video_params) {
break;
}
}
if (!audio_streams.isEmpty()) {
const AudioParams& s = audio_streams.first();
SetAudioParams(AudioParams(s.sample_rate(), s.channel_layout(), kDefaultSampleFormat));
}
}
}
int ViewerOutput::AddStream(Track::Type type, const QVariant& value)
{
return SetStream(type, value, -1);
}
int ViewerOutput::SetStream(Track::Type type, const QVariant &value, int index_in)
{
QString id;
if (type == Track::kVideo) {
id = kVideoParamsInput;
} else if (type == Track::kAudio) {
id = kAudioParamsInput;
} else if (type == Track::kSubtitle) {
id = kSubtitleParamsInput;
} else {
return -1;
}
// Add another video/audio param to the array for this stream
int index = (index_in == -1) ? InputArraySize(id) : index_in;
if (index >= InputArraySize(id)) {
InputArrayResize(id, index+1);
}
SetStandardValue(id, value, index);
return index;
}
QVector<VideoParams> ViewerOutput::GetEnabledVideoStreams() const
{
QVector<VideoParams> streams;
int vp_sz = GetVideoStreamCount();
for (int i=0; i<vp_sz; i++) {
VideoParams vp = GetVideoParams(i);
if (vp.enabled()) {
streams.append(vp);
}
}
return streams;
}
QVector<AudioParams> ViewerOutput::GetEnabledAudioStreams() const
{
QVector<AudioParams> streams;
int ap_sz = GetAudioStreamCount();
for (int i=0; i<ap_sz; i++) {
AudioParams ap = GetAudioParams(i);
if (ap.enabled()) {
streams.append(ap);
}
}
return streams;
}
}
| 17,943
|
C++
|
.cpp
| 500
| 31.124
| 163
| 0.703725
|
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,004
|
tracklist.cpp
|
olive-editor_olive/app/node/output/track/tracklist.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 "tracklist.h"
#include "node/factory.h"
#include "node/math/math/math.h"
#include "node/math/merge/merge.h"
#include "node/output/viewer/viewer.h"
#include "node/project/sequence/sequence.h"
namespace olive {
TrackList::TrackList(Sequence *parent, const Track::Type &type, const QString &track_input) :
QObject(parent),
track_input_(track_input),
total_length_(0),
type_(type)
{
}
Track *TrackList::GetTrackAt(int index) const
{
if (index >= 0 && index < track_cache_.size()) {
return track_cache_.at(index);
} else {
return nullptr;
}
}
void TrackList::TrackConnected(Node *node, int element)
{
if (element == -1) {
parent()->InvalidateAll(track_input(), element);
return;
}
Track* track = dynamic_cast<Track*>(node);
if (!track) {
return;
}
// Determine where in the cache this block will be
int cache_index = -1;
for (int i=element+1; i<ArraySize(); i++) {
// Find next track because this will be the index we insert at
cache_index = GetCacheIndexFromArrayIndex(i);
if (cache_index >= 0) {
break;
}
}
// If there was no next, this will be inserted at the end
if (cache_index == -1) {
cache_index = track_cache_.size();
}
track_cache_.insert(cache_index, track);
track_array_indexes_.insert(cache_index, element);
// Update track indexes in the list (including this track)
UpdateTrackIndexesFrom(cache_index);
connect(track, &Track::TrackLengthChanged, this, &TrackList::UpdateTotalLength);
connect(track, &Track::TrackHeightChanged, this, [this](){
Track *t = static_cast<Track*>(sender());
emit TrackHeightChanged(t, t->GetTrackHeightInPixels());
});
track->set_type(type_);
track->set_sequence(parent());
emit TrackListChanged();
// This function must be called after the track is added to track_cache_, since it uses track_cache_ to determine
// the track's index
emit TrackAdded(track);
UpdateTotalLength();
}
void TrackList::TrackDisconnected(Node *node, int element)
{
if (element == -1) {
// User has replaced the entire array, we will invalidate everything
parent()->InvalidateAll(track_input(), element);
return;
}
Track* track = dynamic_cast<Track*>(node);
if (!track) {
return;
}
// Traverse through Tracks uncaching and disconnecting them
emit TrackRemoved(track);
int cache_index = GetCacheIndexFromArrayIndex(element);
// Remove track here
track_cache_.removeAt(cache_index);
track_array_indexes_.removeAt(cache_index);
// Update indices for all subsequent tracks
UpdateTrackIndexesFrom(cache_index);
track->SetIndex(-1);
track->set_type(Track::kNone);
track->set_sequence(nullptr);
disconnect(track, &Track::TrackLengthChanged, this, &TrackList::UpdateTotalLength);
emit TrackListChanged();
UpdateTotalLength();
}
void TrackList::UpdateTrackIndexesFrom(int index)
{
for (int i=index; i<track_cache_.size(); i++) {
track_cache_.at(i)->SetIndex(i);
}
}
Project *TrackList::GetParentGraph() const
{
return parent()->parent();
}
const QString& TrackList::track_input() const
{
return track_input_;
}
NodeInput TrackList::track_input(int element) const
{
return NodeInput(parent(), track_input(), element);
}
Sequence *TrackList::parent() const
{
return static_cast<Sequence*>(QObject::parent());
}
int TrackList::ArraySize() const
{
return parent()->InputArraySize(track_input());
}
void TrackList::ArrayAppend()
{
parent()->InputArrayAppend(track_input());
}
void TrackList::ArrayRemoveLast()
{
parent()->InputArrayRemoveLast(track_input());
}
void TrackList::UpdateTotalLength()
{
total_length_ = 0;
foreach (Track* track, track_cache_) {
if (track) {
total_length_ = qMax(total_length_, track->track_length());
}
}
emit LengthChanged(total_length_);
}
}
| 4,550
|
C++
|
.cpp
| 147
| 27.993197
| 115
| 0.723434
|
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,005
|
track.cpp
|
olive-editor_olive/app/node/output/track/track.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 "track.h"
#include <QApplication>
#include <QDebug>
#include <QFontMetrics>
#include "audio/audioprocessor.h"
#include "node/block/clip/clip.h"
#include "node/block/gap/gap.h"
#include "node/block/transition/transition.h"
namespace olive {
#define super Node
const double Track::kTrackHeightDefault = 3.0;
const double Track::kTrackHeightMinimum = 1.5;
const double Track::kTrackHeightInterval = 0.5;
const QString Track::kBlockInput = QStringLiteral("block_in");
const QString Track::kMutedInput = QStringLiteral("muted_in");
const QString Track::kArrayMapInput = QStringLiteral("arraymap_in");
Track::Track() :
track_type_(Track::kNone),
index_(-1),
locked_(false),
sequence_(nullptr),
ignore_arraymap_(0),
arraymap_invalid_(false),
ignore_arraymap_set_(false)
{
AddInput(kBlockInput, NodeValue::kNone, InputFlags(kInputFlagArray | kInputFlagNotKeyframable | kInputFlagHidden | kInputFlagIgnoreInvalidations));
AddInput(kMutedInput, NodeValue::kBoolean, false, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kArrayMapInput, NodeValue::kBinary, InputFlags(kInputFlagStatic | kInputFlagHidden | kInputFlagIgnoreInvalidations));
// Set default height
track_height_ = kTrackHeightDefault;
}
void Track::set_type(const Type &track_type)
{
track_type_ = track_type;
}
const Track::Type& Track::type() const
{
return track_type_;
}
QString Track::Name() const
{
if (track_type_ == Track::kVideo) {
return tr("Video Track %1").arg(index_);
} else if (track_type_ == Track::kAudio) {
return tr("Audio Track %1").arg(index_);
} else if (track_type_ == Track::kSubtitle) {
return tr("Subtitle Track %1").arg(index_);
}
return tr("Track");
}
QString Track::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.track");
}
QVector<Node::CategoryID> Track::Category() const
{
return {kCategoryTimeline};
}
QString Track::Description() const
{
return tr("Node for representing and processing a single array of Blocks sorted by time. Also represents the end of "
"a Sequence.");
}
Node::ActiveElements Track::GetActiveElementsAtTime(const QString &input, const TimeRange &r) const
{
if (input == kBlockInput) {
if (IsMuted() || blocks_.empty() || r.in() >= track_length() || r.out() <= 0) {
return ActiveElements::kNoElements;
} else {
int start = GetBlockIndexAtTime(r.in());
int end = GetBlockIndexAtTime(r.out());
if (start == -1) {
start = 0;
}
if (end == -1) {
end = blocks_.size()-1;
}
if (blocks_.at(end)->in() == r.out()) {
end--;
}
ActiveElements a;
for (int i=start; i<=end; i++) {
Block *b = blocks_.at(i);
if (b->is_enabled() && (dynamic_cast<ClipBlock*>(b) || dynamic_cast<TransitionBlock*>(b))) {
a.add(GetArrayIndexFromCacheIndex(i));
}
}
if (a.elements().empty()) {
return ActiveElements::kNoElements;
} else {
return a;
}
}
} else {
return super::GetActiveElementsAtTime(input, r);
}
}
void Track::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
if (this->type() == Track::kVideo) {
// Just pass straight through
NodeValueArray a = value[kBlockInput].toArray();
if (!a.empty()) {
table->Push(a.begin()->second);
}
} else if (this->type() == Track::kAudio) {
// Audio
ProcessAudioTrack(value, globals, table);
}
}
TimeRange Track::InputTimeAdjustment(const QString& input, int element, const TimeRange& input_time, bool clamp) const
{
if (input == kBlockInput && element >= 0) {
int cache_index = GetCacheIndexFromArrayIndex(element);
if (cache_index > -1) {
TimeRange r = input_time;
Block *b = blocks_.at(cache_index);
if (clamp) {
r.set_range(std::max(r.in(), b->in()), std::min(r.out(), b->out()));
}
return TransformRangeForBlock(b, r);
}
}
return Node::InputTimeAdjustment(input, element, input_time, clamp);
}
TimeRange Track::OutputTimeAdjustment(const QString& input, int element, const TimeRange& input_time) const
{
if (input == kBlockInput && element >= 0) {
int cache_index = GetCacheIndexFromArrayIndex(element);
if (cache_index > -1) {
return TransformRangeFromBlock(blocks_.at(cache_index), input_time);
}
}
return Node::OutputTimeAdjustment(input, element, input_time);
}
const double &Track::GetTrackHeight() const
{
return track_height_;
}
void Track::SetTrackHeight(const double &height)
{
track_height_ = height;
emit TrackHeightChanged(track_height_);
}
bool Track::LoadCustom(QXmlStreamReader *reader, SerializedData *data)
{
ignore_arraymap_set_ = true;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("height")) {
this->SetTrackHeight(reader->readElementText().toDouble());
} else {
reader->skipCurrentElement();
}
}
return true;
}
void Track::SaveCustom(QXmlStreamWriter *writer) const
{
writer->writeTextElement(QStringLiteral("height"), QString::number(this->GetTrackHeight()));
}
void Track::PostLoadEvent(SerializedData *data)
{
ignore_arraymap_set_ = false;
RefreshBlockCacheFromArrayMap();
}
void Track::InputValueChangedEvent(const QString &input, int element)
{
Q_UNUSED(element)
if (input == kMutedInput) {
emit MutedChanged(IsMuted());
} else if (input == kArrayMapInput) {
if (ignore_arraymap_ > 0) {
ignore_arraymap_--;
} else {
RefreshBlockCacheFromArrayMap();
}
}
}
void Track::Retranslate()
{
super::Retranslate();
SetInputName(kBlockInput, tr("Blocks"));
SetInputName(kMutedInput, tr("Muted"));
}
void Track::SetIndex(const int &index)
{
int old = index_;
index_ = index;
emit IndexChanged(old, index_);
}
Block *Track::BlockContainingTime(const rational &time) const
{
foreach (Block* block, blocks_) {
if (block->in() < time && block->out() > time) {
return block;
} else if (block->out() == time) {
break;
}
}
return nullptr;
}
Block *Track::NearestBlockBefore(const rational &time) const
{
foreach (Block* block, blocks_) {
// Blocks are sorted by time, so the first Block who's out point is at/after this time is the correct Block
if (block->in() == time) {
break;
}
if (block->out() >= time) {
return block;
}
}
return nullptr;
}
Block *Track::NearestBlockBeforeOrAt(const rational &time) const
{
foreach (Block* block, blocks_) {
// Blocks are sorted by time, so the first Block who's out point is at/after this time is the correct Block
if (block->out() > time) {
return block;
}
}
return nullptr;
}
Block *Track::NearestBlockAfterOrAt(const rational &time) const
{
foreach (Block* block, blocks_) {
// Blocks are sorted by time, so the first Block after this time is the correct Block
if (block->in() >= time) {
return block;
}
}
return nullptr;
}
Block *Track::NearestBlockAfter(const rational &time) const
{
foreach (Block* block, blocks_) {
// Blocks are sorted by time, so the first Block after this time is the correct Block
if (block->in() > time) {
return block;
}
}
return nullptr;
}
bool Track::IsRangeFree(const TimeRange &range) const
{
Block *b = NearestBlockBeforeOrAt(range.in());
if (!b) {
// No block here, assume track is empty here
return true;
}
if (!dynamic_cast<GapBlock*>(b)) {
// There's a block at or around the start point that isn't a gap, range is not free
return false;
}
while ((b = b->next())) {
if (b->in() >= range.out()) {
// This block is after the range, no longer relevant
break;
} else if (!dynamic_cast<GapBlock*>(b)) {
// Found a block in this range, range is not free
return false;
}
}
// If we get here, we couldn't find anything in the way of this range
return true;
}
void Track::InvalidateCache(const TimeRange& range, const QString& from, int element, InvalidateCacheOptions options)
{
TimeRange limited;
const Block* b;
if (from == kBlockInput
&& element >= 0
&& (b = dynamic_cast<const Block*>(GetConnectedOutput(from, element)))
&& !options.value(QStringLiteral("lengthevent")).toBool()) {
// Limit the range signal to the corresponding block
TimeRange transformed = TransformRangeFromBlock(b, range);
if (transformed.out() <= b->in() || transformed.in() >= b->out()) {
return;
}
limited = TimeRange(qMax(transformed.in(), b->in()), qMin(transformed.out(), b->out()));
} else {
limited = range;
}
// NOTE: For now, I figure we drop this key, but we may find in the future that it's advantageous
// to keep it
options.remove(QStringLiteral("lengthevent"));
Node::InvalidateCache(limited, from, element, options);
}
void Track::InsertBlockBefore(Block* block, Block* after)
{
if (!after) {
AppendBlock(block);
} else {
InsertBlockAtIndex(block, blocks_.indexOf(after));
}
}
void Track::InsertBlockAfter(Block *block, Block *before)
{
if (!before) {
PrependBlock(block);
} else {
int before_index = blocks_.indexOf(before);
Q_ASSERT(before_index >= 0);
InsertBlockAtIndex(block, before_index + 1);
}
}
void Track::PrependBlock(Block *block)
{
InsertBlockAtIndex(block, 0);
}
void Track::InsertBlockAtIndex(Block *block, int index)
{
// Set track
Q_ASSERT(block->track() == nullptr);
block->set_track(this);
// Update array
int array_index = ConnectBlock(block);
blocks_.insert(index, block);
block_array_indexes_.insert(index, array_index);
// Handle previous/next
Block *previous = (index > 0) ? blocks_.at(index - 1) : nullptr;
Block *next = (index < blocks_.size()-1) ? blocks_.at(index + 1) : nullptr ;
Block::set_previous_next(previous, block);
Block::set_previous_next(block, next);
// Update in/out
UpdateInOutFrom(index);
connect(block, &Block::LengthChanged, this, &Track::BlockLengthChanged);
Node::InvalidateCache(TimeRange(block->in(), track_length()), kBlockInput);
emit BlockAdded(block);
UpdateArrayMap();
}
void Track::AppendBlock(Block *block)
{
InsertBlockAtIndex(block, blocks_.size());
}
void Track::RippleRemoveBlock(Block *block)
{
rational remove_in = block->in();
rational remove_out = block->out();
emit BlockRemoved(block);
// Set track
Q_ASSERT(block->track() == this);
block->set_track(nullptr);
// Update array
int index = blocks_.indexOf(block);
Q_ASSERT(index != -1);
int array_index = block_array_indexes_.at(index);
blocks_.removeAt(index);
block_array_indexes_.removeAt(index);
Node::DisconnectEdge(block, NodeInput(this, kBlockInput, array_index));
empty_inputs_.push_back(array_index);
disconnect(block, &Block::LengthChanged, this, &Track::BlockLengthChanged);
// Handle previous/next
Block *previous = (index > 0) ? blocks_.at(index - 1) : nullptr;
Block *next = (index < blocks_.size()) ? blocks_.at(index) : nullptr;
Block::set_previous_next(previous, next);
block->set_previous(nullptr);
block->set_next(nullptr);
block->set_in(0);
block->set_out(block->length());
// Update in/outs
UpdateInOutFrom(index);
Node::InvalidateCache(TimeRange(remove_in, qMax(track_length(), remove_out)), kBlockInput);
UpdateArrayMap();
}
void Track::ReplaceBlock(Block *old, Block *replace)
{
emit BlockRemoved(old);
// Set track
Q_ASSERT(old->track() == this);
old->set_track(nullptr);
Q_ASSERT(replace->track() == nullptr);
replace->set_track(this);
// Update array
int cache_index = blocks_.indexOf(old);
int index_of_old_block = GetArrayIndexFromCacheIndex(cache_index);
DisconnectEdge(old, NodeInput(this, kBlockInput, index_of_old_block));
ConnectEdge(replace, NodeInput(this, kBlockInput, index_of_old_block));
blocks_.replace(cache_index, replace);
disconnect(old, &Block::LengthChanged, this, &Track::BlockLengthChanged);
connect(replace, &Block::LengthChanged, this, &Track::BlockLengthChanged);
// Handle previous/next
replace->set_previous(old->previous());
replace->set_next(old->next());
old->set_previous(nullptr);
old->set_next(nullptr);
if (replace->previous()) {
replace->previous()->set_next(replace);
}
if (replace->next()) {
replace->next()->set_previous(replace);
}
if (old->length() == replace->length()) {
replace->set_in(replace->previous() ? replace->previous()->out() : 0);
replace->set_out(replace->in() + replace->length());
Node::InvalidateCache(TimeRange(replace->in(), replace->out()), kBlockInput);
} else {
// Update in/outs
UpdateInOutFrom(cache_index);
Node::InvalidateCache(TimeRange(replace->in(), track_length()), kBlockInput);
}
emit BlockAdded(replace);
UpdateArrayMap();
}
rational Track::track_length() const
{
if (blocks_.isEmpty()) {
return 0;
} else {
return blocks_.last()->out();
}
}
bool Track::IsMuted() const
{
return GetStandardValue(kMutedInput).toBool();
}
bool Track::IsLocked() const
{
return locked_;
}
void Track::SetMuted(bool e)
{
SetStandardValue(kMutedInput, e);
}
void Track::SetLocked(bool e)
{
locked_ = e;
}
void Track::InputConnectedEvent(const QString &input, int element, Node *node)
{
if (arraymap_invalid_ && input == kBlockInput && element >= 0) {
RefreshBlockCacheFromArrayMap();
}
}
void Track::UpdateInOutFrom(int index)
{
// Find block just before this one to find the last out point
rational last_out = (index == 0) ? 0 : blocks_.at(index - 1)->out();
// Iterate through all blocks updating their in/outs
for (int i=index; i<blocks_.size(); i++) {
Block* b = blocks_.at(i);
b->set_in(last_out);
last_out += b->length();
b->set_out(last_out);
}
emit BlocksRefreshed();
// Update track length
emit TrackLengthChanged();
}
int Track::GetArrayIndexFromBlock(Block *block) const
{
return block_array_indexes_.at(blocks_.indexOf(block));
}
int Track::GetArrayIndexFromCacheIndex(int index) const
{
return block_array_indexes_.at(index);
}
int Track::GetCacheIndexFromArrayIndex(int index) const
{
return block_array_indexes_.indexOf(index);
}
int Track::GetBlockIndexAtTime(const rational &time) const
{
if (time < 0 || time >= track_length()) {
return -1;
}
// Use binary search to find block at time
int low = 0;
int high = blocks_.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
Block* block = blocks_.at(mid);
if (block->in() <= time && block->out() > time) {
return mid;
} else if (block->out() <= time) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
void Track::ProcessAudioTrack(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
const TimeRange &range = globals.time();
// All these blocks will need to output to a buffer so we create one here
SampleBuffer block_range_buffer(globals.aparams(), range.length());
block_range_buffer.silence();
// Loop through active blocks retrieving their audio
NodeValueArray arr = value[kBlockInput].toArray();
for (auto it=arr.cbegin(); it!=arr.cend(); it++) {
Block *b = blocks_.at(GetCacheIndexFromArrayIndex(it->first));
TimeRange range_for_block(qMax(b->in(), range.in()),
qMin(b->out(), range.out()));
qint64 source_offset = 0;
qint64 destination_offset = globals.aparams().time_to_samples(range_for_block.in() - range.in());
qint64 max_dest_sz = globals.aparams().time_to_samples(range_for_block.length());
// Destination buffer
SampleBuffer samples_from_this_block = it->second.toSamples();
if (samples_from_this_block.is_allocated()) {
// If this is a clip, we might have extra speed/reverse information
if (ClipBlock *clip_cast = dynamic_cast<ClipBlock*>(b)) {
double speed_value = clip_cast->speed();
bool reversed = clip_cast->reverse();
if (qIsNull(speed_value)) {
// Just silence, don't think there's any other practical application of 0 speed audio
samples_from_this_block.silence();
} else if (!qFuzzyCompare(speed_value, 1.0)) {
if (clip_cast->maintain_audio_pitch()) {
AudioProcessor processor;
if (processor.Open(samples_from_this_block.audio_params(), samples_from_this_block.audio_params(), speed_value)) {
AudioProcessor::Buffer out;
// FIXME: This is not the best way to do this, the TempoProcessor works best
// when it's given a continuous stream of audio, which is challenging
// in our current "modular" audio system. This should still work reasonably
// well on export (assuming audio is all generated at once on export), but
// users may hear clicks and pops in the audio during preview due to this
// approach.
int r = processor.Convert(samples_from_this_block.to_raw_ptrs().data(), samples_from_this_block.sample_count(), nullptr);
if (r < 0) {
qCritical() << "Failed to change tempo of audio:" << r;
} else {
processor.Flush();
processor.Convert(nullptr, 0, &out);
if (!out.empty()) {
int nb_samples = out.front().size() * samples_from_this_block.audio_params().bytes_per_sample_per_channel();
if (nb_samples) {
SampleBuffer new_samples(samples_from_this_block.audio_params(), nb_samples);
for (int i=0; i<out.size(); i++) {
memcpy(new_samples.data(i), out[i].data(), out[i].size());
}
samples_from_this_block = new_samples;
}
}
}
}
} else {
// Multiply time
samples_from_this_block.speed(speed_value);
}
}
if (reversed) {
samples_from_this_block.reverse();
}
}
qint64 copy_length = qMin(max_dest_sz, qint64(samples_from_this_block.sample_count() - source_offset));
// Copy samples into destination buffer
for (int i=0; i<samples_from_this_block.audio_params().channel_count(); i++) {
block_range_buffer.set(i, samples_from_this_block.data(i) + source_offset, destination_offset, copy_length);
}
}
}
table->Push(NodeValue::kSamples, QVariant::fromValue(block_range_buffer), this);
}
int Track::ConnectBlock(Block *b)
{
if (!empty_inputs_.empty()) {
int index = empty_inputs_.front();
empty_inputs_.pop_front();
Node::ConnectEdge(b, NodeInput(this, kBlockInput, index));
return index;
} else {
int old_sz = InputArraySize(kBlockInput);
InputArrayAppend(kBlockInput);
Node::ConnectEdge(b, NodeInput(this, kBlockInput, old_sz));
return old_sz;
}
}
void Track::UpdateArrayMap()
{
ignore_arraymap_++;
SetStandardValue(kArrayMapInput, QByteArray(reinterpret_cast<const char *>(block_array_indexes_.data()), block_array_indexes_.size() * sizeof(uint32_t)));
}
void Track::RefreshBlockCacheFromArrayMap()
{
if (ignore_arraymap_set_) {
return;
}
// Disconnecting any existing blocks
for (Block *b : blocks_) {
Q_ASSERT(b->track() == this);
b->set_track(nullptr);
b->set_previous(nullptr);
b->set_next(nullptr);
b->set_in(0);
b->set_out(b->length());
disconnect(b, &Block::LengthChanged, this, &Track::BlockLengthChanged);
}
QByteArray bytes = GetStandardValue(kArrayMapInput).toByteArray();
block_array_indexes_.resize(bytes.size() / sizeof(uint32_t));
memcpy(block_array_indexes_.data(), bytes.data(), bytes.size());
blocks_.clear();
blocks_.reserve(block_array_indexes_.size());
Block *prev = nullptr;
arraymap_invalid_ = false;
for (int i = 0; i < block_array_indexes_.size(); i++) {
Block *b = static_cast<Block*>(GetConnectedOutput(kBlockInput, block_array_indexes_.at(i)));
Block::set_previous_next(prev, b);
if (b) {
b->set_track(this);
connect(b, &Block::LengthChanged, this, &Track::BlockLengthChanged);
blocks_.append(b);
prev = b;
} else {
block_array_indexes_.resize(i);
arraymap_invalid_ = true;
break;
}
}
if (prev) {
prev->set_next(nullptr);
}
UpdateInOutFrom(0);
}
void Track::BlockLengthChanged()
{
// Assumes sender is a Block
Block* b = static_cast<Block*>(sender());
UpdateInOutFrom(blocks_.indexOf(b));
}
uint qHash(const Track::Reference &r, uint seed)
{
// Not super efficient, but couldn't think of any better way to ensure a different hash each time
return ::qHash(QStringLiteral("%1:%2").arg(QString::number(r.type()),
QString::number(r.index())),
seed);
}
QDataStream &operator<<(QDataStream &out, const Track::Reference &ref)
{
out << static_cast<int>(ref.type()) << ref.index();
return out;
}
QDataStream &operator>>(QDataStream &in, Track::Reference &ref)
{
int type;
int index;
in >> type >> index;
ref = Track::Reference(static_cast<Track::Type>(type), index);
return in;
}
}
| 22,120
|
C++
|
.cpp
| 656
| 29.29878
| 156
| 0.669798
|
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,006
|
sequence.cpp
|
olive-editor_olive/app/node/project/sequence/sequence.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 "sequence.h"
#include <QThread>
#include "panel/timeline/timeline.h"
#include "ui/icons/icons.h"
#include "timeline/timelineundogeneral.h"
namespace olive {
const QString Sequence::kTrackInputFormat = QStringLiteral("track_in_%1");
#define super ViewerOutput
Sequence::Sequence()
{
SetFlag(kIsItem);
// Create TrackList instances
track_lists_.resize(Track::kCount);
for (int i=0;i<Track::kCount;i++) {
// Create track input
QString track_input_id = kTrackInputFormat.arg(i);
AddInput(track_input_id, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable | kInputFlagArray | kInputFlagHidden | kInputFlagIgnoreInvalidations));
TrackList* list = new TrackList(this, static_cast<Track::Type>(i), track_input_id);
track_lists_.replace(i, list);
connect(list, &TrackList::TrackListChanged, this, &Sequence::UpdateTrackCache);
connect(list, &TrackList::LengthChanged, this, &Sequence::VerifyLength);
connect(list, &TrackList::TrackAdded, this, &Sequence::TrackAdded);
connect(list, &TrackList::TrackRemoved, this, &Sequence::TrackRemoved);
}
}
void Sequence::add_default_nodes(MultiUndoCommand* command)
{
// Create tracks and connect them to the viewer
UndoCommand* video_track_command = new TimelineAddTrackCommand(track_list(Track::kVideo));
UndoCommand* audio_track_command = new TimelineAddTrackCommand(track_list(Track::kAudio));
if (command) {
command->add_child(video_track_command);
command->add_child(audio_track_command);
} else {
video_track_command->redo_now();
audio_track_command->redo_now();
delete video_track_command;
delete audio_track_command;
}
}
QVariant Sequence::data(const DataType &d) const
{
if (d == ICON) {
return icon::Sequence;
}
return super::data(d);
}
QVector<Track *> Sequence::GetUnlockedTracks() const
{
QVector<Track*> tracks = GetTracks();
for (int i=0;i<tracks.size();i++) {
if (tracks.at(i)->IsLocked()) {
tracks.removeAt(i);
i--;
}
}
return tracks;
}
void Sequence::Retranslate()
{
super::Retranslate();
for (int i=0;i<Track::kCount;i++) {
QString input_name;
switch (static_cast<Track::Type>(i)) {
case Track::kVideo:
input_name = tr("Video Tracks");
break;
case Track::kAudio:
input_name = tr("Audio Tracks");
break;
case Track::kSubtitle:
input_name = tr("Subtitle Tracks");
break;
case Track::kNone:
case Track::kCount:
break;
}
if (!input_name.isEmpty()) {
SetInputName(kTrackInputFormat.arg(i), input_name);
}
}
}
void Sequence::InvalidateCache(const TimeRange &range, const QString &from, int element, InvalidateCacheOptions options)
{
if (from == kTrackInputFormat.arg(Track::kSubtitle)) {
emit SubtitlesChanged(range);
}
super::InvalidateCache(range, from, element, options);
}
rational Sequence::VerifyLengthInternal(Track::Type type) const
{
if (!track_lists_.isEmpty()) {
switch (type) {
case Track::kVideo:
return track_lists_.at(Track::kVideo)->GetTotalLength();
case Track::kAudio:
return track_lists_.at(Track::kAudio)->GetTotalLength();
case Track::kSubtitle:
return track_lists_.at(Track::kSubtitle)->GetTotalLength();
case Track::kNone:
case Track::kCount:
break;
}
}
return 0;
}
void Sequence::InputConnectedEvent(const QString &input, int element, Node *output)
{
foreach (TrackList* list, track_lists_) {
if (list->track_input() == input) {
// Return because we found our input
list->TrackConnected(output, element);
return;
}
}
super::InputConnectedEvent(input, element, output);
}
void Sequence::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
foreach (TrackList* list, track_lists_) {
if (list->track_input() == input) {
// Return because we found our input
list->TrackDisconnected(output, element);
return;
}
}
super::InputDisconnectedEvent(input, element, output);
}
void Sequence::UpdateTrackCache()
{
track_cache_.clear();
foreach (TrackList* list, track_lists_) {
foreach (Track* track, list->GetTracks()) {
track_cache_.append(track);
}
}
}
}
| 4,955
|
C++
|
.cpp
| 152
| 28.782895
| 154
| 0.711438
|
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,007
|
serializer210528.cpp
|
olive-editor_olive/app/node/project/serializer/serializer210528.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 "serializer210528.h"
#include "config/config.h"
#include "node/factory.h"
#include "node/group/group.h"
namespace olive {
ProjectSerializer210528::LoadData ProjectSerializer210528::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
XMLNodeData xml_node_data;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("uuid")) {
project->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("nodes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
bool is_root = false;
bool is_cm = false;
bool is_settings = false;
QString id;
{
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
} else if (attr.name() == QStringLiteral("root") && attr.value() == QStringLiteral("1")) {
is_root = true;
} else if (attr.name() == QStringLiteral("cm") && attr.value() == QStringLiteral("1")) {
is_cm = true;
} else if (attr.name() == QStringLiteral("settings") && attr.value() == QStringLiteral("1")) {
is_settings = true;
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
Node* node;
bool handled_elsewhere = false;
if (is_root) {
project->Initialize();
node = project->root();
} else if (is_cm) {
LoadColorManager(reader, project);
handled_elsewhere = true;
} else if (is_settings) {
LoadProjectSettings(reader, project);
handled_elsewhere = true;
} else {
node = NodeFactory::CreateFromID(id);
}
if (!handled_elsewhere) {
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
LoadNode(node, xml_node_data, reader);
node->setParent(project);
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("positions")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("context")) {
quintptr context_ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
context_ptr = attr.value().toULongLong();
break;
}
}
Node *context = xml_node_data.node_ptrs.value(context_ptr);
if (!context) {
qWarning() << "Failed to find pointer for context";
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr node_ptr;
Node::Position node_pos;
if (LoadPosition(reader, &node_ptr, &node_pos)) {
Node *node = xml_node_data.node_ptrs.value(node_ptr);
if (node) {
context->SetNodePositionInContext(node, node_pos);
} else {
qWarning() << "Failed to find pointer for node position";
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
// Skip this
reader->skipCurrentElement();
}
}
// Make connections
PostConnect(xml_node_data);
// Resolve tracks
for (Node *n : project->nodes()) {
n->SetCachesEnabled(true);
if (Track *t = dynamic_cast<Track *>(n)) {
for (int i = 0; i < t->InputArraySize(Track::kBlockInput); i++) {
Block *b = static_cast<Block*>(t->GetConnectedOutput(Track::kBlockInput, i));
if (!b->track()) {
t->AppendBlock(b);
}
}
}
}
return LoadData();
}
void ProjectSerializer210528::LoadNode(Node *node, XMLNodeData &xml_node_data, QXmlStreamReader *reader) const
{
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("input")) {
LoadInput(node, reader, xml_node_data);
} else if (reader->name() == QStringLiteral("ptr")) {
xml_node_data.node_ptrs.insert(reader->readElementText().toULongLong(), node);
} else if (reader->name() == QStringLiteral("label")) {
node->SetLabel(reader->readElementText());
} else if (reader->name() == QStringLiteral("color")) {
node->SetOverrideColor(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("links")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("link")) {
xml_node_data.block_links.append({node, reader->readElementText().toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("custom")) {
LoadNodeCustom(reader, node, xml_node_data);
} else if (reader->name() == QStringLiteral("connections")) {
// Load connections
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("connection")) {
QString param_id;
int ele = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("element")) {
ele = attr.value().toInt();
} else if (attr.name() == QStringLiteral("input")) {
param_id = attr.value().toString();
}
}
QString output_node_id;
QString output_param_id;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
output_node_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("output")) {
output_param_id = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.desired_connections.append({NodeInput(node, param_id, ele), output_node_id.toULongLong(), output_param_id});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("hints")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("hint")) {
QString input;
int element = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
input = attr.value().toString();
} else if (attr.name() == QStringLiteral("element")) {
element = attr.value().toInt();
}
}
Node::ValueHint vh;
LoadValueHint(&vh, reader);
node->SetValueHintForInput(input, vh, element);
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
node->LoadFinishedEvent();
}
void ProjectSerializer210528::LoadColorManager(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("config") || id == QStringLiteral("default_input") || id == QStringLiteral("reference_space")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("default_input")) {
// Default color space
// NOTE: Stupidly, we saved these as integers which means we can't add anything to the OCIO
// config. So we must convert back to string here.
static const QStringList list = {
QStringLiteral("Linear"),
QStringLiteral("CIE-XYZ D65"),
QStringLiteral("Filmic Log Encoding"),
QStringLiteral("sRGB OETF"),
QStringLiteral("Apple DCI-P3 D65"),
QStringLiteral("AppleP3 sRGB OETF"),
QStringLiteral("BT.1886 EOTF"),
QStringLiteral("AppleP3 Filmic Log Encoding"),
QStringLiteral("BT.1886 Filmic Log Encoding"),
QStringLiteral("Fuji F-Log OETF"),
QStringLiteral("Fuji F-Log F-Gamut"),
QStringLiteral("Panasonic V-Log V-Gamut"),
QStringLiteral("Arri Wide Gamut / LogC EI 800"),
QStringLiteral("Arri Wide Gamut / LogC EI 400"),
QStringLiteral("Blackmagic Film Wide Gamut (Gen 5)"),
QStringLiteral("Rec.709 OETF"),
QStringLiteral("Non-Colour Data")
};
int num_value = value.toInt();
value = list.at(num_value);
project->SetDefaultInputColorSpace(value);
} else if (id == QStringLiteral("reference_space")) {
// Reference space
if (value == QStringLiteral("1")) {
value = OCIO::ROLE_COMPOSITING_LOG;
} else {
value = OCIO::ROLE_SCENE_LINEAR;
}
project->SetColorReferenceSpace(value);
} else {
// Config filename
project->SetColorConfigFilename(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210528::LoadProjectSettings(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("cache_setting") || id == QStringLiteral("cache_path")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("cache_setting")) {
project->SetCacheLocationSetting(static_cast<Project::CacheSetting>(value.toInt()));
} else {
project->SetCustomCachePath(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210528::LoadInput(Node *node, QXmlStreamReader *reader, XMLNodeData &xml_node_data) const
{
QString param_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
param_id = attr.value().toString();
break;
}
}
if (param_id.isEmpty()) {
qWarning() << "Failed to load parameter with missing ID";
reader->skipCurrentElement();
return;
}
if (!node->HasInputWithID(param_id)) {
qWarning() << "Failed to load parameter that didn't exist:" << param_id;
reader->skipCurrentElement();
return;
}
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("primary")) {
// Load primary immediate
LoadImmediate(reader, node, param_id, -1, xml_node_data);
} else if (reader->name() == QStringLiteral("subelements")) {
// Load subelements
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("count")) {
node->InputArrayResize(param_id, attr.value().toInt());
}
}
int element_counter = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
LoadImmediate(reader, node, param_id, element_counter, xml_node_data);
element_counter++;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210528::LoadImmediate(QXmlStreamReader *reader, Node *node, const QString& input, int element, XMLNodeData &xml_node_data) const
{
Q_UNUSED(xml_node_data)
NodeValue::Type data_type = node->GetInputDataType(input);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
// Load standard value
int val_index = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
QVariant value_on_track;
if (data_type == NodeValue::kVideoParams) {
VideoParams vp;
vp.Load(reader);
value_on_track = QVariant::fromValue(vp);
} else if (data_type == NodeValue::kAudioParams) {
AudioParams ap = TypeSerializer::LoadAudioParams(reader);
value_on_track = QVariant::fromValue(ap);
} else {
QString value_text = reader->readElementText();
if (!value_text.isEmpty()) {
value_on_track = NodeValue::StringToValue(data_type, value_text, true);
}
}
node->SetSplitStandardValueOnTrack(input, val_index, value_on_track, element);
val_index++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframing") && node->IsInputKeyframable(input)) {
node->SetInputIsKeyframing(input, reader->readElementText().toInt(), element);
} else if (reader->name() == QStringLiteral("keyframes")) {
int track = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("key")) {
QString key_input;
rational key_time;
NodeKeyframe::Type key_type = NodeKeyframe::kLinear;
QVariant key_value;
QPointF key_in_handle;
QPointF key_out_handle;
XMLAttributeLoop(reader, attr) {
if (IsCancelled()) {
return;
}
if (attr.name() == QStringLiteral("input")) {
key_input = attr.value().toString();
} else if (attr.name() == QStringLiteral("time")) {
key_time = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("type")) {
key_type = static_cast<NodeKeyframe::Type>(attr.value().toInt());
} else if (attr.name() == QStringLiteral("inhandlex")) {
key_in_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("inhandley")) {
key_in_handle.setY(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandlex")) {
key_out_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandley")) {
key_out_handle.setY(attr.value().toDouble());
}
}
key_value = NodeValue::StringToValue(data_type, reader->readElementText(), true);
NodeKeyframe* key = new NodeKeyframe(key_time, key_value, key_type, track, element, key_input, node);
key->set_bezier_control_in(key_in_handle);
key->set_bezier_control_out(key_out_handle);
} else {
reader->skipCurrentElement();
}
}
track++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("csinput")) {
node->SetInputProperty(input, QStringLiteral("col_input"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csdisplay")) {
node->SetInputProperty(input, QStringLiteral("col_display"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csview")) {
node->SetInputProperty(input, QStringLiteral("col_view"), reader->readElementText());
} else if (reader->name() == QStringLiteral("cslook")) {
node->SetInputProperty(input, QStringLiteral("col_look"), reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
}
bool ProjectSerializer210528::LoadPosition(QXmlStreamReader *reader, quintptr *node_ptr, Node::Position *pos) const
{
bool got_node_ptr = false;
bool got_pos_x = false;
bool got_pos_y = false;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
*node_ptr = attr.value().toULongLong();
got_node_ptr = true;
break;
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("x")) {
pos->position.setX(reader->readElementText().toDouble());
got_pos_x = true;
} else if (reader->name() == QStringLiteral("y")) {
pos->position.setY(reader->readElementText().toDouble());
got_pos_y = true;
} else if (reader->name() == QStringLiteral("expanded")) {
pos->expanded = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
return got_node_ptr && got_pos_x && got_pos_y;
}
void ProjectSerializer210528::PostConnect(const XMLNodeData &xml_node_data) const
{
foreach (const XMLNodeData::SerializedConnection& con, xml_node_data.desired_connections) {
if (Node *out = xml_node_data.node_ptrs.value(con.output_node)) {
// Use output param as hint tag since we grandfathered those in
Node::ValueHint hint(con.output_param);
Node::ConnectEdge(out, con.input);
con.input.node()->SetValueHintForInput(con.input.input(), hint, con.input.element());
}
}
foreach (const XMLNodeData::BlockLink& l, xml_node_data.block_links) {
Node *a = l.block;
Node *b = xml_node_data.node_ptrs.value(l.link);
Node::Link(a, b);
}
foreach (const XMLNodeData::GroupLink &l, xml_node_data.group_input_links) {
if (Node *input_node = xml_node_data.node_ptrs.value(l.input_node)) {
NodeInput resolved(input_node, l.input_id, l.input_element);
l.group->AddInputPassthrough(resolved);
}
}
for (auto it=xml_node_data.group_output_links.cbegin(); it!=xml_node_data.group_output_links.cend(); it++) {
if (Node *output_node = xml_node_data.node_ptrs.value(it.value())) {
it.key()->SetOutputPassthrough(output_node);
}
}
}
void ProjectSerializer210528::LoadNodeCustom(QXmlStreamReader *reader, Node *node, XMLNodeData &xml_node_data) const
{
// Viewer-based nodes
if (ViewerOutput *viewer = dynamic_cast<ViewerOutput*>(node)) {
Footage *footage = dynamic_cast<Footage*>(node);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("points")) {
LoadTimelinePoints(reader, viewer);
} else if (reader->name() == QStringLiteral("timestamp") && footage) {
footage->set_timestamp(reader->readElementText().toLongLong());
} else {
reader->skipCurrentElement();
}
}
} else if (Track *track = dynamic_cast<Track*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("height")) {
track->SetTrackHeight(reader->readElementText().toDouble());
} else {
reader->skipCurrentElement();
}
}
} else if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthroughs")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthrough")) {
XMLNodeData::GroupLink link;
link.group = group;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
link.input_node = reader->readElementText().toULongLong();
} else if (reader->name() == QStringLiteral("input")) {
link.input_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("element")) {
link.input_element = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.group_input_links.append(link);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("outputpassthrough")) {
xml_node_data.group_output_links.insert(group, reader->readElementText().toULongLong());
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
void ProjectSerializer210528::LoadTimelinePoints(QXmlStreamReader *reader, ViewerOutput *points) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("markers")) {
LoadMarkerList(reader, points->GetMarkers());
} else if (reader->name() == QStringLiteral("workarea")) {
LoadWorkArea(reader, points->GetWorkArea());
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210528::LoadWorkArea(QXmlStreamReader *reader, TimelineWorkArea *workarea) const
{
rational range_in = workarea->in();
rational range_out = workarea->out();
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
workarea->set_enabled(attr.value() != QStringLiteral("0"));
} else if (attr.name() == QStringLiteral("in")) {
range_in = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("out")) {
range_out = rational::fromString(attr.value().toString().toStdString());
}
}
TimeRange loaded_workarea(range_in, range_out);
if (loaded_workarea != workarea->range()) {
workarea->set_range(loaded_workarea);
}
reader->skipCurrentElement();
}
void ProjectSerializer210528::LoadMarkerList(QXmlStreamReader *reader, TimelineMarkerList *markers) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
QString name;
rational in, out;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("name")) {
name = attr.value().toString();
} else 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());
}
}
new TimelineMarker(OLIVE_CONFIG("MarkerColor").toInt(), TimeRange(in, out), name, markers);
}
reader->skipCurrentElement();
}
}
void ProjectSerializer210528::LoadValueHint(Node::ValueHint *hint, QXmlStreamReader *reader) const
{
QVector<NodeValue::Type> types;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("types")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("type")) {
types.append(static_cast<NodeValue::Type>(reader->readElementText().toInt()));
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("index")) {
hint->set_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("tag")) {
hint->set_tag(reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
hint->set_type(types);
}
}
| 26,265
|
C++
|
.cpp
| 663
| 30.589744
| 150
| 0.587607
|
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,008
|
typeserializer.cpp
|
olive-editor_olive/app/node/project/serializer/typeserializer.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 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 "typeserializer.h"
namespace olive {
AudioParams TypeSerializer::LoadAudioParams(QXmlStreamReader *reader)
{
AudioParams a;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("samplerate")) {
a.set_sample_rate(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("channellayout")) {
a.set_channel_layout(reader->readElementText().toULongLong());
} else if (reader->name() == QStringLiteral("format")) {
a.set_format(SampleFormat::from_string(reader->readElementText().toStdString()));
} else if (reader->name() == QStringLiteral("enabled")) {
a.set_enabled(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("streamindex")) {
a.set_stream_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("duration")) {
a.set_duration(reader->readElementText().toLongLong());
} else if (reader->name() == QStringLiteral("timebase")) {
a.set_time_base(rational::fromString(reader->readElementText().toStdString()));
} else {
reader->skipCurrentElement();
}
}
return a;
}
void TypeSerializer::SaveAudioParams(QXmlStreamWriter *writer, const AudioParams &a)
{
writer->writeTextElement(QStringLiteral("samplerate"), QString::number(a.sample_rate()));
writer->writeTextElement(QStringLiteral("channellayout"), QString::number(a.channel_layout()));
writer->writeTextElement(QStringLiteral("format"), QString::fromStdString(a.format().to_string()));
writer->writeTextElement(QStringLiteral("enabled"), QString::number(a.enabled()));
writer->writeTextElement(QStringLiteral("streamindex"), QString::number(a.stream_index()));
writer->writeTextElement(QStringLiteral("duration"), QString::number(a.duration()));
writer->writeTextElement(QStringLiteral("timebase"), QString::fromStdString(a.time_base().toString()));
}
}
| 2,648
|
C++
|
.cpp
| 51
| 48.137255
| 105
| 0.733462
|
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,009
|
serializer210907.cpp
|
olive-editor_olive/app/node/project/serializer/serializer210907.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 "serializer210907.h"
#include "config/config.h"
#include "node/factory.h"
#include "node/group/group.h"
namespace olive {
ProjectSerializer210907::LoadData ProjectSerializer210907::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
XMLNodeData xml_node_data;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("uuid")) {
project->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("nodes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
bool is_root = false;
bool is_cm = false;
bool is_settings = false;
QString id;
{
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
} else if (attr.name() == QStringLiteral("root") && attr.value() == QStringLiteral("1")) {
is_root = true;
} else if (attr.name() == QStringLiteral("cm") && attr.value() == QStringLiteral("1")) {
is_cm = true;
} else if (attr.name() == QStringLiteral("settings") && attr.value() == QStringLiteral("1")) {
is_settings = true;
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
Node* node;
bool handled_elsewhere = false;
if (is_root) {
project->Initialize();
node = project->root();
} else if (is_cm) {
LoadColorManager(reader, project);
handled_elsewhere = true;
} else if (is_settings) {
LoadProjectSettings(reader, project);
handled_elsewhere = true;
} else {
node = NodeFactory::CreateFromID(id);
}
if (!handled_elsewhere) {
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
LoadNode(node, xml_node_data, reader);
node->setParent(project);
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("positions")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("context")) {
quintptr context_ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
context_ptr = attr.value().toULongLong();
break;
}
}
Node *context = xml_node_data.node_ptrs.value(context_ptr);
if (!context) {
qWarning() << "Failed to find pointer for context";
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr node_ptr;
Node::Position node_pos;
if (LoadPosition(reader, &node_ptr, &node_pos)) {
Node *node = xml_node_data.node_ptrs.value(node_ptr);
if (node) {
context->SetNodePositionInContext(node, node_pos);
} else {
qWarning() << "Failed to find pointer for node position";
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
// Skip this
reader->skipCurrentElement();
}
}
// Make connections
PostConnect(xml_node_data);
// Resolve tracks
for (Node *n : project->nodes()) {
n->SetCachesEnabled(true);
if (Track *t = dynamic_cast<Track *>(n)) {
for (int i = 0; i < t->InputArraySize(Track::kBlockInput); i++) {
Block *b = static_cast<Block*>(t->GetConnectedOutput(Track::kBlockInput, i));
if (!b->track()) {
t->AppendBlock(b);
}
}
}
}
return LoadData();
}
void ProjectSerializer210907::LoadNode(Node *node, XMLNodeData &xml_node_data, QXmlStreamReader *reader) const
{
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("input")) {
LoadInput(node, reader, xml_node_data);
} else if (reader->name() == QStringLiteral("ptr")) {
xml_node_data.node_ptrs.insert(reader->readElementText().toULongLong(), node);
} else if (reader->name() == QStringLiteral("label")) {
node->SetLabel(reader->readElementText());
} else if (reader->name() == QStringLiteral("color")) {
node->SetOverrideColor(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("links")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("link")) {
xml_node_data.block_links.append({node, reader->readElementText().toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("custom")) {
LoadNodeCustom(reader, node, xml_node_data);
} else if (reader->name() == QStringLiteral("connections")) {
// Load connections
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("connection")) {
QString param_id;
int ele = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("element")) {
ele = attr.value().toInt();
} else if (attr.name() == QStringLiteral("input")) {
param_id = attr.value().toString();
}
}
QString output_node_id;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("output")) {
output_node_id = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.desired_connections.append({NodeInput(node, param_id, ele), output_node_id.toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("hints")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("hint")) {
QString input;
int element = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
input = attr.value().toString();
} else if (attr.name() == QStringLiteral("element")) {
element = attr.value().toInt();
}
}
Node::ValueHint vh;
LoadValueHint(&vh, reader);
node->SetValueHintForInput(input, vh, element);
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
node->LoadFinishedEvent();
}
void ProjectSerializer210907::LoadColorManager(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("config") || id == QStringLiteral("default_input") || id == QStringLiteral("reference_space")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("default_input")) {
// Default color space
// NOTE: Stupidly, we saved these as integers which means we can't add anything to the OCIO
// config. So we must convert back to string here.
static const QStringList list = {
QStringLiteral("Linear"),
QStringLiteral("CIE-XYZ D65"),
QStringLiteral("Filmic Log Encoding"),
QStringLiteral("sRGB OETF"),
QStringLiteral("Apple DCI-P3 D65"),
QStringLiteral("AppleP3 sRGB OETF"),
QStringLiteral("BT.1886 EOTF"),
QStringLiteral("AppleP3 Filmic Log Encoding"),
QStringLiteral("BT.1886 Filmic Log Encoding"),
QStringLiteral("Fuji F-Log OETF"),
QStringLiteral("Fuji F-Log F-Gamut"),
QStringLiteral("Panasonic V-Log V-Gamut"),
QStringLiteral("Arri Wide Gamut / LogC EI 800"),
QStringLiteral("Arri Wide Gamut / LogC EI 400"),
QStringLiteral("Blackmagic Film Wide Gamut (Gen 5)"),
QStringLiteral("Rec.709 OETF"),
QStringLiteral("Non-Colour Data")
};
int num_value = value.toInt();
value = list.at(num_value);
project->SetDefaultInputColorSpace(value);
} else if (id == QStringLiteral("reference_space")) {
// Reference space
if (value == QStringLiteral("1")) {
value = OCIO::ROLE_COMPOSITING_LOG;
} else {
value = OCIO::ROLE_SCENE_LINEAR;
}
project->SetColorReferenceSpace(value);
} else {
// Config filename
project->SetColorConfigFilename(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210907::LoadProjectSettings(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("cache_setting") || id == QStringLiteral("cache_path")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("cache_setting")) {
project->SetCacheLocationSetting(static_cast<Project::CacheSetting>(value.toInt()));
} else {
project->SetCustomCachePath(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210907::LoadInput(Node *node, QXmlStreamReader *reader, XMLNodeData &xml_node_data) const
{
QString param_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
param_id = attr.value().toString();
break;
}
}
if (param_id.isEmpty()) {
qWarning() << "Failed to load parameter with missing ID";
reader->skipCurrentElement();
return;
}
if (!node->HasInputWithID(param_id)) {
qWarning() << "Failed to load parameter that didn't exist:" << param_id;
reader->skipCurrentElement();
return;
}
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("primary")) {
// Load primary immediate
LoadImmediate(reader, node, param_id, -1, xml_node_data);
} else if (reader->name() == QStringLiteral("subelements")) {
// Load subelements
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("count")) {
node->InputArrayResize(param_id, attr.value().toInt());
}
}
int element_counter = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
LoadImmediate(reader, node, param_id, element_counter, xml_node_data);
element_counter++;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210907::LoadImmediate(QXmlStreamReader *reader, Node *node, const QString& input, int element, XMLNodeData &xml_node_data) const
{
Q_UNUSED(xml_node_data)
NodeValue::Type data_type = node->GetInputDataType(input);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
// Load standard value
int val_index = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
QVariant value_on_track;
if (data_type == NodeValue::kVideoParams) {
VideoParams vp;
vp.Load(reader);
value_on_track = QVariant::fromValue(vp);
} else if (data_type == NodeValue::kAudioParams) {
AudioParams ap = TypeSerializer::LoadAudioParams(reader);
value_on_track = QVariant::fromValue(ap);
} else {
QString value_text = reader->readElementText();
if (!value_text.isEmpty()) {
value_on_track = NodeValue::StringToValue(data_type, value_text, true);
}
}
node->SetSplitStandardValueOnTrack(input, val_index, value_on_track, element);
val_index++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframing") && node->IsInputKeyframable(input)) {
node->SetInputIsKeyframing(input, reader->readElementText().toInt(), element);
} else if (reader->name() == QStringLiteral("keyframes")) {
int track = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("key")) {
QString key_input;
rational key_time;
NodeKeyframe::Type key_type = NodeKeyframe::kLinear;
QVariant key_value;
QPointF key_in_handle;
QPointF key_out_handle;
XMLAttributeLoop(reader, attr) {
if (IsCancelled()) {
return;
}
if (attr.name() == QStringLiteral("input")) {
key_input = attr.value().toString();
} else if (attr.name() == QStringLiteral("time")) {
key_time = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("type")) {
key_type = static_cast<NodeKeyframe::Type>(attr.value().toInt());
} else if (attr.name() == QStringLiteral("inhandlex")) {
key_in_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("inhandley")) {
key_in_handle.setY(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandlex")) {
key_out_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandley")) {
key_out_handle.setY(attr.value().toDouble());
}
}
key_value = NodeValue::StringToValue(data_type, reader->readElementText(), true);
NodeKeyframe* key = new NodeKeyframe(key_time, key_value, key_type, track, element, key_input, node);
key->set_bezier_control_in(key_in_handle);
key->set_bezier_control_out(key_out_handle);
} else {
reader->skipCurrentElement();
}
}
track++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("csinput")) {
node->SetInputProperty(input, QStringLiteral("col_input"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csdisplay")) {
node->SetInputProperty(input, QStringLiteral("col_display"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csview")) {
node->SetInputProperty(input, QStringLiteral("col_view"), reader->readElementText());
} else if (reader->name() == QStringLiteral("cslook")) {
node->SetInputProperty(input, QStringLiteral("col_look"), reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
}
bool ProjectSerializer210907::LoadPosition(QXmlStreamReader *reader, quintptr *node_ptr, Node::Position *pos) const
{
bool got_node_ptr = false;
bool got_pos_x = false;
bool got_pos_y = false;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
*node_ptr = attr.value().toULongLong();
got_node_ptr = true;
break;
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("x")) {
pos->position.setX(reader->readElementText().toDouble());
got_pos_x = true;
} else if (reader->name() == QStringLiteral("y")) {
pos->position.setY(reader->readElementText().toDouble());
got_pos_y = true;
} else if (reader->name() == QStringLiteral("expanded")) {
pos->expanded = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
return got_node_ptr && got_pos_x && got_pos_y;
}
void ProjectSerializer210907::PostConnect(const XMLNodeData &xml_node_data) const
{
foreach (const XMLNodeData::SerializedConnection& con, xml_node_data.desired_connections) {
if (Node *out = xml_node_data.node_ptrs.value(con.output_node)) {
Node::ConnectEdge(out, con.input);
}
}
foreach (const XMLNodeData::BlockLink& l, xml_node_data.block_links) {
Node *a = l.block;
Node *b = xml_node_data.node_ptrs.value(l.link);
Node::Link(a, b);
}
foreach (const XMLNodeData::GroupLink &l, xml_node_data.group_input_links) {
if (Node *input_node = xml_node_data.node_ptrs.value(l.input_node)) {
NodeInput resolved(input_node, l.input_id, l.input_element);
l.group->AddInputPassthrough(resolved);
}
}
for (auto it=xml_node_data.group_output_links.cbegin(); it!=xml_node_data.group_output_links.cend(); it++) {
if (Node *output_node = xml_node_data.node_ptrs.value(it.value())) {
it.key()->SetOutputPassthrough(output_node);
}
}
}
void ProjectSerializer210907::LoadNodeCustom(QXmlStreamReader *reader, Node *node, XMLNodeData &xml_node_data) const
{
// Viewer-based nodes
if (ViewerOutput *viewer = dynamic_cast<ViewerOutput*>(node)) {
Footage *footage = dynamic_cast<Footage*>(node);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("points")) {
LoadTimelinePoints(reader, viewer);
} else if (reader->name() == QStringLiteral("timestamp") && footage) {
footage->set_timestamp(reader->readElementText().toLongLong());
} else {
reader->skipCurrentElement();
}
}
} else if (Track *track = dynamic_cast<Track*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("height")) {
track->SetTrackHeight(reader->readElementText().toDouble());
} else {
reader->skipCurrentElement();
}
}
} else if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthroughs")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthrough")) {
XMLNodeData::GroupLink link;
link.group = group;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
link.input_node = reader->readElementText().toULongLong();
} else if (reader->name() == QStringLiteral("input")) {
link.input_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("element")) {
link.input_element = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.group_input_links.append(link);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("outputpassthrough")) {
xml_node_data.group_output_links.insert(group, reader->readElementText().toULongLong());
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
void ProjectSerializer210907::LoadTimelinePoints(QXmlStreamReader *reader, ViewerOutput *points) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("markers")) {
LoadMarkerList(reader, points->GetMarkers());
} else if (reader->name() == QStringLiteral("workarea")) {
LoadWorkArea(reader, points->GetWorkArea());
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer210907::LoadWorkArea(QXmlStreamReader *reader, TimelineWorkArea *workarea) const
{
rational range_in = workarea->in();
rational range_out = workarea->out();
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
workarea->set_enabled(attr.value() != QStringLiteral("0"));
} else if (attr.name() == QStringLiteral("in")) {
range_in = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("out")) {
range_out = rational::fromString(attr.value().toString().toStdString());
}
}
TimeRange loaded_workarea(range_in, range_out);
if (loaded_workarea != workarea->range()) {
workarea->set_range(loaded_workarea);
}
reader->skipCurrentElement();
}
void ProjectSerializer210907::LoadMarkerList(QXmlStreamReader *reader, TimelineMarkerList *markers) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
QString name;
rational in, out;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("name")) {
name = attr.value().toString();
} else 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());
}
}
new TimelineMarker(OLIVE_CONFIG("MarkerColor").toInt(), TimeRange(in, out), name, markers);
}
reader->skipCurrentElement();
}
}
void ProjectSerializer210907::LoadValueHint(Node::ValueHint *hint, QXmlStreamReader *reader) const
{
QVector<NodeValue::Type> types;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("types")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("type")) {
types.append(static_cast<NodeValue::Type>(reader->readElementText().toInt()));
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("index")) {
hint->set_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("tag")) {
hint->set_tag(reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
hint->set_type(types);
}
}
| 25,877
|
C++
|
.cpp
| 657
| 30.372907
| 150
| 0.586703
|
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,010
|
serializer230220.cpp
|
olive-editor_olive/app/node/project/serializer/serializer230220.cpp
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2023 Olive Studios LLC
This program is free software: you can 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 "serializer230220.h"
#include "config/config.h"
#include "node/factory.h"
#include "node/group/group.h"
#include "node/serializeddata.h"
namespace olive {
ProjectSerializer230220::LoadData ProjectSerializer230220::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
QMap<quintptr, QMap<QString, QString> > properties;
QMap<quintptr, QMap<quintptr, Node::Position> > positions;
LoadData load_data;
SerializedData project_data;
switch (load_type) {
case kProject:
{
if (reader->name() == QStringLiteral("project")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("project")) {
project_data = project->Load(reader);
} else if (reader->name() == QStringLiteral("layout")) {
load_data.layout = MainWindowLayoutInfo::fromXml(reader, project_data.node_ptrs);
} else {
reader->skipCurrentElement();
}
}
PostConnect(project->nodes(), &project_data);
} else {
reader->skipCurrentElement();
}
break;
}
case kOnlyMarkers:
{
if (reader->name() == QStringLiteral("markers")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
TimelineMarker *marker = new TimelineMarker();
marker->load(reader);
load_data.markers.push_back(marker);
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
break;
}
case kOnlyKeyframes:
{
if (reader->name() == QStringLiteral("keyframes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
QString node_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
node_id = attr.value().toString();
break;
}
}
Node *n = nullptr;
if (!node_id.isEmpty()) {
n = NodeFactory::CreateFromID(node_id);
}
if (!n) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString input_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
input_id = attr.value().toString();
break;
}
}
if (input_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
QString element_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
element_id = attr.value().toString();
break;
}
}
if (element_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
QString track_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
track_id = attr.value().toString();
break;
}
}
if (track_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
NodeKeyframe *key = new NodeKeyframe();
key->set_input(input_id);
key->set_element(element_id.toInt());
key->set_track(track_id.toInt());
key->load(reader, n->GetInputDataType(input_id));
load_data.keyframes[node_id].append(key);
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
delete n;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
break;
}
case kOnlyClips:
case kOnlyNodes:
{
if ((load_type == kOnlyNodes && reader->name() == QStringLiteral("nodes")) || (load_type == kOnlyClips && reader->name() == QStringLiteral("timeline"))) {
QMap<quintptr, Node*> skipped_items;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
QString id;
quintptr ptr = 0;
QVector<quintptr> items;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
} else if (attr.name() == QStringLiteral("ptr")) {
ptr = attr.value().toULongLong();
} else if (attr.name() == QStringLiteral("items")) {
QVector<QStringRef> l = attr.value().split(',');
items.reserve(l.size());
for (const QStringRef &s : l) {
items.append(s.toULongLong());
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
bool dependency_of_item = false;
if (project && !items.empty()) {
for (quintptr p : items) {
if (project->nodes().contains(reinterpret_cast<Node*>(p))) {
dependency_of_item = true;
break;
}
}
}
if (dependency_of_item) {
reader->skipCurrentElement();
} else {
Node* node = NodeFactory::CreateFromID(id);
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
if (project && node->IsItem() && ptr) {
// If we're pasting an object into the same project, we should re-use the item
// rather than duplicate.
Node *existing = reinterpret_cast<Node *>(ptr);
if (project->nodes().contains(existing)) {
// Connect this
skipped_items.insert(ptr, existing);
// Don't continue loading this
delete node;
node = nullptr;
// Skip element
reader->skipCurrentElement();
}
}
if (node) {
// Disable cache while node is being loaded (we'll re-enable it later)
node->SetCachesEnabled(false);
node->Load(reader, &project_data);
load_data.nodes.append(node);
}
}
}
}
} else if (reader->name() == QStringLiteral("properties")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
ptr = attr.value().toULongLong();
// Only attribute we're looking for right now
break;
}
}
if (ptr) {
QMap<QString, QString> properties_for_node;
while (XMLReadNextStartElement(reader)) {
properties_for_node.insert(reader->name().toString(), reader->readElementText());
}
properties.insert(ptr, properties_for_node);
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (!skipped_items.empty()) {
for (auto it = project_data.desired_connections.begin(); it != project_data.desired_connections.end(); ) {
const SerializedData::SerializedConnection &sc = *it;
if (Node *si = skipped_items.value(sc.output_node)) {
// Convert this to a promised connection
Node::OutputConnection oc = {si, sc.input};
load_data.promised_connections.push_back(oc);
it = project_data.desired_connections.erase(it);
} else {
it++;
}
}
}
// Resolve serialized properties (if any)
for (auto it=properties.cbegin(); it!=properties.cend(); it++) {
Node *node = project_data.node_ptrs.value(it.key());
if (node) {
load_data.properties.insert(node, it.value());
}
}
PostConnect(load_data.nodes, &project_data);
} else {
reader->skipCurrentElement();
}
break;
}
}
return load_data;
}
void WriteNodeMap(QXmlStreamWriter *writer, Node *node, const QVector<Node*> &nodes)
{
writer->writeStartElement(QStringLiteral("node"));
writer->writeAttribute(QStringLiteral("ptr"), QString::number(reinterpret_cast<quintptr>(node)));
for (auto oc : node->output_connections()) {
if (nodes.contains(oc.second.node())) {
WriteNodeMap(writer, oc.second.node(), nodes);
}
}
writer->writeEndElement();
}
void ProjectSerializer230220::Save(QXmlStreamWriter *writer, const SaveData &data, void *reserved) const
{
if (!data.GetOnlySerializeMarkers().empty()) {
writer->writeStartElement(QStringLiteral("markers"));
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
for (auto it=data.GetOnlySerializeMarkers().cbegin(); it!=data.GetOnlySerializeMarkers().cend(); it++) {
TimelineMarker *marker = *it;
writer->writeStartElement(QStringLiteral("marker"));
marker->save(writer);
writer->writeEndElement(); // marker
}
writer->writeEndElement(); // markers
} else if (!data.GetOnlySerializeKeyframes().empty()) {
writer->writeStartElement(QStringLiteral("keyframes"));
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
// Organize keyframes into node+input
QHash<QString, QHash<QString, QMap<int, QMap<int, QVector<NodeKeyframe*> > > > > organized;
for (auto it=data.GetOnlySerializeKeyframes().cbegin(); it!=data.GetOnlySerializeKeyframes().cend(); it++) {
NodeKeyframe *key = *it;
organized[key->parent()->id()][key->input()][key->element()][key->track()].append(key);
}
for (auto it=organized.cbegin(); it!=organized.cend(); it++) {
writer->writeStartElement(QStringLiteral("node"));
writer->writeAttribute(QStringLiteral("id"), it.key());
for (auto jt=it.value().cbegin(); jt!=it.value().cend(); jt++) {
writer->writeStartElement(QStringLiteral("input"));
writer->writeAttribute(QStringLiteral("id"), jt.key());
for (auto kt=jt.value().cbegin(); kt!=jt.value().cend(); kt++) {
writer->writeStartElement(QStringLiteral("element"));
writer->writeAttribute(QStringLiteral("id"), QString::number(kt.key()));
for (auto lt=kt.value().cbegin(); lt!=kt.value().cend(); lt++) {
const QVector<NodeKeyframe *> &keys = lt.value();
writer->writeStartElement(QStringLiteral("track"));
writer->writeAttribute(QStringLiteral("id"), QString::number(lt.key()));
for (NodeKeyframe *key : keys) {
writer->writeStartElement(QStringLiteral("key"));
key->save(writer, key->parent()->GetInputDataType(key->input()));
writer->writeEndElement(); // key
}
writer->writeEndElement(); // track
}
writer->writeEndElement(); // element
}
writer->writeEndElement(); // input
}
writer->writeEndElement(); // node;
}
writer->writeEndElement(); // keyframes
} else if (!data.GetOnlySerializeNodes().empty()) {
if (data.type() == kOnlyClips) {
writer->writeStartElement(QStringLiteral("timeline"));
} else {
writer->writeStartElement(QStringLiteral("nodes"));
}
writer->writeAttribute(QStringLiteral("version"), QString::number(1));
for (Node *n : data.GetOnlySerializeNodes()) {
writer->writeStartElement(QStringLiteral("node"));
QStringList item_list;
for (Node *i : data.GetOnlySerializeNodes()) {
if (i->IsItem() && i->InputsFrom(n, true)) {
item_list.append(QString::number(reinterpret_cast<quintptr>(i)));
}
}
if (!item_list.empty()) {
writer->writeAttribute(QStringLiteral("items"), item_list.join(','));
}
n->Save(writer);
writer->writeEndElement(); // node
}
if (!data.GetProperties().empty()) {
writer->writeStartElement(QStringLiteral("properties"));
for (auto it=data.GetProperties().cbegin(); it!=data.GetProperties().cend(); it++) {
writer->writeStartElement(QStringLiteral("node"));
writer->writeAttribute(QStringLiteral("ptr"), QString::number(reinterpret_cast<quintptr>(it.key())));
for (auto jt=it.value().cbegin(); jt!=it.value().cend(); jt++) {
writer->writeTextElement(jt.key(), jt.value());
}
writer->writeEndElement(); // node
}
writer->writeEndElement(); // properties
}
writer->writeEndElement(); // nodes
} else if (Project *project = data.GetProject()) {
writer->writeStartElement(QStringLiteral("project"));
writer->writeStartElement(QStringLiteral("project"));
project->Save(writer);
writer->writeEndElement(); // project
writer->writeStartElement(QStringLiteral("layout"));
data.GetLayout().toXml(writer);
writer->writeEndElement(); // layout
writer->writeEndElement(); // project
} else {
qCritical() << "ProjectSerializer provided nothing to save";
}
}
void ProjectSerializer230220::PostConnect(const QVector<Node *> &nodes, SerializedData *project_data) const
{
foreach (const SerializedData::SerializedConnection& con, project_data->desired_connections) {
if (Node *out = project_data->node_ptrs.value(con.output_node)) {
Node::ConnectEdge(out, con.input);
}
}
foreach (const SerializedData::BlockLink& l, project_data->block_links) {
Node *a = l.block;
Node *b = project_data->node_ptrs.value(l.link);
Node::Link(a, b);
}
for (auto it = nodes.cbegin(); it != nodes.cend(); it++){
Node *n = *it;
n->PostLoadEvent(project_data);
n->SetCachesEnabled(true);
}
}
}
| 16,482
|
C++
|
.cpp
| 402
| 29.5
| 158
| 0.547472
|
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,011
|
serializer.cpp
|
olive-editor_olive/app/node/project/serializer/serializer.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 "serializer.h"
#include <QApplication>
#include <QFile>
#include <QXmlStreamReader>
#include "common/xmlutils.h"
#include "core.h"
#include "node/group/group.h"
#include "serializer190219.h"
#include "serializer210528.h"
#include "serializer210907.h"
#include "serializer211228.h"
#include "serializer220403.h"
#include "serializer230220.h"
namespace olive {
QVector<ProjectSerializer*> ProjectSerializer::instances_;
void ProjectSerializer::Initialize()
{
// Make sure to order these from oldest to newest
// FIXME: Implement this - yes it's a 0.1 project loader
//instances_.append(new ProjectSerializer190219);
instances_.append(new ProjectSerializer210528);
instances_.append(new ProjectSerializer210907);
instances_.append(new ProjectSerializer211228);
instances_.append(new ProjectSerializer220403);
instances_.append(new ProjectSerializer230220);
}
void ProjectSerializer::Destroy()
{
qDeleteAll(instances_);
instances_.clear();
}
ProjectSerializer::Result ProjectSerializer::Load(Project *project, const QString &filename, LoadType load_type)
{
QFile project_file(filename);
if (project_file.open(QFile::ReadOnly)) {
// Some project files are compressed, marked with "OVEC" at the beginning of the file. Check for
// that signature now.
std::unique_ptr<QXmlStreamReader> reader;
if (CheckCompressedID(&project_file)) {
// File is compressed, decompress into memory
QByteArray b;
b = qUncompress(project_file.readAll());
reader.reset(new QXmlStreamReader(b));
} else {
project_file.seek(0);
reader.reset(new QXmlStreamReader(&project_file));
}
Result inner_result = Load(project, reader.get(), load_type);
project_file.close();
if (inner_result.code() != kSuccess) {
return inner_result;
}
if (reader->hasError()) {
Result r(kXmlError);
r.SetDetails(reader->errorString());
return r;
} else {
return inner_result;
}
} else {
return kFileError;
}
}
ProjectSerializer::Result ProjectSerializer::Load(Project *project, QXmlStreamReader *reader, LoadType load_type)
{
// Determine project version
uint version = 0;
Result res = kUnknownVersion;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("olive")
|| reader->name() == QStringLiteral("project")) { // 0.1 projects only
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("version")) { // 230220+ projects
version = attr.value().toUInt();
} else if (reader->name() == QStringLiteral("url")) { // 230220+ projects
project->SetSavedURL(attr.value().toString());
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("version")) { // projects <= 220403
version = reader->readElementText().toUInt();
} else if (reader->name() == QStringLiteral("url")) { // projects <= 220403
if (project) {
project->SetSavedURL(reader->readElementText());
} else {
reader->skipCurrentElement();
}
} else {
// Handle any other value with the serializer
res = LoadWithSerializerVersion(version, project, reader, load_type);
}
}
} else {
reader->skipCurrentElement();
}
}
return res;
}
ProjectSerializer::Result ProjectSerializer::Paste(LoadType load_type, Project *project)
{
QString clipboard = Core::PasteStringFromClipboard();
if (clipboard.isEmpty()) {
return kNoData;
}
QXmlStreamReader reader(clipboard);
return ProjectSerializer::Load(project, &reader, load_type);
}
ProjectSerializer::Result ProjectSerializer::Save(const SaveData &data, bool compress)
{
QString temp_save = FileFunctions::GetSafeTemporaryFilename(data.GetFilename());
QFile project_file(temp_save);
if (project_file.open(QFile::WriteOnly)) {
QByteArray b;
QXmlStreamWriter writer(&b);
Result inner_result = Save(&writer, data);
if (writer.hasError()) {
Result r(kXmlError);
return r;
}
if (compress) {
project_file.write("OVEC");
project_file.write(qCompress(b));
} else {
project_file.write(b);
}
project_file.close();
if (inner_result != kSuccess) {
return inner_result;
}
// Save was successful, we can now rewrite the original file
if (FileFunctions::RenameFileAllowOverwrite(temp_save, data.GetFilename())) {
return kSuccess;
} else {
Result r(kOverwriteError);
r.SetDetails(temp_save);
return r;
}
} else {
Result r(kFileError);
r.SetDetails(temp_save);
return r;
}
}
ProjectSerializer::Result ProjectSerializer::Save(QXmlStreamWriter *writer, const SaveData &data)
{
writer->setAutoFormatting(true);
writer->writeStartDocument();
writer->writeStartElement("olive");
// By default, save as last serializer which, assuming the instances are ordered correctly,
// will be the newest file format. But we may allow saving as older versions later on.
ProjectSerializer *serializer = instances_.last();
// Version is stored in YYMMDD from whenever the project format was last changed
// Allows easy integer math for checking project versions.
writer->writeAttribute(QStringLiteral("version"), QString::number(serializer->Version()));
if (!data.GetFilename().isEmpty()) {
writer->writeAttribute("url", data.GetFilename());
}
serializer->Save(writer, data, nullptr);
writer->writeEndElement(); // olive
writer->writeEndDocument();
if (writer->hasError()) {
return kXmlError;
}
return kSuccess;
}
ProjectSerializer::Result ProjectSerializer::Copy(const SaveData &data)
{
QString copy_str;
QXmlStreamWriter writer(©_str);
ProjectSerializer::Result res = ProjectSerializer::Save(&writer, data);
if (res == kSuccess) {
Core::CopyStringToClipboard(copy_str);
}
return res;
}
bool ProjectSerializer::CheckCompressedID(QFile *file)
{
QByteArray b = file->read(4);
return !memcmp(b.data(), "OVEC", 4);
}
bool ProjectSerializer::IsCancelled() const
{
return false;
}
ProjectSerializer::Result ProjectSerializer::LoadWithSerializerVersion(uint version, Project *project, QXmlStreamReader *reader, LoadType load_type)
{
// Failed to find version in file
if (version == 0) {
return kUnknownVersion;
}
// We should now have the version, if we have a serializer for it, use it to load the project
ProjectSerializer *serializer = nullptr;
foreach (ProjectSerializer *s, instances_) {
if (version == s->Version()) {
serializer = s;
break;
} else if (version < s->Version()) {
// Assuming the instance list is in order, if the project version is less than any version
// we find, we must not support it anymore
return kProjectTooOld;
}
}
if (serializer) {
LoadData ld = serializer->Load(project, reader, load_type, nullptr);
Result r(kSuccess);
if (reader->hasError()) {
r = Result(kXmlError);
r.SetDetails(QCoreApplication::translate("Serializer", "%1 on line %2").arg(reader->errorString(), QString::number(reader->lineNumber())));
}
r.SetLoadData(ld);
return r;
} else {
// Reached the end of the list with no serializer, assume too new
return kProjectTooNew;
}
}
void ProjectSerializer::SaveData::SetOnlySerializeNodesAndResolveGroups(QVector<Node *> nodes)
{
// For any groups, add children
for (int i=0; i<nodes.size(); i++) {
// If this is a group, add the child nodes too
if (NodeGroup *g = dynamic_cast<NodeGroup*>(nodes.at(i))) {
for (auto it=g->GetContextPositions().cbegin(); it!=g->GetContextPositions().cend(); it++) {
if (!nodes.contains(it.key())) {
nodes.append(it.key());
}
}
}
}
SetOnlySerializeNodes(nodes);
}
}
| 8,638
|
C++
|
.cpp
| 246
| 30.678862
| 148
| 0.702317
|
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,012
|
serializer220403.cpp
|
olive-editor_olive/app/node/project/serializer/serializer220403.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 "serializer220403.h"
#include "config/config.h"
#include "node/factory.h"
#include "node/group/group.h"
namespace olive {
ProjectSerializer220403::LoadData ProjectSerializer220403::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
QMap<quintptr, QMap<QString, QString> > properties;
QMap<quintptr, QMap<quintptr, Node::Position> > positions;
XMLNodeData xml_node_data;
LoadData load_data;
if ((load_type == kProject && reader->name() == QStringLiteral("project"))
|| ((load_type == kOnlyNodes && reader->name() == QStringLiteral("nodes")) || (load_type == kOnlyClips && reader->name() == QStringLiteral("timeline")))
|| (load_type == kOnlyKeyframes && reader->name() == QStringLiteral("keyframes"))
|| (load_type == kOnlyMarkers && reader->name() == QStringLiteral("markers"))) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("layout")) {
// Since the main window's functions have to occur in the GUI thread (and we're likely
// loading in a secondary thread), we load all necessary data into a separate struct so we
// can continue loading and queue it with the main window so it can handle the data
// appropriately in its own thread.
load_data.layout = MainWindowLayoutInfo::fromXml(reader, xml_node_data.node_ptrs);
} else if (reader->name() == QStringLiteral("uuid")) {
if (project) {
project->SetUuid(QUuid::fromString(reader->readElementText()));
} else {
reader->skipCurrentElement();
}
} else if (reader->name() == QStringLiteral("nodes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
bool is_root = false;
bool is_cm = false;
bool is_settings = false;
QString id;
{
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
} else if (attr.name() == QStringLiteral("root") && attr.value() == QStringLiteral("1")) {
is_root = true;
} else if (attr.name() == QStringLiteral("cm") && attr.value() == QStringLiteral("1")) {
is_cm = true;
} else if (attr.name() == QStringLiteral("settings") && attr.value() == QStringLiteral("1")) {
is_settings = true;
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
Node* node;
bool handled_elsewhere = false;
if (is_root) {
project->Initialize();
node = project->root();
} else if (is_cm) {
LoadColorManager(reader, project);
handled_elsewhere = true;
} else if (is_settings) {
LoadProjectSettings(reader, project);
handled_elsewhere = true;
} else {
node = NodeFactory::CreateFromID(id);
}
if (!handled_elsewhere) {
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
LoadNode(node, xml_node_data, reader);
if (project) {
node->setParent(project);
} else {
load_data.nodes.append(node);
}
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
QString node_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
node_id = attr.value().toString();
break;
}
}
Node *n = nullptr;
if (!node_id.isEmpty()) {
n = NodeFactory::CreateFromID(node_id);
}
if (!n) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString input_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
input_id = attr.value().toString();
break;
}
}
if (input_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
QString element_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
element_id = attr.value().toString();
break;
}
}
if (element_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
QString track_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
track_id = attr.value().toString();
break;
}
}
if (track_id.isEmpty()) {
reader->skipCurrentElement();
} else {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
NodeKeyframe *key = new NodeKeyframe();
key->set_input(input_id);
key->set_element(element_id.toInt());
key->set_track(track_id.toInt());
LoadKeyframe(reader, key, n->GetInputDataType(input_id));
load_data.keyframes[node_id].append(key);
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
} else {
reader->skipCurrentElement();
}
}
}
delete n;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("markers")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
TimelineMarker *marker = new TimelineMarker();
LoadMarker(reader, marker);
load_data.markers.push_back(marker);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("positions")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("context")) {
quintptr context_ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
context_ptr = attr.value().toULongLong();
break;
}
}
if (context_ptr) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr node_ptr;
Node::Position node_pos;
if (LoadPosition(reader, &node_ptr, &node_pos)) {
if (node_ptr) {
positions[context_ptr].insert(node_ptr, node_pos);
} else {
qWarning() << "Failed to find pointer for node position";
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
qWarning() << "Attempted to load context with no pointer";
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("properties")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
ptr = attr.value().toULongLong();
// Only attribute we're looking for right now
break;
}
}
if (ptr) {
QMap<QString, QString> properties_for_node;
while (XMLReadNextStartElement(reader)) {
properties_for_node.insert(reader->name().toString(), reader->readElementText());
}
properties.insert(ptr, properties_for_node);
}
} else {
reader->skipCurrentElement();
}
}
} else {
// Skip this
reader->skipCurrentElement();
}
}
}
// Resolve positions
for (auto it=positions.cbegin(); it!=positions.cend(); it++) {
Node *ctx = xml_node_data.node_ptrs.value(it.key());
if (ctx) {
for (auto jt=it.value().cbegin(); jt!=it.value().cend(); jt++) {
Node *n = xml_node_data.node_ptrs.value(jt.key());
if (n) {
ctx->SetNodePositionInContext(n, jt.value());
}
}
}
}
// Make connections
PostConnect(xml_node_data);
// Resolve serialized properties (if any)
for (auto it=properties.cbegin(); it!=properties.cend(); it++) {
Node *node = xml_node_data.node_ptrs.value(it.key());
if (node) {
load_data.properties.insert(node, it.value());
}
}
// Re-enable caches and resolve tracks
const QVector<Node*> &nodes = project ? project->nodes() : load_data.nodes;
for (Node *n : nodes) {
n->SetCachesEnabled(true);
if (Track *t = dynamic_cast<Track *>(n)) {
for (int i = 0; i < t->InputArraySize(Track::kBlockInput); i++) {
Block *b = static_cast<Block*>(t->GetConnectedOutput(Track::kBlockInput, i));
if (!b->track()) {
t->AppendBlock(b);
}
}
}
// Clear duplicate label (to facilitate #2147)
if (ClipBlock *c = dynamic_cast<ClipBlock*>(n)) {
if (c->connected_viewer() && c->GetLabel() == c->connected_viewer()->GetLabel()) {
c->SetLabel(QString());
}
}
}
return load_data;
}
void ProjectSerializer220403::LoadNode(Node *node, XMLNodeData &xml_node_data, QXmlStreamReader *reader) const
{
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("input")) {
LoadInput(node, reader, xml_node_data);
} else if (reader->name() == QStringLiteral("ptr")) {
quintptr ptr = reader->readElementText().toULongLong();
xml_node_data.node_ptrs.insert(ptr, node);
} else if (reader->name() == QStringLiteral("label")) {
node->SetLabel(reader->readElementText());
} else if (reader->name() == QStringLiteral("uuid")) {
xml_node_data.node_uuids.insert(node, QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("color")) {
node->SetOverrideColor(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("links")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("link")) {
xml_node_data.block_links.append({node, reader->readElementText().toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("custom")) {
LoadNodeCustom(reader, node, xml_node_data);
} else if (reader->name() == QStringLiteral("connections")) {
// Load connections
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("connection")) {
QString param_id;
int ele = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("element")) {
ele = attr.value().toInt();
} else if (attr.name() == QStringLiteral("input")) {
param_id = attr.value().toString();
}
}
QString output_node_id;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("output")) {
output_node_id = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.desired_connections.append({NodeInput(node, param_id, ele), output_node_id.toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("hints")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("hint")) {
QString input;
int element = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
input = attr.value().toString();
} else if (attr.name() == QStringLiteral("element")) {
element = attr.value().toInt();
}
}
Node::ValueHint vh;
LoadValueHint(&vh, reader);
node->SetValueHintForInput(input, vh, element);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("caches")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("audio")) {
node->audio_playback_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("video")) {
node->video_frame_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("thumb")) {
node->thumbnail_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("waveform")) {
node->waveform_cache()->SetUuid(QUuid::fromString(reader->readElementText()));
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
node->LoadFinishedEvent();
}
void ProjectSerializer220403::LoadColorManager(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("config") || id == QStringLiteral("default_input") || id == QStringLiteral("reference_space")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("default_input")) {
// Default color space
// NOTE: Stupidly, we saved these as integers which means we can't add anything to the OCIO
// config. So we must convert back to string here.
static const QStringList list = {
QStringLiteral("Linear"),
QStringLiteral("Filmic Log Encoding"),
QStringLiteral("sRGB OETF"),
QStringLiteral("Apple DCI-P3 D65"),
QStringLiteral("AppleP3 sRGB OETF"),
QStringLiteral("BT.1886 EOTF"),
QStringLiteral("AppleP3 Filmic Log Encoding"),
QStringLiteral("BT.1886 Filmic Log Encoding"),
QStringLiteral("Fuji F-Log OETF"),
QStringLiteral("Fuji F-Log F-Gamut"),
QStringLiteral("Panasonic V-Log V-Gamut"),
QStringLiteral("Arri Wide Gamut / LogC EI 800"),
QStringLiteral("Arri Wide Gamut / LogC EI 400"),
QStringLiteral("Blackmagic Film Wide Gamut (Gen 5)"),
QStringLiteral("Rec.709 OETF"),
QStringLiteral("Non-Colour Data")
};
int num_value = value.toInt();
value = list.at(num_value);
project->SetDefaultInputColorSpace(value);
} else if (id == QStringLiteral("reference_space")) {
// Reference space
if (value == QStringLiteral("1")) {
value = OCIO::ROLE_COMPOSITING_LOG;
} else {
value = OCIO::ROLE_SCENE_LINEAR;
}
project->SetColorReferenceSpace(value);
} else {
// Config filename
project->SetColorConfigFilename(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadProjectSettings(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("cache_setting") || id == QStringLiteral("cache_path")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("cache_setting")) {
project->SetCacheLocationSetting(static_cast<Project::CacheSetting>(value.toInt()));
} else {
project->SetCustomCachePath(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadInput(Node *node, QXmlStreamReader *reader, XMLNodeData &xml_node_data) const
{
if (dynamic_cast<NodeGroup*>(node)) {
// Ignore input of group
reader->skipCurrentElement();
return;
}
QString param_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
param_id = attr.value().toString();
break;
}
}
if (param_id.isEmpty()) {
qWarning() << "Failed to load parameter with missing ID";
reader->skipCurrentElement();
return;
}
if (!node->HasInputWithID(param_id)) {
qWarning() << "Failed to load parameter that didn't exist:" << param_id;
reader->skipCurrentElement();
return;
}
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("primary")) {
// Load primary immediate
LoadImmediate(reader, node, param_id, -1, xml_node_data);
} else if (reader->name() == QStringLiteral("subelements")) {
// Load subelements
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("count")) {
node->InputArrayResize(param_id, attr.value().toInt());
}
}
int element_counter = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
LoadImmediate(reader, node, param_id, element_counter, xml_node_data);
element_counter++;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadImmediate(QXmlStreamReader *reader, Node *node, const QString& input, int element, XMLNodeData &xml_node_data) const
{
Q_UNUSED(xml_node_data)
NodeValue::Type data_type = node->GetInputDataType(input);
// HACK: SubtitleParams contain the actual subtitle data, so loading/replacing it will overwrite
// the valid subtitles. We hack around it by simply skipping loading subtitles, we'll see
// if this ends up being an issue in the future.
if (data_type == NodeValue::kSubtitleParams) {
reader->skipCurrentElement();
return;
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
// Load standard value
int val_index = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
QVariant value_on_track;
if (data_type == NodeValue::kVideoParams) {
VideoParams vp;
vp.Load(reader);
value_on_track = QVariant::fromValue(vp);
} else if (data_type == NodeValue::kAudioParams) {
AudioParams ap = TypeSerializer::LoadAudioParams(reader);
value_on_track = QVariant::fromValue(ap);
} else {
QString value_text = reader->readElementText();
if (!value_text.isEmpty()) {
value_on_track = NodeValue::StringToValue(data_type, value_text, true);
}
}
node->SetSplitStandardValueOnTrack(input, val_index, value_on_track, element);
val_index++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframing") && node->IsInputKeyframable(input)) {
node->SetInputIsKeyframing(input, reader->readElementText().toInt(), element);
} else if (reader->name() == QStringLiteral("keyframes")) {
int track = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("key")) {
NodeKeyframe* key = new NodeKeyframe();
key->set_input(input);
key->set_element(element);
key->set_track(track);
LoadKeyframe(reader, key, data_type);
key->setParent(node);
} else {
reader->skipCurrentElement();
}
}
track++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("csinput")) {
node->SetInputProperty(input, QStringLiteral("col_input"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csdisplay")) {
node->SetInputProperty(input, QStringLiteral("col_display"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csview")) {
node->SetInputProperty(input, QStringLiteral("col_view"), reader->readElementText());
} else if (reader->name() == QStringLiteral("cslook")) {
node->SetInputProperty(input, QStringLiteral("col_look"), reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadKeyframe(QXmlStreamReader *reader, NodeKeyframe *key, NodeValue::Type data_type) const
{
QString key_input;
QPointF key_in_handle;
QPointF key_out_handle;
XMLAttributeLoop(reader, attr) {
if (IsCancelled()) {
return;
}
if (attr.name() == QStringLiteral("input")) {
key_input = attr.value().toString();
} else if (attr.name() == QStringLiteral("time")) {
key->set_time(rational::fromString(attr.value().toString().toStdString()));
} else if (attr.name() == QStringLiteral("type")) {
key->set_type_no_bezier_adj(static_cast<NodeKeyframe::Type>(attr.value().toInt()));
} else if (attr.name() == QStringLiteral("inhandlex")) {
key_in_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("inhandley")) {
key_in_handle.setY(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandlex")) {
key_out_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandley")) {
key_out_handle.setY(attr.value().toDouble());
}
}
key->set_value(NodeValue::StringToValue(data_type, reader->readElementText(), true));
key->set_bezier_control_in(key_in_handle);
key->set_bezier_control_out(key_out_handle);
}
bool ProjectSerializer220403::LoadPosition(QXmlStreamReader *reader, quintptr *node_ptr, Node::Position *pos) const
{
bool got_node_ptr = false;
bool got_pos_x = false;
bool got_pos_y = false;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
*node_ptr = attr.value().toULongLong();
got_node_ptr = true;
break;
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("x")) {
pos->position.setX(reader->readElementText().toDouble());
got_pos_x = true;
} else if (reader->name() == QStringLiteral("y")) {
pos->position.setY(reader->readElementText().toDouble());
got_pos_y = true;
} else if (reader->name() == QStringLiteral("expanded")) {
pos->expanded = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
return got_node_ptr && got_pos_x && got_pos_y;
}
void ProjectSerializer220403::PostConnect(const XMLNodeData &xml_node_data) const
{
foreach (const XMLNodeData::SerializedConnection& con, xml_node_data.desired_connections) {
if (Node *out = xml_node_data.node_ptrs.value(con.output_node)) {
Node::ConnectEdge(out, con.input);
}
}
foreach (const XMLNodeData::BlockLink& l, xml_node_data.block_links) {
Node *a = l.block;
Node *b = xml_node_data.node_ptrs.value(l.link);
Node::Link(a, b);
}
foreach (const XMLNodeData::GroupLink &l, xml_node_data.group_input_links) {
if (Node *input_node = xml_node_data.node_ptrs.value(l.input_node)) {
NodeInput resolved(input_node, l.input_id, l.input_element);
l.group->AddInputPassthrough(resolved, l.passthrough_id);
l.group->SetInputFlag(l.passthrough_id, InputFlag(l.custom_flags.value()));
if (!l.custom_name.isEmpty()) {
l.group->SetInputName(l.passthrough_id, l.custom_name);
}
l.group->SetInputDataType(l.passthrough_id, l.data_type);
l.group->SetDefaultValue(l.passthrough_id, l.default_val);
for (auto it=l.custom_properties.cbegin(); it!=l.custom_properties.cend(); it++) {
l.group->SetInputProperty(l.passthrough_id, it.key(), it.value());
}
}
}
for (auto it=xml_node_data.group_output_links.cbegin(); it!=xml_node_data.group_output_links.cend(); it++) {
if (Node *output_node = xml_node_data.node_ptrs.value(it.value())) {
it.key()->SetOutputPassthrough(output_node);
}
}
}
void ProjectSerializer220403::LoadNodeCustom(QXmlStreamReader *reader, Node *node, XMLNodeData &xml_node_data) const
{
// Viewer-based nodes
if (ViewerOutput *viewer = dynamic_cast<ViewerOutput*>(node)) {
Footage *footage = dynamic_cast<Footage*>(node);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("points")) {
LoadTimelinePoints(reader, viewer);
} else if (reader->name() == QStringLiteral("timestamp") && footage) {
footage->set_timestamp(reader->readElementText().toLongLong());
} else {
reader->skipCurrentElement();
}
}
} else if (Track *track = dynamic_cast<Track*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("height")) {
track->SetTrackHeight(reader->readElementText().toDouble());
} else {
reader->skipCurrentElement();
}
}
} else if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthroughs")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthrough")) {
XMLNodeData::GroupLink link;
link.group = group;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
link.input_node = reader->readElementText().toULongLong();
} else if (reader->name() == QStringLiteral("input")) {
link.input_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("element")) {
link.input_element = reader->readElementText().toInt();
} else if (reader->name() == QStringLiteral("id")) {
link.passthrough_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("name")) {
link.custom_name = reader->readElementText();
} else if (reader->name() == QStringLiteral("flags")) {
link.custom_flags = InputFlags(reader->readElementText().toULongLong());
} else if (reader->name() == QStringLiteral("type")) {
link.data_type = NodeValue::GetDataTypeFromName(reader->readElementText());
} else if (reader->name() == QStringLiteral("default")) {
link.default_val = NodeValue::StringToValue(link.data_type, reader->readElementText(), false);
} else if (reader->name() == QStringLiteral("properties")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("property")) {
QString key;
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("key")) {
key = reader->readElementText();
} else if (reader->name() == QStringLiteral("value")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
if (!key.isEmpty()) {
link.custom_properties.insert(key, value);
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
xml_node_data.group_input_links.append(link);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("outputpassthrough")) {
xml_node_data.group_output_links.insert(group, reader->readElementText().toULongLong());
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
void ProjectSerializer220403::LoadTimelinePoints(QXmlStreamReader *reader, ViewerOutput *viewer) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("markers")) {
LoadMarkerList(reader, viewer->GetMarkers());
} else if (reader->name() == QStringLiteral("workarea")) {
LoadWorkArea(reader, viewer->GetWorkArea());
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadMarker(QXmlStreamReader *reader, TimelineMarker *marker) const
{
rational in, out;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("name")) {
marker->set_name(attr.value().toString());
} else 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());
} else if (attr.name() == QStringLiteral("color")) {
marker->set_color(attr.value().toInt());
}
}
marker->set_time(TimeRange(in, out));
// This element has no inner text, so just skip it
reader->skipCurrentElement();
}
void ProjectSerializer220403::LoadWorkArea(QXmlStreamReader *reader, TimelineWorkArea *workarea) const
{
rational range_in = workarea->in();
rational range_out = workarea->out();
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
workarea->set_enabled(attr.value() != QStringLiteral("0"));
} else if (attr.name() == QStringLiteral("in")) {
range_in = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("out")) {
range_out = rational::fromString(attr.value().toString().toStdString());
}
}
TimeRange loaded_workarea(range_in, range_out);
if (loaded_workarea != workarea->range()) {
workarea->set_range(loaded_workarea);
}
reader->skipCurrentElement();
}
void ProjectSerializer220403::LoadMarkerList(QXmlStreamReader *reader, TimelineMarkerList *markers) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
TimelineMarker *marker = new TimelineMarker(markers);
LoadMarker(reader, marker);
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer220403::LoadValueHint(Node::ValueHint *hint, QXmlStreamReader *reader) const
{
QVector<NodeValue::Type> types;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("types")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("type")) {
types.append(static_cast<NodeValue::Type>(reader->readElementText().toInt()));
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("index")) {
hint->set_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("tag")) {
hint->set_tag(reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
hint->set_type(types);
}
}
| 37,074
|
C++
|
.cpp
| 903
| 30.605759
| 158
| 0.563144
|
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,013
|
serializer190219.cpp
|
olive-editor_olive/app/node/project/serializer/serializer190219.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 "serializer190219.h"
namespace olive {
ProjectSerializer::LoadData ProjectSerializer190219::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
return LoadData();
}
}
| 934
|
C++
|
.cpp
| 21
| 41.809524
| 143
| 0.78208
|
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,014
|
serializer211228.cpp
|
olive-editor_olive/app/node/project/serializer/serializer211228.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 "serializer211228.h"
#include "config/config.h"
#include "node/factory.h"
#include "node/group/group.h"
namespace olive {
ProjectSerializer211228::LoadData ProjectSerializer211228::Load(Project *project, QXmlStreamReader *reader, LoadType load_type, void *reserved) const
{
QMap<quintptr, QMap<QString, QString> > properties;
QMap<quintptr, QMap<quintptr, Node::Position> > positions;
XMLNodeData xml_node_data;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("uuid")) {
project->SetUuid(QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("nodes")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
bool is_root = false;
bool is_cm = false;
bool is_settings = false;
QString id;
{
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
} else if (attr.name() == QStringLiteral("root") && attr.value() == QStringLiteral("1")) {
is_root = true;
} else if (attr.name() == QStringLiteral("cm") && attr.value() == QStringLiteral("1")) {
is_cm = true;
} else if (attr.name() == QStringLiteral("settings") && attr.value() == QStringLiteral("1")) {
is_settings = true;
}
}
}
if (id.isEmpty()) {
qWarning() << "Failed to load node with empty ID";
reader->skipCurrentElement();
} else {
Node* node;
bool handled_elsewhere = false;
if (is_root) {
project->Initialize();
node = project->root();
} else if (is_cm) {
LoadColorManager(reader, project);
handled_elsewhere = true;
} else if (is_settings) {
LoadProjectSettings(reader, project);
handled_elsewhere = true;
} else {
node = NodeFactory::CreateFromID(id);
}
if (!handled_elsewhere) {
if (!node) {
qWarning() << "Failed to find node with ID" << id;
reader->skipCurrentElement();
} else {
LoadNode(node, xml_node_data, reader);
node->setParent(project);
}
}
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("positions")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("context")) {
quintptr context_ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
context_ptr = attr.value().toULongLong();
break;
}
}
if (context_ptr) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr node_ptr;
Node::Position node_pos;
if (LoadPosition(reader, &node_ptr, &node_pos)) {
if (node_ptr) {
positions[context_ptr].insert(node_ptr, node_pos);
} else {
qWarning() << "Failed to find pointer for node position";
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
qWarning() << "Attempted to load context with no pointer";
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("properties")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
quintptr ptr = 0;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
ptr = attr.value().toULongLong();
// Only attribute we're looking for right now
break;
}
}
if (ptr) {
QMap<QString, QString> properties_for_node;
while (XMLReadNextStartElement(reader)) {
properties_for_node.insert(reader->name().toString(), reader->readElementText());
}
properties.insert(ptr, properties_for_node);
}
} else {
reader->skipCurrentElement();
}
}
} else {
// Skip this
reader->skipCurrentElement();
}
}
// Resolve positions
for (auto it=positions.cbegin(); it!=positions.cend(); it++) {
Node *ctx = xml_node_data.node_ptrs.value(it.key());
if (ctx) {
for (auto jt=it.value().cbegin(); jt!=it.value().cend(); jt++) {
Node *n = xml_node_data.node_ptrs.value(jt.key());
if (n) {
ctx->SetNodePositionInContext(n, jt.value());
}
}
}
}
// Make connections
PostConnect(xml_node_data);
LoadData load_data;
// Resolve serialized properties (if any)
for (auto it=properties.cbegin(); it!=properties.cend(); it++) {
Node *node = xml_node_data.node_ptrs.value(it.key());
if (node) {
load_data.properties.insert(node, it.value());
}
}
// Resolve tracks
for (Node *n : project->nodes()) {
n->SetCachesEnabled(true);
if (Track *t = dynamic_cast<Track *>(n)) {
for (int i = 0; i < t->InputArraySize(Track::kBlockInput); i++) {
Block *b = static_cast<Block*>(t->GetConnectedOutput(Track::kBlockInput, i));
if (!b->track()) {
t->AppendBlock(b);
}
}
}
}
return load_data;
}
void ProjectSerializer211228::LoadNode(Node *node, XMLNodeData &xml_node_data, QXmlStreamReader *reader) const
{
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("input")) {
LoadInput(node, reader, xml_node_data);
} else if (reader->name() == QStringLiteral("ptr")) {
quintptr ptr = reader->readElementText().toULongLong();
xml_node_data.node_ptrs.insert(ptr, node);
} else if (reader->name() == QStringLiteral("label")) {
node->SetLabel(reader->readElementText());
} else if (reader->name() == QStringLiteral("uuid")) {
xml_node_data.node_uuids.insert(node, QUuid::fromString(reader->readElementText()));
} else if (reader->name() == QStringLiteral("color")) {
node->SetOverrideColor(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("links")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("link")) {
xml_node_data.block_links.append({node, reader->readElementText().toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("custom")) {
LoadNodeCustom(reader, node, xml_node_data);
} else if (reader->name() == QStringLiteral("connections")) {
// Load connections
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("connection")) {
QString param_id;
int ele = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("element")) {
ele = attr.value().toInt();
} else if (attr.name() == QStringLiteral("input")) {
param_id = attr.value().toString();
}
}
QString output_node_id;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("output")) {
output_node_id = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.desired_connections.append({NodeInput(node, param_id, ele), output_node_id.toULongLong()});
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("hints")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("hint")) {
QString input;
int element = -1;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("input")) {
input = attr.value().toString();
} else if (attr.name() == QStringLiteral("element")) {
element = attr.value().toInt();
}
}
Node::ValueHint vh;
LoadValueHint(&vh, reader);
node->SetValueHintForInput(input, vh, element);
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
node->LoadFinishedEvent();
}
void ProjectSerializer211228::LoadColorManager(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("config") || id == QStringLiteral("default_input") || id == QStringLiteral("reference_space")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("default_input")) {
// Default color space
// NOTE: Stupidly, we saved these as integers which means we can't add anything to the OCIO
// config. So we must convert back to string here.
static const QStringList list = {
QStringLiteral("Linear"),
QStringLiteral("CIE-XYZ D65"),
QStringLiteral("Filmic Log Encoding"),
QStringLiteral("sRGB OETF"),
QStringLiteral("Apple DCI-P3 D65"),
QStringLiteral("AppleP3 sRGB OETF"),
QStringLiteral("BT.1886 EOTF"),
QStringLiteral("AppleP3 Filmic Log Encoding"),
QStringLiteral("BT.1886 Filmic Log Encoding"),
QStringLiteral("Fuji F-Log OETF"),
QStringLiteral("Fuji F-Log F-Gamut"),
QStringLiteral("Panasonic V-Log V-Gamut"),
QStringLiteral("Arri Wide Gamut / LogC EI 800"),
QStringLiteral("Arri Wide Gamut / LogC EI 400"),
QStringLiteral("Blackmagic Film Wide Gamut (Gen 5)"),
QStringLiteral("Rec.709 OETF"),
QStringLiteral("Non-Colour Data")
};
int num_value = value.toInt();
value = list.at(num_value);
project->SetDefaultInputColorSpace(value);
} else if (id == QStringLiteral("reference_space")) {
// Reference space
if (value == QStringLiteral("1")) {
value = OCIO::ROLE_COMPOSITING_LOG;
} else {
value = OCIO::ROLE_SCENE_LINEAR;
}
project->SetColorReferenceSpace(value);
} else {
// Config filename
project->SetColorConfigFilename(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer211228::LoadProjectSettings(QXmlStreamReader *reader, Project *project) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("input")) {
QString id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
id = attr.value().toString();
}
}
if (id == QStringLiteral("cache_setting") || id == QStringLiteral("cache_path")) {
QString value;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("primary")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("track")) {
value = reader->readElementText();
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
if (id == QStringLiteral("cache_setting")) {
project->SetCacheLocationSetting(static_cast<Project::CacheSetting>(value.toInt()));
} else {
project->SetCustomCachePath(value);
}
} else {
reader->skipCurrentElement();
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer211228::LoadInput(Node *node, QXmlStreamReader *reader, XMLNodeData &xml_node_data) const
{
QString param_id;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("id")) {
param_id = attr.value().toString();
break;
}
}
if (param_id.isEmpty()) {
qWarning() << "Failed to load parameter with missing ID";
reader->skipCurrentElement();
return;
}
if (!node->HasInputWithID(param_id)) {
qWarning() << "Failed to load parameter that didn't exist:" << param_id;
reader->skipCurrentElement();
return;
}
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("primary")) {
// Load primary immediate
LoadImmediate(reader, node, param_id, -1, xml_node_data);
} else if (reader->name() == QStringLiteral("subelements")) {
// Load subelements
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("count")) {
node->InputArrayResize(param_id, attr.value().toInt());
}
}
int element_counter = 0;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("element")) {
LoadImmediate(reader, node, param_id, element_counter, xml_node_data);
element_counter++;
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer211228::LoadImmediate(QXmlStreamReader *reader, Node *node, const QString& input, int element, XMLNodeData &xml_node_data) const
{
Q_UNUSED(xml_node_data)
NodeValue::Type data_type = node->GetInputDataType(input);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("standard")) {
// Load standard value
int val_index = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
QVariant value_on_track;
if (data_type == NodeValue::kVideoParams) {
VideoParams vp;
vp.Load(reader);
value_on_track = QVariant::fromValue(vp);
} else if (data_type == NodeValue::kAudioParams) {
AudioParams ap = TypeSerializer::LoadAudioParams(reader);
value_on_track = QVariant::fromValue(ap);
} else {
QString value_text = reader->readElementText();
if (!value_text.isEmpty()) {
value_on_track = NodeValue::StringToValue(data_type, value_text, true);
}
}
node->SetSplitStandardValueOnTrack(input, val_index, value_on_track, element);
val_index++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("keyframing") && node->IsInputKeyframable(input)) {
node->SetInputIsKeyframing(input, reader->readElementText().toInt(), element);
} else if (reader->name() == QStringLiteral("keyframes")) {
int track = 0;
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("track")) {
while (XMLReadNextStartElement(reader)) {
if (IsCancelled()) {
return;
}
if (reader->name() == QStringLiteral("key")) {
QString key_input;
rational key_time;
NodeKeyframe::Type key_type = NodeKeyframe::kLinear;
QVariant key_value;
QPointF key_in_handle;
QPointF key_out_handle;
XMLAttributeLoop(reader, attr) {
if (IsCancelled()) {
return;
}
if (attr.name() == QStringLiteral("input")) {
key_input = attr.value().toString();
} else if (attr.name() == QStringLiteral("time")) {
key_time = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("type")) {
key_type = static_cast<NodeKeyframe::Type>(attr.value().toInt());
} else if (attr.name() == QStringLiteral("inhandlex")) {
key_in_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("inhandley")) {
key_in_handle.setY(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandlex")) {
key_out_handle.setX(attr.value().toDouble());
} else if (attr.name() == QStringLiteral("outhandley")) {
key_out_handle.setY(attr.value().toDouble());
}
}
key_value = NodeValue::StringToValue(data_type, reader->readElementText(), true);
NodeKeyframe* key = new NodeKeyframe(key_time, key_value, key_type, track, element, key_input, node);
key->set_bezier_control_in(key_in_handle);
key->set_bezier_control_out(key_out_handle);
} else {
reader->skipCurrentElement();
}
}
track++;
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("csinput")) {
node->SetInputProperty(input, QStringLiteral("col_input"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csdisplay")) {
node->SetInputProperty(input, QStringLiteral("col_display"), reader->readElementText());
} else if (reader->name() == QStringLiteral("csview")) {
node->SetInputProperty(input, QStringLiteral("col_view"), reader->readElementText());
} else if (reader->name() == QStringLiteral("cslook")) {
node->SetInputProperty(input, QStringLiteral("col_look"), reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
}
bool ProjectSerializer211228::LoadPosition(QXmlStreamReader *reader, quintptr *node_ptr, Node::Position *pos) const
{
bool got_node_ptr = false;
bool got_pos_x = false;
bool got_pos_y = false;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("ptr")) {
*node_ptr = attr.value().toULongLong();
got_node_ptr = true;
break;
}
}
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("x")) {
pos->position.setX(reader->readElementText().toDouble());
got_pos_x = true;
} else if (reader->name() == QStringLiteral("y")) {
pos->position.setY(reader->readElementText().toDouble());
got_pos_y = true;
} else if (reader->name() == QStringLiteral("expanded")) {
pos->expanded = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
return got_node_ptr && got_pos_x && got_pos_y;
}
void ProjectSerializer211228::PostConnect(const XMLNodeData &xml_node_data) const
{
foreach (const XMLNodeData::SerializedConnection& con, xml_node_data.desired_connections) {
if (Node *out = xml_node_data.node_ptrs.value(con.output_node)) {
Node::ConnectEdge(out, con.input);
}
}
foreach (const XMLNodeData::BlockLink& l, xml_node_data.block_links) {
Node *a = l.block;
Node *b = xml_node_data.node_ptrs.value(l.link);
Node::Link(a, b);
}
foreach (const XMLNodeData::GroupLink &l, xml_node_data.group_input_links) {
if (Node *input_node = xml_node_data.node_ptrs.value(l.input_node)) {
NodeInput resolved(input_node, l.input_id, l.input_element);
l.group->AddInputPassthrough(resolved);
}
}
for (auto it=xml_node_data.group_output_links.cbegin(); it!=xml_node_data.group_output_links.cend(); it++) {
if (Node *output_node = xml_node_data.node_ptrs.value(it.value())) {
it.key()->SetOutputPassthrough(output_node);
}
}
}
void ProjectSerializer211228::LoadNodeCustom(QXmlStreamReader *reader, Node *node, XMLNodeData &xml_node_data) const
{
// Viewer-based nodes
if (ViewerOutput *viewer = dynamic_cast<ViewerOutput*>(node)) {
Footage *footage = dynamic_cast<Footage*>(node);
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("points")) {
LoadTimelinePoints(reader, viewer);
} else if (reader->name() == QStringLiteral("timestamp") && footage) {
footage->set_timestamp(reader->readElementText().toLongLong());
} else {
reader->skipCurrentElement();
}
}
} else if (Track *track = dynamic_cast<Track*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("height")) {
track->SetTrackHeight(reader->readElementText().toDouble());
} else {
reader->skipCurrentElement();
}
}
} else if (NodeGroup *group = dynamic_cast<NodeGroup*>(node)) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthroughs")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("inputpassthrough")) {
XMLNodeData::GroupLink link;
link.group = group;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("node")) {
link.input_node = reader->readElementText().toULongLong();
} else if (reader->name() == QStringLiteral("input")) {
link.input_id = reader->readElementText();
} else if (reader->name() == QStringLiteral("element")) {
link.input_element = reader->readElementText().toInt();
} else {
reader->skipCurrentElement();
}
}
xml_node_data.group_input_links.append(link);
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("outputpassthrough")) {
xml_node_data.group_output_links.insert(group, reader->readElementText().toULongLong());
} else {
reader->skipCurrentElement();
}
}
} else {
reader->skipCurrentElement();
}
}
void ProjectSerializer211228::LoadTimelinePoints(QXmlStreamReader *reader, ViewerOutput *points) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("markers")) {
LoadMarkerList(reader, points->GetMarkers());
} else if (reader->name() == QStringLiteral("workarea")) {
LoadWorkArea(reader, points->GetWorkArea());
} else {
reader->skipCurrentElement();
}
}
}
void ProjectSerializer211228::LoadWorkArea(QXmlStreamReader *reader, TimelineWorkArea *workarea) const
{
rational range_in = workarea->in();
rational range_out = workarea->out();
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("enabled")) {
workarea->set_enabled(attr.value() != QStringLiteral("0"));
} else if (attr.name() == QStringLiteral("in")) {
range_in = rational::fromString(attr.value().toString().toStdString());
} else if (attr.name() == QStringLiteral("out")) {
range_out = rational::fromString(attr.value().toString().toStdString());
}
}
TimeRange loaded_workarea(range_in, range_out);
if (loaded_workarea != workarea->range()) {
workarea->set_range(loaded_workarea);
}
reader->skipCurrentElement();
}
void ProjectSerializer211228::LoadMarkerList(QXmlStreamReader *reader, TimelineMarkerList *markers) const
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("marker")) {
QString name;
rational in, out;
XMLAttributeLoop(reader, attr) {
if (attr.name() == QStringLiteral("name")) {
name = attr.value().toString();
} else 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());
}
}
new TimelineMarker(OLIVE_CONFIG("MarkerColor").toInt(), TimeRange(in, out), name, markers);
}
reader->skipCurrentElement();
}
}
void ProjectSerializer211228::LoadValueHint(Node::ValueHint *hint, QXmlStreamReader *reader) const
{
QVector<NodeValue::Type> types;
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("types")) {
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("type")) {
types.append(static_cast<NodeValue::Type>(reader->readElementText().toInt()));
} else {
reader->skipCurrentElement();
}
}
} else if (reader->name() == QStringLiteral("index")) {
hint->set_index(reader->readElementText().toInt());
} else if (reader->name() == QStringLiteral("tag")) {
hint->set_tag(reader->readElementText());
} else {
reader->skipCurrentElement();
}
}
hint->set_type(types);
}
}
| 27,541
|
C++
|
.cpp
| 702
| 30.283476
| 150
| 0.586144
|
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,015
|
footagedescription.cpp
|
olive-editor_olive/app/node/project/footage/footagedescription.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 "footagedescription.h"
#include <QFile>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "common/xmlutils.h"
#include "node/project/serializer/typeserializer.h"
namespace olive {
bool FootageDescription::Load(const QString &filename)
{
// Reset self
*this = FootageDescription();
QFile file(filename);
if (file.open(QFile::ReadOnly)) {
QXmlStreamReader reader(&file);
while (XMLReadNextStartElement(&reader)) {
if (reader.name() == QStringLiteral("streamcache")) {
// Default to first version of metadata (which wasn't versioned at all)
unsigned version = 1;
{
XMLAttributeLoop((&reader), attr) {
if (attr.name() == QStringLiteral("version")) {
version = attr.value().toUInt();
}
}
}
if (version != kFootageMetaVersion) {
// If this is a different version, discard so we can probe new data
return false;
}
while (XMLReadNextStartElement(&reader)) {
if (reader.name() == QStringLiteral("decoder")) {
decoder_ = reader.readElementText();
} else if (reader.name() == QStringLiteral("streams")) {
{
XMLAttributeLoop((&reader), attr) {
if (attr.name() == QStringLiteral("count")) {
total_stream_count_ = attr.value().toInt();
}
}
}
while (XMLReadNextStartElement(&reader)) {
if (reader.name() == QStringLiteral("video")) {
VideoParams vp;
vp.Load(&reader);
AddVideoStream(vp);
} else if (reader.name() == QStringLiteral("audio")) {
AudioParams ap = TypeSerializer::LoadAudioParams(&reader);
AddAudioStream(ap);
} else if (reader.name() == QStringLiteral("subtitle")) {
SubtitleParams sp;
sp.Load(&reader);
AddSubtitleStream(sp);
} else {
reader.skipCurrentElement();
}
}
} else {
reader.skipCurrentElement();
}
}
} else {
reader.skipCurrentElement();
}
}
file.close();
if (reader.hasError()) {
qWarning() << "Failed to load footage description for" << filename << reader.errorString();
} else {
return true;
}
}
return false;
}
bool FootageDescription::Save(const QString &filename) const
{
QFile file(filename);
if (!file.open(QFile::WriteOnly)) {
return false;
}
QXmlStreamWriter writer(&file);
writer.writeStartDocument();
writer.writeStartElement(QStringLiteral("streamcache"));
writer.writeAttribute(QStringLiteral("version"), QString::number(kFootageMetaVersion));
writer.writeTextElement(QStringLiteral("decoder"), decoder_);
writer.writeStartElement(QStringLiteral("streams"));
writer.writeAttribute(QStringLiteral("count"), QString::number(total_stream_count_));
foreach (const VideoParams& vp, video_streams_) {
writer.writeStartElement(QStringLiteral("video"));
vp.Save(&writer);
writer.writeEndElement(); // video
}
foreach (const AudioParams& ap, audio_streams_) {
writer.writeStartElement(QStringLiteral("audio"));
TypeSerializer::SaveAudioParams(&writer, ap);
writer.writeEndElement(); // audio
}
foreach (const SubtitleParams& sp, subtitle_streams_) {
writer.writeStartElement(QStringLiteral("subtitle"));
sp.Save(&writer);
writer.writeEndElement(); // audio
}
writer.writeEndElement(); // streams
writer.writeEndElement(); // streamcache
writer.writeEndDocument();
file.close();
return true;
}
}
| 4,483
|
C++
|
.cpp
| 122
| 29.45082
| 97
| 0.643072
|
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,016
|
footage.cpp
|
olive-editor_olive/app/node/project/footage/footage.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 "footage.h"
#include <QApplication>
#include <QDir>
#include <QStandardPaths>
#include "codec/decoder.h"
#include "common/filefunctions.h"
#include "common/qtutils.h"
#include "common/xmlutils.h"
#include "config/config.h"
#include "core.h"
#include "render/job/footagejob.h"
#include "ui/icons/icons.h"
namespace olive {
const QString Footage::kFilenameInput = QStringLiteral("file_in");
#define super ViewerOutput
Footage::Footage(const QString &filename) :
ViewerOutput(false, false),
timestamp_(0),
valid_(false),
cancelled_(nullptr),
total_stream_count_(0)
{
SetFlag(kIsItem);
PrependInput(kFilenameInput, NodeValue::kFile, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
Clear();
if (!filename.isEmpty()) {
set_filename(filename);
}
QTimer *check_timer = new QTimer(this);
check_timer->setInterval(5000);
connect(check_timer, &QTimer::timeout, this, &Footage::CheckFootage);
check_timer->start();
connect(this->waveform_cache(), &AudioWaveformCache::Validated, this, &ViewerOutput::ConnectedWaveformChanged);
}
void Footage::Retranslate()
{
super::Retranslate();
SetInputName(kFilenameInput, tr("Filename"));
}
void Footage::InputValueChangedEvent(const QString &input, int element)
{
if (input == kFilenameInput) {
// Reset internal stream cache
Clear();
Reprobe();
} else {
super::InputValueChangedEvent(input, element);
}
}
rational Footage::VerifyLengthInternal(Track::Type type) const
{
if (type == Track::kVideo) {
VideoParams first_stream = GetFirstEnabledVideoStream();
if (first_stream.is_valid()) {
return Timecode::timestamp_to_time(first_stream.duration(), first_stream.time_base());
}
} else if (type == Track::kAudio) {
AudioParams first_stream = GetFirstEnabledAudioStream();
if (first_stream.is_valid()) {
return Timecode::timestamp_to_time(first_stream.duration(), first_stream.time_base());
}
} else if (type == Track::kSubtitle) {
SubtitleParams first_stream = GetFirstEnabledSubtitleStream();
if (first_stream.is_valid()) {
return first_stream.duration();
}
}
return 0;
}
QString Footage::GetColorspaceToUse(const VideoParams ¶ms) const
{
if (params.colorspace().isEmpty()) {
return project()->color_manager()->GetDefaultInputColorSpace();
} else {
return params.colorspace();
}
}
void Footage::Clear()
{
// Clear all dynamically created inputs
InputArrayResize(kVideoParamsInput, 0);
InputArrayResize(kAudioParamsInput, 0);
InputArrayResize(kSubtitleParamsInput, 0);
// Clear decoder link
decoder_.clear();
// Clear total stream count
total_stream_count_ = 0;
// Reset ready state
valid_ = false;
}
void Footage::SetValid()
{
valid_ = true;
}
QString Footage::filename() const
{
return GetStandardValue(kFilenameInput).toString();
}
void Footage::set_filename(const QString &s)
{
SetStandardValue(kFilenameInput, s);
}
const qint64 &Footage::timestamp() const
{
return timestamp_;
}
void Footage::set_timestamp(const qint64 &t)
{
timestamp_ = t;
}
int Footage::GetStreamIndex(Track::Type type, int index) const
{
switch (type) {
case Track::kVideo:
return GetVideoParams(index).stream_index();
case Track::kAudio:
return GetAudioParams(index).stream_index();
case Track::kSubtitle:
return GetSubtitleParams(index).stream_index();
case Track::kNone:
case Track::kCount:
break;
}
return -1;
}
Track::Reference Footage::GetReferenceFromRealIndex(int real_index) const
{
// Check video streams
for (int i=0; i<GetVideoStreamCount(); i++) {
if (GetVideoParams(i).stream_index() == real_index) {
return Track::Reference(Track::kVideo, i);
}
}
for (int i=0; i<GetAudioStreamCount(); i++) {
if (GetAudioParams(i).stream_index() == real_index) {
return Track::Reference(Track::kAudio, i);
}
}
for (int i=0; i<GetSubtitleStreamCount(); i++) {
if (GetSubtitleParams(i).stream_index() == real_index) {
return Track::Reference(Track::kSubtitle, i);
}
}
return Track::Reference();
}
const QString &Footage::decoder() const
{
return decoder_;
}
QString Footage::DescribeVideoStream(const VideoParams ¶ms)
{
if (params.video_type() == VideoParams::kVideoTypeStill) {
return tr("%1: Image - %2x%3").arg(QString::number(params.stream_index()),
QString::number(params.width()),
QString::number(params.height()));
} else {
return tr("%1: Video - %2x%3").arg(QString::number(params.stream_index()),
QString::number(params.width()),
QString::number(params.height()));
}
}
QString Footage::DescribeAudioStream(const AudioParams ¶ms)
{
return tr("%1: Audio - %n Channel(s), %2Hz", nullptr, params.channel_count())
.arg(QString::number(params.stream_index()),
QString::number(params.sample_rate()));
}
QString Footage::DescribeSubtitleStream(const SubtitleParams ¶ms)
{
return tr("%1: Subtitle")
.arg(QString::number(params.stream_index()));
}
void Footage::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
Q_UNUSED(globals)
// Pop filename from table
QString file = value[kFilenameInput].toString();
// If the file exists and the reference is valid, push a footage job to the renderer
if (QFileInfo::exists(file)) {
// Push length
table->Push(NodeValue::kRational, QVariant::fromValue(GetLength()), this, QStringLiteral("length"));
// Push each stream as a footage job
for (int i=0; i<GetTotalStreamCount(); i++) {
Track::Reference ref = GetReferenceFromRealIndex(i);
FootageJob job(globals.time(), decoder_, filename(), ref.type(), GetLength(), globals.loop_mode());
if (ref.type() == Track::kVideo) {
VideoParams vp = GetVideoParams(ref.index());
// Ensure the colorspace is valid and not empty
vp.set_colorspace(GetColorspaceToUse(vp));
// Adjust footage job's divider
if (globals.vparams().divider() > 1) {
// Use a divider appropriate for this target resolution
int calculated = VideoParams::GetDividerForTargetResolution(vp.width(), vp.height(), globals.vparams().effective_width(), globals.vparams().effective_height());
vp.set_divider(std::min(calculated, globals.vparams().divider()));
} else {
// Render everything at full res
vp.set_divider(1);
}
job.set_video_params(vp);
table->Push(NodeValue::kTexture, Texture::Job(vp, job), this, ref.ToString());
} else if (ref.type() == Track::kAudio) {
AudioParams ap = GetAudioParams(ref.index());
job.set_audio_params(ap);
job.set_cache_path(project()->cache_path());
table->Push(NodeValue::kSamples, QVariant::fromValue(job), this, ref.ToString());
}
}
}
}
QString Footage::GetStreamTypeName(Track::Type type)
{
switch (type) {
case Track::kVideo:
return tr("Video");
case Track::kAudio:
return tr("Audio");
case Track::kSubtitle:
return tr("Subtitle");
case Track::kNone:
case Track::kCount:
break;
}
return tr("Unknown");
}
Node *Footage::GetConnectedTextureOutput()
{
if (GetVideoStreamCount() > 0) {
return this;
} else {
return nullptr;
}
}
Node *Footage::GetConnectedSampleOutput()
{
if (GetAudioStreamCount() > 0) {
return this;
} else {
return nullptr;
}
}
bool TimeIsOutOfBounds(const rational& time, const rational& length)
{
return time < 0 || time >= length;
}
rational Footage::AdjustTimeByLoopMode(rational time, LoopMode loop_mode, const rational &length, VideoParams::Type type, const rational& timebase)
{
if (type == VideoParams::kVideoTypeStill) {
// No looping for still images
return 0;
}
if (TimeIsOutOfBounds(time, length)) {
switch (loop_mode) {
case LoopMode::kLoopModeOff:
// Return no time to indicate no frame should be shown here
time = rational::NaN;
break;
case LoopMode::kLoopModeClamp:
// Clamp footage time to length
time = std::clamp(time, rational(0), length - timebase);
break;
case LoopMode::kLoopModeLoop:
// Loop footage time around job length
do {
if (time >= length) {
time -= length;
} else {
time += length;
}
} while (TimeIsOutOfBounds(time, length));
}
}
return time;
}
QVariant Footage::data(const DataType &d) const
{
switch (d) {
case CREATED_TIME:
{
QFileInfo info(filename());
if (info.exists()) {
return QtUtils::GetCreationDate(info).toSecsSinceEpoch();
}
break;
}
case MODIFIED_TIME:
{
QFileInfo info(filename());
if (info.exists()) {
return info.lastModified().toSecsSinceEpoch();
}
break;
}
case ICON:
{
if (valid_ && GetTotalStreamCount()) {
// Prioritize video > audio > image
VideoParams s = GetFirstEnabledVideoStream();
if (s.is_valid() && s.video_type() != VideoParams::kVideoTypeStill) {
return icon::Video;
} else if (HasEnabledAudioStreams()) {
return icon::Audio;
} else if (s.is_valid() && s.video_type() == VideoParams::kVideoTypeStill) {
return icon::Image;
} else if (HasEnabledSubtitleStreams()) {
return icon::Subtitles;
}
}
return icon::Error;
}
case TOOLTIP:
{
if (valid_) {
QString tip = tr("Filename: %1").arg(filename());
int vp_sz = GetVideoStreamCount();
for (int i=0; i<vp_sz; i++) {
VideoParams p = GetVideoParams(i);
if (p.enabled()) {
tip.append("\n");
tip.append(DescribeVideoStream(p));
}
}
int ap_sz = GetAudioStreamCount();
for (int i=0; i<ap_sz; i++) {
AudioParams p = GetAudioParams(i);
if (p.enabled()) {
tip.append("\n");
tip.append(DescribeAudioStream(p));
}
}
int sp_sz = GetSubtitleStreamCount();
for (int i=0; i<sp_sz; i++) {
SubtitleParams p = GetSubtitleParams(i);
if (p.enabled()) {
tip.append("\n");
tip.append(DescribeSubtitleStream(p));
}
}
return tip;
} else {
return tr("Invalid");
}
}
default:
break;
}
return super::data(d);
}
bool Footage::LoadCustom(QXmlStreamReader *reader, SerializedData *data)
{
while (XMLReadNextStartElement(reader)) {
if (reader->name() == QStringLiteral("timestamp")) {
this->set_timestamp(reader->readElementText().toLongLong());
} else if (reader->name() == QStringLiteral("viewer")) {
if (!ViewerOutput::LoadCustom(reader, data)) {
return false;
}
} else {
reader->skipCurrentElement();
}
}
return true;
}
void Footage::SaveCustom(QXmlStreamWriter *writer) const
{
writer->writeTextElement(QStringLiteral("timestamp"), QString::number(this->timestamp()));
writer->writeStartElement(QStringLiteral("viewer"));
ViewerOutput::SaveCustom(writer);
writer->writeEndElement(); // viewer
}
void Footage::AddedToGraphEvent(Project *p)
{
connect(p->color_manager(), &ColorManager::DefaultInputChanged, this, &Footage::DefaultColorSpaceChanged);
}
void Footage::RemovedFromGraphEvent(Project *p)
{
disconnect(p->color_manager(), &ColorManager::DefaultInputChanged, this, &Footage::DefaultColorSpaceChanged);
}
void Footage::Reprobe()
{
// Determine if file still exists
QString filename = this->filename();
// In case of failure to load file, set timestamp to a value that will always be invalid so we
// continuously reprobe
set_timestamp(0);
if (!filename.isEmpty()) {
QFileInfo info(filename);
if (info.exists()) {
// Grab timestamp
set_timestamp(info.lastModified().toMSecsSinceEpoch());
// Determine if we've already cached the metadata of this file
QString meta_cache_file = QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).filePath(FileFunctions::GetUniqueFileIdentifier(filename));
FootageDescription footage_info;
// Try to load footage info from cache
if (!QFileInfo::exists(meta_cache_file) || !footage_info.Load(meta_cache_file)) {
// Probe and create cache
QVector<DecoderPtr> decoder_list = Decoder::ReceiveListOfAllDecoders();
foreach (DecoderPtr decoder, decoder_list) {
footage_info = decoder->Probe(filename, cancelled_);
if (footage_info.IsValid()) {
break;
}
}
if (!cancelled_ || !cancelled_->HeardCancel()) {
if (!footage_info.Save(meta_cache_file)) {
qWarning() << "Failed to save stream cache, footage will have to be re-probed";
}
}
}
if (footage_info.IsValid()) {
decoder_ = footage_info.decoder();
InputArrayResize(kVideoParamsInput, footage_info.GetVideoStreams().size());
for (int i=0; i<footage_info.GetVideoStreams().size(); i++) {
VideoParams video_stream = footage_info.GetVideoStreams().at(i);
if (i < InputArraySize(kVideoParamsInput)) {
VideoParams existing = this->GetVideoParams(i);
if (existing.is_valid()) {
video_stream = MergeVideoStream(video_stream, existing);
}
}
SetStream(Track::kVideo, QVariant::fromValue(video_stream), i);
}
InputArrayResize(kAudioParamsInput, footage_info.GetAudioStreams().size());
for (int i=0; i<footage_info.GetAudioStreams().size(); i++) {
SetStream(Track::kAudio, QVariant::fromValue(footage_info.GetAudioStreams().at(i)), i);
}
InputArrayResize(kSubtitleParamsInput, footage_info.GetSubtitleStreams().size());
for (int i=0; i<footage_info.GetSubtitleStreams().size(); i++) {
SetStream(Track::kSubtitle, QVariant::fromValue(footage_info.GetSubtitleStreams().at(i)), i);
}
total_stream_count_ = footage_info.GetStreamCount();
SetValid();
}
}
}
}
VideoParams Footage::MergeVideoStream(const VideoParams &base, const VideoParams &over)
{
VideoParams merged = base;
merged.set_pixel_aspect_ratio(over.pixel_aspect_ratio());
merged.set_interlacing(over.interlacing());
merged.set_colorspace(over.colorspace());
merged.set_premultiplied_alpha(over.premultiplied_alpha());
merged.set_video_type(over.video_type());
merged.set_color_range(over.color_range());
if (merged.video_type() == VideoParams::kVideoTypeImageSequence) {
merged.set_start_time(over.start_time());
merged.set_duration(over.duration());
merged.set_frame_rate(over.frame_rate());
merged.set_time_base(over.time_base());
}
return merged;
}
void Footage::CheckFootage()
{
// Don't check files if not the active window
if (qApp->activeWindow()) {
QString fn = filename();
if (!fn.isEmpty()) {
QFileInfo info(fn);
qint64 current_file_timestamp;
if (!info.lastModified().isValid()) {
current_file_timestamp = 0;
} else {
current_file_timestamp = info.lastModified().toMSecsSinceEpoch();
}
if (current_file_timestamp != timestamp()) {
// File has changed!
Reprobe();
InvalidateAll(kFilenameInput);
}
}
}
}
void Footage::DefaultColorSpaceChanged()
{
bool inv = false;
int sz = GetVideoStreamCount();
for (int i = 0; i < sz; i++) {
// Check if any of our streams are using the default colorspace
if (GetVideoParams(i).colorspace().isEmpty()) {
inv = true;
break;
}
}
if (inv) {
InvalidateAll(kVideoParamsInput);
}
}
}
| 16,558
|
C++
|
.cpp
| 503
| 27.856859
| 170
| 0.670055
|
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,017
|
folder.cpp
|
olive-editor_olive/app/node/project/folder/folder.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 "folder.h"
#include "common/xmlutils.h"
#include "node/nodeundo.h"
#include "node/project/footage/footage.h"
#include "node/project/sequence/sequence.h"
#include "ui/icons/icons.h"
namespace olive {
#define super Node
const QString Folder::kChildInput = QStringLiteral("child_in");
Folder::Folder()
{
SetFlag(kIsItem);
AddInput(kChildInput, NodeValue::kNone, InputFlags(kInputFlagArray | kInputFlagNotKeyframable));
}
QVariant Folder::data(const DataType &d) const
{
if (d == ICON) {
return icon::Folder;
}
return super::data(d);
}
void Folder::Retranslate()
{
super::Retranslate();
SetInputName(kChildInput, tr("Children"));
}
Node *GetChildWithNameInternal(const Folder* n, const QString& s)
{
for (int i=0; i<n->item_child_count(); i++) {
Node* child = n->item_child(i);
if (child->GetLabel() == s) {
return child;
} else if (Folder* subfolder = dynamic_cast<Folder*>(child)) {
if (Node *n2 = GetChildWithNameInternal(subfolder, s)) {
return n2;
}
}
}
return nullptr;
}
Node *Folder::GetChildWithName(const QString &s) const
{
return GetChildWithNameInternal(this, s);
}
bool Folder::HasChildRecursive(Node *child) const
{
for (Node *i : item_children_) {
if (i == child) {
return true;
} else if (Folder *f = dynamic_cast<Folder*>(i)) {
if (f->HasChildRecursive(child)) {
return true;
}
}
}
return false;
}
int Folder::index_of_child_in_array(Node *item) const
{
int index_of_item = item_children_.indexOf(item);
if (index_of_item == -1) {
return -1;
}
return item_element_index_.at(index_of_item);
}
void Folder::InputConnectedEvent(const QString &input, int element, Node *output)
{
if (input == kChildInput && element != -1) {
Node* item = output;
// The insert index is always our "count" because we only support appending in our internal
// model. For sorting/organizing, a QSortFilterProxyModel is used instead.
emit BeginInsertItem(item, item_child_count());
item_children_.append(item);
item_element_index_.append(element);
item->SetFolder(this);
emit EndInsertItem();
}
}
void Folder::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
if (input == kChildInput && element != -1) {
Node* item = output;
int child_index = item_children_.indexOf(item);
emit BeginRemoveItem(item, child_index);
item_children_.removeAt(child_index);
item_element_index_.removeAt(child_index);
item->SetFolder(nullptr);
emit EndRemoveItem();
}
}
FolderAddChild::FolderAddChild(Folder *folder, Node *child) :
folder_(folder),
child_(child)
{
}
Project *FolderAddChild::GetRelevantProject() const
{
return folder_->project();
}
void FolderAddChild::redo()
{
int array_index = folder_->InputArraySize(Folder::kChildInput);
folder_->InputArrayAppend(Folder::kChildInput);
Node::ConnectEdge(child_, NodeInput(folder_, Folder::kChildInput, array_index));
}
void FolderAddChild::undo()
{
Node::DisconnectEdge(child_, NodeInput(folder_, Folder::kChildInput, folder_->InputArraySize(Folder::kChildInput)-1));
folder_->InputArrayRemoveLast(Folder::kChildInput);
}
void Folder::RemoveElementCommand::redo()
{
if (!subcommand_) {
remove_index_ = folder_->index_of_child_in_array(child_);
if (remove_index_ != -1) {
NodeInput connected_input(folder_, Folder::kChildInput, remove_index_);
subcommand_ = new MultiUndoCommand();
subcommand_->add_child(new NodeEdgeRemoveCommand(folder_->GetConnectedOutput(connected_input), connected_input));
subcommand_->add_child(new NodeArrayRemoveCommand(folder_, Folder::kChildInput, remove_index_));
}
}
if (subcommand_) {
subcommand_->redo_now();
}
}
}
| 4,499
|
C++
|
.cpp
| 140
| 28.878571
| 120
| 0.717557
|
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,018
|
block.cpp
|
olive-editor_olive/app/node/block/block.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 "block.h"
#include <QDebug>
#include "node/inputdragger.h"
#include "node/output/track/track.h"
#include "transition/transition.h"
#include "widget/slider/rationalslider.h"
namespace olive {
#define super Node
const QString Block::kLengthInput = QStringLiteral("length_in");
Block::Block() :
previous_(nullptr),
next_(nullptr),
track_(nullptr)
{
AddInput(kLengthInput, NodeValue::kRational, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable | kInputFlagHidden));
SetInputProperty(kLengthInput, QStringLiteral("min"), QVariant::fromValue(rational(0, 1)));
SetInputProperty(kLengthInput, QStringLiteral("view"), RationalSlider::kTime);
SetInputProperty(kLengthInput, QStringLiteral("viewlock"), true);
SetInputFlag(kEnabledInput, kInputFlagNotConnectable);
SetInputFlag(kEnabledInput, kInputFlagNotKeyframable);
SetFlag(kDontShowInParamView);
}
QVector<Node::CategoryID> Block::Category() const
{
return {kCategoryTimeline};
}
rational Block::length() const
{
return GetStandardValue(kLengthInput).value<rational>();
}
void Block::set_length_and_media_out(const rational &length)
{
if (length == this->length()) {
return;
}
set_length_internal(length);
}
void Block::set_length_and_media_in(const rational &length)
{
if (length == this->length()) {
return;
}
// Set the length without setting media out
set_length_internal(length);
}
bool Block::is_enabled() const
{
return GetStandardValue(kEnabledInput).toBool();
}
void Block::set_enabled(bool e)
{
SetStandardValue(kEnabledInput, e);
emit EnabledChanged();
}
void Block::InputValueChangedEvent(const QString &input, int element)
{
super::InputValueChangedEvent(input, element);
if (input == kLengthInput) {
emit LengthChanged();
} else if (input == kEnabledInput) {
emit EnabledChanged();
}
}
void Block::set_length_internal(const rational &length)
{
SetStandardValue(kLengthInput, QVariant::fromValue(length));
}
void Block::Retranslate()
{
super::Retranslate();
SetInputName(kLengthInput, tr("Length"));
SetInputName(kEnabledInput, tr("Enabled"));
}
void Block::InvalidateCache(const TimeRange& range, const QString& from, int element, InvalidateCacheOptions options)
{
TimeRange r;
if (from == kLengthInput) {
// We must intercept the signal here
r = TimeRange(qMin(length(), last_length_), RATIONAL_MAX);
if (!NodeInputDragger::IsInputBeingDragged()) {
last_length_ = length();
}
options.insert(QStringLiteral("lengthevent"), true);
} else {
r = range;
}
super::InvalidateCache(r, from, element, options);
}
void Block::set_previous_next(Block *previous, Block *next)
{
if (previous) {
previous->set_next(next);
}
if (next) {
next->set_previous(previous);
}
}
}
| 3,513
|
C++
|
.cpp
| 112
| 28.660714
| 131
| 0.754011
|
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,019
|
subtitle.cpp
|
olive-editor_olive/app/node/block/subtitle/subtitle.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 "subtitle.h"
namespace olive {
#define super ClipBlock
const QString SubtitleBlock::kTextIn = QStringLiteral("text_in");
SubtitleBlock::SubtitleBlock()
{
AddInput(kTextIn, NodeValue::kText, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
SetInputFlag(kBufferIn, kInputFlagHidden);
SetInputFlag(kLengthInput, kInputFlagHidden);
SetInputFlag(kMediaInInput, kInputFlagHidden);
SetInputFlag(kSpeedInput, kInputFlagHidden);
SetInputFlag(kReverseInput, kInputFlagHidden);
SetInputFlag(kMaintainAudioPitchInput, kInputFlagHidden);
// Undo block flag that hides in param view
SetFlag(kDontShowInParamView, false);
}
QString SubtitleBlock::Name() const
{
if (GetText().isEmpty()) {
return tr("Subtitle");
} else {
return GetText();
}
}
QString SubtitleBlock::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.subtitle");
}
QString SubtitleBlock::Description() const
{
return tr("A time-based node representing a single subtitle element for a certain period of time.");
}
void SubtitleBlock::Retranslate()
{
super::Retranslate();
SetInputName(kTextIn, tr("Text"));
}
}
| 1,863
|
C++
|
.cpp
| 52
| 33.25
| 103
| 0.783603
|
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,020
|
clip.cpp
|
olive-editor_olive/app/node/block/clip/clip.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 "clip.h"
#include "config/config.h"
#include "node/block/transition/transition.h"
#include "node/project/sequence/sequence.h"
#include "node/output/track/track.h"
#include "node/output/viewer/viewer.h"
#include "widget/slider/floatslider.h"
#include "widget/slider/rationalslider.h"
namespace olive {
#define super Block
const QString ClipBlock::kBufferIn = QStringLiteral("buffer_in");
const QString ClipBlock::kMediaInInput = QStringLiteral("media_in_in");
const QString ClipBlock::kSpeedInput = QStringLiteral("speed_in");
const QString ClipBlock::kReverseInput = QStringLiteral("reverse_in");
const QString ClipBlock::kMaintainAudioPitchInput = QStringLiteral("maintain_audio_pitch_in");
const QString ClipBlock::kAutoCacheInput = QStringLiteral("autocache_in");
const QString ClipBlock::kLoopModeInput = QStringLiteral("loop_in");
ClipBlock::ClipBlock() :
in_transition_(nullptr),
out_transition_(nullptr),
connected_viewer_(nullptr)
{
AddInput(kMediaInInput, NodeValue::kRational, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
SetInputProperty(kMediaInInput, QStringLiteral("view"), RationalSlider::kTime);
SetInputProperty(kMediaInInput, QStringLiteral("viewlock"), true);
AddInput(kSpeedInput, NodeValue::kFloat, 1.0, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
SetInputProperty(kSpeedInput, QStringLiteral("view"), FloatSlider::kPercentage);
SetInputProperty(kSpeedInput, QStringLiteral("min"), 0.0);
AddInput(kReverseInput, NodeValue::kBoolean, false, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kMaintainAudioPitchInput, NodeValue::kBoolean, false, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kAutoCacheInput, NodeValue::kBoolean, false, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
PrependInput(kBufferIn, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
//SetValueHintForInput(kBufferIn, ValueHint(NodeValue::kBuffer));
SetEffectInput(kBufferIn);
AddInput(kLoopModeInput, NodeValue::kCombo, 0, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
}
QString ClipBlock::Name() const
{
if (connected_viewer_ && !connected_viewer_->GetLabel().isEmpty()) {
return connected_viewer_->GetLabel();
} else if (track()) {
if (track()->type() == Track::kVideo) {
return tr("Video Clip");
} else if (track()->type() == Track::kAudio) {
return tr("Audio Clip");
}
}
return tr("Clip");
}
QString ClipBlock::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.clip");
}
QString ClipBlock::Description() const
{
return tr("A time-based node that represents a media source.");
}
void ClipBlock::set_length_and_media_out(const rational &length)
{
if (length == this->length()) {
return;
}
if (reverse()) {
// Calculate media_in adjustment
rational proposed_media_in = SequenceToMediaTime(this->length() - length, kSTMIgnoreReverse | kSTMIgnoreLoop);
set_media_in(proposed_media_in);
}
super::set_length_and_media_out(length);
}
void ClipBlock::set_length_and_media_in(const rational &length)
{
if (length == this->length()) {
return;
}
rational old_length = this->length();
super::set_length_and_media_in(length);
if (!reverse()) {
// Calculate media_in adjustment
set_media_in(SequenceToMediaTime(old_length - length, kSTMIgnoreLoop));
}
}
rational ClipBlock::media_in() const
{
return GetStandardValue(kMediaInInput).value<rational>();
}
void ClipBlock::set_media_in(const rational &media_in)
{
SetStandardValue(kMediaInInput, QVariant::fromValue(media_in));
RequestInvalidatedFromConnected();
}
void ClipBlock::SetAutocache(bool e)
{
SetStandardValue(kAutoCacheInput, e);
}
void ClipBlock::DiscardCache()
{
if (Node *connected = GetConnectedOutput(kBufferIn)) {
Track::Type type = GetTrackType();
if (type == Track::kVideo) {
connected->video_frame_cache()->Invalidate(TimeRange(RATIONAL_MIN, RATIONAL_MAX));
} else if (type == Track::kAudio) {
connected->audio_playback_cache()->Invalidate(TimeRange(RATIONAL_MIN, RATIONAL_MAX));
}
}
}
rational ClipBlock::SequenceToMediaTime(const rational &sequence_time, uint64_t flags) const
{
// These constants are not considered "values" per se, so we don't modify them
if (sequence_time == RATIONAL_MIN || sequence_time == RATIONAL_MAX) {
return sequence_time;
}
rational media_time = sequence_time;
if (reverse() && !(flags & kSTMIgnoreReverse)) {
media_time = length() - media_time;
}
if (!(flags & kSTMIgnoreSpeed)) {
double speed_value = speed();
if (qIsNull(speed_value)) {
// Effectively holds the frame at the in point
media_time = 0;
} else if (!qFuzzyCompare(speed_value, 1.0)) {
// Multiply time
media_time = rational::fromDouble(media_time.toDouble() * speed_value);
}
}
media_time += media_in();
/*if (!(flags & kSTMIgnoreLoop)
&& this->loop_mode() != kLoopModeOff
&& connected_viewer_
&& !connected_viewer_->GetLength().isNull()
&& (media_time < 0 || media_time >= connected_viewer_->GetLength())) {
if (loop_mode() == kLoopModeLoop) {
while (media_time < 0) {
media_time += connected_viewer_->GetLength();
}
while (media_time >= connected_viewer_->GetLength()) {
media_time -= connected_viewer_->GetLength();
}
} else if (loop_mode() == kLoopModeClamp) {
media_time = std::clamp(media_time, rational(0), connected_viewer_->GetLength()-connected_viewer_->GetVideoParams().frame_rate_as_time_base());
}
}*/
return media_time;
}
rational ClipBlock::MediaToSequenceTime(const rational &media_time) const
{
// These constants are not considered "values" per se, so we don't modify them
if (media_time == RATIONAL_MIN || media_time == RATIONAL_MAX) {
return media_time;
}
rational sequence_time = media_time - media_in();
double speed_value = speed();
if (qIsNull(speed_value)) {
// I don't know what to return here yet...
sequence_time = rational::NaN;
} else if (!qFuzzyCompare(speed_value, 1.0)) {
// Divide time
sequence_time = rational::fromDouble(sequence_time.toDouble() / speed_value);
}
if (reverse()) {
sequence_time = length() - sequence_time;
}
return sequence_time;
}
void ClipBlock::RequestRangeFromConnected(const TimeRange &range)
{
Track::Type type = GetTrackType();
if (type == Track::kVideo || type == Track::kAudio) {
if (Node *connected = GetConnectedOutput(kBufferIn)) {
TimeRange max_range = media_range();
if (type == Track::kVideo) {
// Handle thumbnails
RequestRangeForCache(connected->thumbnail_cache(), max_range, range, true, false);
{
TimeRange thumb_range = range.Intersected(max_range);
if (GetAdjustedThumbnailRange(&thumb_range)) {
connected->thumbnail_cache()->Request(this->track()->sequence(), thumb_range);
}
}
// Handle video cache
RequestRangeForCache(connected->video_frame_cache(), max_range, range, true, IsAutocaching());
} else if (type == Track::kAudio) {
// Handle waveforms
RequestRangeForCache(connected->waveform_cache(), max_range, range, true, (OLIVE_CONFIG("TimelineWaveformMode").toInt() == Timeline::kWaveformsEnabled));
// Handle audio cache
RequestRangeForCache(connected->audio_playback_cache(), max_range, range, true, IsAutocaching());
}
}
}
}
void ClipBlock::RequestInvalidatedFromConnected(bool force_all, const TimeRange &intersect)
{
Track::Type type = GetTrackType();
if (type == Track::kVideo || type == Track::kAudio) {
if (Node *connected = GetConnectedOutput(kBufferIn)) {
TimeRange max_range = media_range();
if (!intersect.length().isNull()) {
max_range = max_range.Intersected(intersect);
}
if (type == Track::kVideo) {
// Handle thumbnails
TimeRange thumb_range = max_range;
if (GetAdjustedThumbnailRange(&thumb_range)) {
RequestInvalidatedForCache(connected->thumbnail_cache(), thumb_range);
}
// Handle video cache
if (IsAutocaching() || force_all) {
RequestInvalidatedForCache(connected->video_frame_cache(), max_range);
}
} else if (type == Track::kAudio) {
// Handle waveforms
if (OLIVE_CONFIG("TimelineWaveformMode").toInt() == Timeline::kWaveformsEnabled) {
RequestInvalidatedForCache(connected->waveform_cache(), max_range);
}
// Handle audio cache
if (IsAutocaching() || force_all) {
RequestInvalidatedForCache(connected->audio_playback_cache(), max_range);
}
}
}
}
}
void ClipBlock::RequestRangeForCache(PlaybackCache *cache, const TimeRange &max_range, const TimeRange &range, bool invalidate, bool request)
{
TimeRange r = range.Intersected(max_range);
if (invalidate) {
cache->Invalidate(r);
}
if (request) {
cache->Request(this->track()->sequence(), r);
}
}
void ClipBlock::RequestInvalidatedForCache(PlaybackCache *cache, const TimeRange &max_range)
{
TimeRangeList invalid = cache->GetInvalidatedRanges(max_range);
for (const PlaybackCache::Passthrough &p : cache->GetPassthroughs()) {
invalid.remove(p);
}
for (const TimeRange &r : invalid) {
RequestRangeForCache(cache, max_range, r, false, true);
}
}
bool ClipBlock::GetAdjustedThumbnailRange(TimeRange *r) const
{
switch (static_cast<Timeline::ThumbnailMode>(OLIVE_CONFIG("TimelineThumbnailMode").toInt())) {
case Timeline::kThumbnailOff:
// Don't cache any range
return false;
case Timeline::kThumbnailInOut:
{
// Only cache in point
rational in = this->media_range().in();
if (r->Contains(in)) {
// Cache only the in point
*r = TimeRange(in, in + thumbnail_cache()->GetTimebase());
return true;
} else {
// Cache nothing
return false;
}
}
case Timeline::kThumbnailOn:
// Cache entire range
return true;
}
// Fallback
return true;
}
void ClipBlock::InvalidateCache(const TimeRange& range, const QString& from, int element, InvalidateCacheOptions options)
{
Q_UNUSED(element)
// If signal is from texture input, transform all times from media time to sequence time
if (from == kBufferIn) {
// Render caches where necessary
if (AreCachesEnabled()) {
RequestRangeFromConnected(range);
}
// Adjust range from media time to sequence time
TimeRange adj;
double speed_value = speed();
if (qIsNull(speed_value)) {
// Handle 0 speed by invalidating the whole clip
adj = TimeRange(RATIONAL_MIN, RATIONAL_MAX);
} else {
adj = TimeRange(MediaToSequenceTime(range.in()), MediaToSequenceTime(range.out()));
}
// Find connected viewer node
auto viewers = FindInputNodesConnectedToInput<ViewerOutput>(NodeInput(this, kBufferIn), 1);
ViewerOutput *new_connected_viewer = viewers.isEmpty() ? nullptr : viewers.first();
if (new_connected_viewer != connected_viewer_) {
if (connected_viewer_) {
disconnect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerAdded, this, &ClipBlock::PreviewChanged);
disconnect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerRemoved, this, &ClipBlock::PreviewChanged);
disconnect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerModified, this, &ClipBlock::PreviewChanged);
}
connected_viewer_ = new_connected_viewer;
if (connected_viewer_) {
connect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerAdded, this, &ClipBlock::PreviewChanged);
connect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerRemoved, this, &ClipBlock::PreviewChanged);
connect(connected_viewer_->GetMarkers(), &TimelineMarkerList::MarkerModified, this, &ClipBlock::PreviewChanged);
}
}
super::InvalidateCache(adj, from, element, options);
} else {
// Otherwise, pass signal along normally
super::InvalidateCache(range, from, element, options);
}
}
void ClipBlock::LinkChangeEvent()
{
block_links_.clear();
foreach (Node* n, links()) {
ClipBlock* b = dynamic_cast<ClipBlock*>(n);
if (b) {
block_links_.append(b);
}
}
}
void ClipBlock::InputConnectedEvent(const QString &input, int element, Node *output)
{
super::InputConnectedEvent(input, element, output);
if (input == kBufferIn) {
connect(output->thumbnail_cache(), &FrameHashCache::Invalidated, this, &Block::PreviewChanged);
connect(output->waveform_cache(), &AudioPlaybackCache::Invalidated, this, &Block::PreviewChanged);
connect(output->video_frame_cache(), &FrameHashCache::Invalidated, this, &Block::PreviewChanged);
connect(output->audio_playback_cache(), &AudioPlaybackCache::Invalidated, this, &Block::PreviewChanged);
connect(output->thumbnail_cache(), &FrameHashCache::Validated, this, &Block::PreviewChanged);
connect(output->waveform_cache(), &AudioPlaybackCache::Validated, this, &Block::PreviewChanged);
connect(output->video_frame_cache(), &FrameHashCache::Validated, this, &Block::PreviewChanged);
connect(output->audio_playback_cache(), &AudioPlaybackCache::Validated, this, &Block::PreviewChanged);
}
}
void ClipBlock::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
super::InputDisconnectedEvent(input, element, output);
if (input == kBufferIn) {
disconnect(output->thumbnail_cache(), &FrameHashCache::Invalidated, this, &Block::PreviewChanged);
disconnect(output->waveform_cache(), &AudioPlaybackCache::Invalidated, this, &Block::PreviewChanged);
disconnect(output->video_frame_cache(), &FrameHashCache::Invalidated, this, &Block::PreviewChanged);
disconnect(output->audio_playback_cache(), &AudioPlaybackCache::Invalidated, this, &Block::PreviewChanged);
disconnect(output->thumbnail_cache(), &FrameHashCache::Validated, this, &Block::PreviewChanged);
disconnect(output->waveform_cache(), &AudioPlaybackCache::Validated, this, &Block::PreviewChanged);
disconnect(output->video_frame_cache(), &FrameHashCache::Validated, this, &Block::PreviewChanged);
disconnect(output->audio_playback_cache(), &AudioPlaybackCache::Validated, this, &Block::PreviewChanged);
}
}
void ClipBlock::InputValueChangedEvent(const QString &input, int element)
{
super::InputValueChangedEvent(input, element);
if (input == kAutoCacheInput) {
if (IsAutocaching()) {
RequestInvalidatedFromConnected();
} else {
Track::Type type = GetTrackType();
if (Node *connected = GetConnectedOutput(kBufferIn)) {
if (type == Track::kVideo) {
emit connected->video_frame_cache()->CancelAll();
} else if (type == Track::kAudio) {
emit connected->audio_playback_cache()->CancelAll();
}
}
}
} else if (input == kLoopModeInput) {
emit PreviewChanged();
}
}
TimeRange ClipBlock::InputTimeAdjustment(const QString& input, int element, const TimeRange& input_time, bool clamp) const
{
Q_UNUSED(element)
if (input == kBufferIn) {
return TimeRange(SequenceToMediaTime(input_time.in()), SequenceToMediaTime(input_time.out()));
}
return super::InputTimeAdjustment(input, element, input_time, clamp);
}
TimeRange ClipBlock::OutputTimeAdjustment(const QString& input, int element, const TimeRange& input_time) const
{
Q_UNUSED(element)
if (input == kBufferIn) {
return TimeRange(MediaToSequenceTime(input_time.in()), MediaToSequenceTime(input_time.out()));
}
return super::OutputTimeAdjustment(input, element, input_time);
}
void ClipBlock::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
Q_UNUSED(globals)
// We discard most values here except for the buffer we received
NodeValue data = value[kBufferIn];
table->Clear();
if (data.type() != NodeValue::kNone) {
table->Push(data);
}
}
void ClipBlock::Retranslate()
{
super::Retranslate();
SetInputName(kBufferIn, tr("Buffer"));
SetInputName(kMediaInInput, tr("Media In"));
SetInputName(kSpeedInput, tr("Speed"));
SetInputName(kReverseInput, tr("Reverse"));
SetInputName(kMaintainAudioPitchInput, tr("Maintain Audio Pitch"));
SetInputName(kLoopModeInput, tr("Loop"));
SetComboBoxStrings(kLoopModeInput, {tr("None"), tr("Loop"), tr("Clamp")});
}
void ClipBlock::AddCachePassthroughFrom(ClipBlock *other)
{
if (auto tc = this->video_frame_cache()) {
if (auto oc = other->video_frame_cache()) {
tc->SetPassthrough(oc);
}
}
if (auto tc = this->audio_playback_cache()) {
if (auto oc = other->audio_playback_cache()) {
tc->SetPassthrough(oc);
}
}
if (auto tc = this->thumbnails()) {
if (auto oc = other->thumbnails()) {
tc->SetPassthrough(oc);
}
}
if (auto tc = this->waveform()) {
if (auto oc = other->waveform()) {
tc->SetPassthrough(oc);
}
}
}
void ClipBlock::ConnectedToPreviewEvent()
{
RequestInvalidatedFromConnected();
}
TimeRange ClipBlock::media_range() const
{
return InputTimeAdjustment(kBufferIn, -1, TimeRange(0, length()), false);
}
MultiCamNode *ClipBlock::FindMulticam()
{
auto v = FindInputNodesConnectedToInput<MultiCamNode>(NodeInput(this, kBufferIn), 1);
if (v.empty()) {
return nullptr;
} else {
return v.first();
}
}
}
| 18,246
|
C++
|
.cpp
| 458
| 35.585153
| 161
| 0.712315
|
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,021
|
transition.cpp
|
olive-editor_olive/app/node/block/transition/transition.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 "transition.h"
#include "node/block/clip/clip.h"
#include "node/output/track/track.h"
#include "widget/slider/rationalslider.h"
namespace olive {
#define super Block
const QString TransitionBlock::kOutBlockInput = QStringLiteral("out_block_in");
const QString TransitionBlock::kInBlockInput = QStringLiteral("in_block_in");
const QString TransitionBlock::kCurveInput = QStringLiteral("curve_in");
const QString TransitionBlock::kCenterInput = QStringLiteral("center_in");
TransitionBlock::TransitionBlock() :
connected_out_block_(nullptr),
connected_in_block_(nullptr)
{
AddInput(kOutBlockInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
AddInput(kInBlockInput, NodeValue::kNone, InputFlags(kInputFlagNotKeyframable));
AddInput(kCurveInput, NodeValue::kCombo, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable));
AddInput(kCenterInput, NodeValue::kRational, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable));
SetInputProperty(kCenterInput, QStringLiteral("view"), RationalSlider::kTime);
SetInputProperty(kCenterInput, QStringLiteral("viewlock"), true);
SetFlag(kDontShowInParamView, false);
}
void TransitionBlock::Retranslate()
{
super::Retranslate();
SetInputName(kOutBlockInput, tr("From"));
SetInputName(kInBlockInput, tr("To"));
SetInputName(kCurveInput, tr("Curve"));
SetInputName(kCenterInput, tr("Center Offset"));
// These must correspond to the CurveType enum
SetComboBoxStrings(kCurveInput, { tr("Linear"), tr("Exponential"), tr("Logarithmic") });
}
rational TransitionBlock::in_offset() const
{
if (is_dual_transition()) {
return length()/2 + offset_center();
} else if (connected_in_block()) {
return length();
} else {
return 0;
}
}
rational TransitionBlock::out_offset() const
{
if (is_dual_transition()) {
return length()/2 - offset_center();
} else if (connected_out_block()) {
return length();
} else {
return 0;
}
}
rational TransitionBlock::offset_center() const
{
return GetStandardValue(kCenterInput).value<rational>();
}
void TransitionBlock::set_offset_center(const rational &r)
{
SetStandardValue(kCenterInput, QVariant::fromValue(r));
}
void TransitionBlock::set_offsets_and_length(const rational &in_offset, const rational &out_offset)
{
rational len = in_offset + out_offset;
rational center = len / 2 - in_offset;
set_length_and_media_out(len);
set_offset_center(center);
}
Block *TransitionBlock::connected_out_block() const
{
return connected_out_block_;
}
Block *TransitionBlock::connected_in_block() const
{
return connected_in_block_;
}
double TransitionBlock::GetTotalProgress(const double &time) const
{
return GetInternalTransitionTime(time) / length().toDouble();
}
double TransitionBlock::GetOutProgress(const double &time) const
{
if (out_offset() == 0) {
return 0;
}
return std::clamp(1.0 - (GetInternalTransitionTime(time) / out_offset().toDouble()), 0.0, 1.0);
}
double TransitionBlock::GetInProgress(const double &time) const
{
if (in_offset() == 0) {
return 0;
}
return std::clamp((GetInternalTransitionTime(time) - out_offset().toDouble()) / in_offset().toDouble(), 0.0, 1.0);
}
double TransitionBlock::GetInternalTransitionTime(const double &time) const
{
return time;
}
void TransitionBlock::InsertTransitionTimes(AcceleratedJob *job, const double &time) const
{
// Provides total transition progress from 0.0 (start) - 1.0 (end)
job->Insert(QStringLiteral("ove_tprog_all"),
NodeValue(NodeValue::kFloat, GetTotalProgress(time), this));
// Provides progress of out section from 1.0 (start) - 0.0 (end)
job->Insert(QStringLiteral("ove_tprog_out"),
NodeValue(NodeValue::kFloat, GetOutProgress(time), this));
// Provides progress of in section from 0.0 (start) - 1.0 (end)
job->Insert(QStringLiteral("ove_tprog_in"),
NodeValue(NodeValue::kFloat, GetInProgress(time), this));
}
void TransitionBlock::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
NodeValue out_buffer = value[kOutBlockInput];
NodeValue in_buffer = value[kInBlockInput];
NodeValue::Type data_type = (out_buffer.type() != NodeValue::kNone) ? out_buffer.type() : in_buffer.type();
NodeValue::Type job_type = NodeValue::kNone;
QVariant push_job;
if (data_type == NodeValue::kTexture) {
// This must be a visual transition
ShaderJob job;
if (out_buffer.type() != NodeValue::kNone) {
job.Insert(kOutBlockInput, out_buffer);
} else {
job.Insert(kOutBlockInput, NodeValue(NodeValue::kTexture, nullptr));
}
if (in_buffer.type() != NodeValue::kNone) {
job.Insert(kInBlockInput, in_buffer);
} else {
job.Insert(kInBlockInput, NodeValue(NodeValue::kTexture, nullptr));
}
job.Insert(kCurveInput, value);
double time = globals.time().in().toDouble();
InsertTransitionTimes(&job, time);
ShaderJobEvent(value, &job);
job_type = NodeValue::kTexture;
push_job = QVariant::fromValue(Texture::Job(globals.vparams(), job));
} else if (data_type == NodeValue::kSamples) {
// This must be an audio transition
SampleBuffer from_samples = out_buffer.toSamples();
SampleBuffer to_samples = in_buffer.toSamples();
if (from_samples.is_allocated() || to_samples.is_allocated()) {
double time_in = globals.time().in().toDouble();
double time_out = globals.time().out().toDouble();
const AudioParams& params = (from_samples.is_allocated()) ? from_samples.audio_params() : to_samples.audio_params();
SampleBuffer out_samples;
if (params.is_valid()) {
int nb_samples = params.time_to_samples(time_out - time_in);
out_samples = SampleBuffer(params, nb_samples);
SampleJobEvent(from_samples, to_samples, out_samples, time_in);
}
job_type = NodeValue::kSamples;
push_job = QVariant::fromValue(out_samples);
}
}
if (!push_job.isNull()) {
table->Push(job_type, push_job, this);
}
}
void TransitionBlock::InvalidateCache(const TimeRange &range, const QString &from, int element, InvalidateCacheOptions options)
{
TimeRange r = range;
if (from == kOutBlockInput || from == kInBlockInput) {
Block *n = dynamic_cast<Block*>(GetConnectedOutput(from));
if (n) {
r = Track::TransformRangeFromBlock(n, r);
}
}
super::InvalidateCache(r, from, element, options);
}
double TransitionBlock::TransformCurve(double linear) const
{
switch (static_cast<CurveType>(GetStandardValue(kCurveInput).toInt())) {
case kLinear:
break;
case kExponential:
linear *= linear;
break;
case kLogarithmic:
linear = std::sqrt(linear);
break;
}
return linear;
}
void TransitionBlock::InputConnectedEvent(const QString &input, int element, Node *output)
{
Q_UNUSED(element)
if (input == kOutBlockInput) {
// If node is not a block, this will just be null
if ((connected_out_block_ = dynamic_cast<ClipBlock*>(output))) {
connected_out_block_->set_out_transition(this);
}
} else if (input == kInBlockInput) {
// If node is not a block, this will just be null
if ((connected_in_block_ = dynamic_cast<ClipBlock*>(output))) {
connected_in_block_->set_in_transition(this);
}
}
}
void TransitionBlock::InputDisconnectedEvent(const QString &input, int element, Node *output)
{
Q_UNUSED(element)
Q_UNUSED(output)
if (input == kOutBlockInput) {
if (connected_out_block_) {
connected_out_block_->set_out_transition(nullptr);
connected_out_block_ = nullptr;
}
} else if (input == kInBlockInput) {
if (connected_in_block_) {
connected_in_block_->set_in_transition(nullptr);
connected_in_block_ = nullptr;
}
}
}
TimeRange TransitionBlock::InputTimeAdjustment(const QString &input, int element, const TimeRange &input_time, bool clamp) const
{
if (input == kInBlockInput || input == kOutBlockInput) {
Block* block = dynamic_cast<Block*>(GetConnectedOutput(input));
if (block) {
// Retransform time as if it came from the track
return input_time + in() - block->in();
}
}
return super::InputTimeAdjustment(input, element, input_time, clamp);
}
TimeRange TransitionBlock::OutputTimeAdjustment(const QString &input, int element, const TimeRange &input_time) const
{
if (input == kInBlockInput || input == kOutBlockInput) {
Block* block = dynamic_cast<Block*>(GetConnectedOutput(input));
if (block) {
return input_time + block->in() - in();
}
}
return super::OutputTimeAdjustment(input, element, input_time);
}
}
| 9,383
|
C++
|
.cpp
| 249
| 33.983936
| 128
| 0.720917
|
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,022
|
diptocolortransition.cpp
|
olive-editor_olive/app/node/block/transition/diptocolor/diptocolortransition.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 "diptocolortransition.h"
namespace olive {
const QString DipToColorTransition::kColorInput = QStringLiteral("color_in");
#define super TransitionBlock
DipToColorTransition::DipToColorTransition()
{
AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(0, 0, 0)));
}
QString DipToColorTransition::Name() const
{
return tr("Dip To Color");
}
QString DipToColorTransition::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.diptocolor");
}
QVector<Node::CategoryID> DipToColorTransition::Category() const
{
return {kCategoryTransition};
}
QString DipToColorTransition::Description() const
{
return tr("Transition between clips by dipping to a color.");
}
ShaderCode DipToColorTransition::GetShaderCode(const ShaderRequest &request) const
{
Q_UNUSED(request)
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/diptoblack.frag"), QString());
}
void DipToColorTransition::Retranslate()
{
super::Retranslate();
SetInputName(kColorInput, tr("Color"));
}
void DipToColorTransition::ShaderJobEvent(const NodeValueRow &value, ShaderJob *job) const
{
job->Insert(kColorInput, value);
}
}
| 1,866
|
C++
|
.cpp
| 53
| 33
| 93
| 0.791411
|
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,023
|
crossdissolvetransition.cpp
|
olive-editor_olive/app/node/block/transition/crossdissolve/crossdissolvetransition.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 "crossdissolvetransition.h"
namespace olive {
CrossDissolveTransition::CrossDissolveTransition()
{
}
QString CrossDissolveTransition::Name() const
{
return tr("Cross Dissolve");
}
QString CrossDissolveTransition::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.crossdissolve");
}
QVector<Node::CategoryID> CrossDissolveTransition::Category() const
{
return {kCategoryTransition};
}
QString CrossDissolveTransition::Description() const
{
return tr("Smoothly transition between two clips.");
}
ShaderCode CrossDissolveTransition::GetShaderCode(const ShaderRequest &request) const
{
Q_UNUSED(request)
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/crossdissolve.frag"), QString());
}
void CrossDissolveTransition::SampleJobEvent(const SampleBuffer &from_samples, const SampleBuffer &to_samples, SampleBuffer &out_samples, double time_in) const
{
for (size_t i=0; i<out_samples.sample_count(); i++) {
double this_sample_time = out_samples.audio_params().samples_to_time(i).toDouble() + time_in;
double progress = GetTotalProgress(this_sample_time);
for (int j=0; j<out_samples.audio_params().channel_count(); j++) {
out_samples.data(j)[i] = 0;
if (from_samples.is_allocated()) {
if (i < from_samples.sample_count()) {
out_samples.data(j)[i] += from_samples.data(j)[i] * TransformCurve(1.0 - progress);
}
}
if (to_samples.is_allocated()) {
// Offset input samples from the end
size_t remain = (out_samples.sample_count() - to_samples.sample_count());
if (i >= remain) {
qint64 in_index = i - remain;
out_samples.data(j)[i] += to_samples.data(j)[in_index] * TransformCurve(progress);
}
}
}
}
}
}
| 2,493
|
C++
|
.cpp
| 64
| 35.09375
| 159
| 0.726141
|
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,024
|
gap.cpp
|
olive-editor_olive/app/node/block/gap/gap.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 "gap.h"
namespace olive {
GapBlock::GapBlock()
{
}
QString GapBlock::Name() const
{
return tr("Gap");
}
QString GapBlock::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.gap");
}
QString GapBlock::Description() const
{
return tr("A time-based node that represents an empty space.");
}
}
| 1,035
|
C++
|
.cpp
| 32
| 30.03125
| 71
| 0.764884
|
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,025
|
trigonometry.cpp
|
olive-editor_olive/app/node/math/trigonometry/trigonometry.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 "trigonometry.h"
namespace olive {
const QString TrigonometryNode::kMethodIn = QStringLiteral("method_in");
const QString TrigonometryNode::kXIn = QStringLiteral("x_in");
#define super Node
TrigonometryNode::TrigonometryNode()
{
AddInput(kMethodIn, NodeValue::kCombo, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kXIn, NodeValue::kFloat, 0.0);
}
QString TrigonometryNode::Name() const
{
return tr("Trigonometry");
}
QString TrigonometryNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.trigonometry");
}
QVector<Node::CategoryID> TrigonometryNode::Category() const
{
return {kCategoryMath};
}
QString TrigonometryNode::Description() const
{
return tr("Perform a trigonometry operation on a value.");
}
void TrigonometryNode::Retranslate()
{
super::Retranslate();
QStringList strings = {tr("Sine"),
tr("Cosine"),
tr("Tangent"),
QString(),
tr("Inverse Sine"),
tr("Inverse Cosine"),
tr("Inverse Tangent"),
QString(),
tr("Hyperbolic Sine"),
tr("Hyperbolic Cosine"),
tr("Hyperbolic Tangent")};
SetComboBoxStrings(kMethodIn, strings);
SetInputName(kMethodIn, tr("Method"));
SetInputName(kXIn, tr("Value"));
}
void TrigonometryNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
double x = value[kXIn].toDouble();
switch (static_cast<Operation>(GetStandardValue(kMethodIn).toInt())) {
case kOpSine:
x = std::sin(x);
break;
case kOpCosine:
x = std::cos(x);
break;
case kOpTangent:
x = std::tan(x);
break;
case kOpArcSine:
x = std::asin(x);
break;
case kOpArcCosine:
x = std::acos(x);
break;
case kOpArcTangent:
x = std::atan(x);
break;
case kOpHypSine:
x = std::sinh(x);
break;
case kOpHypCosine:
x = std::cosh(x);
break;
case kOpHypTangent:
x = std::tanh(x);
break;
}
table->Push(NodeValue::kFloat, x, this);
}
}
| 2,910
|
C++
|
.cpp
| 93
| 25.795699
| 112
| 0.671321
|
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,026
|
merge.cpp
|
olive-editor_olive/app/node/math/merge/merge.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 "merge.h"
#include "node/traverser.h"
namespace olive {
const QString MergeNode::kBaseIn = QStringLiteral("base_in");
const QString MergeNode::kBlendIn = QStringLiteral("blend_in");
#define super Node
MergeNode::MergeNode()
{
AddInput(kBaseIn, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
AddInput(kBlendIn, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable));
SetFlag(kDontShowInParamView);
}
QString MergeNode::Name() const
{
return tr("Merge");
}
QString MergeNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.merge");
}
QVector<Node::CategoryID> MergeNode::Category() const
{
return {kCategoryMath};
}
QString MergeNode::Description() const
{
return tr("Merge two textures together.");
}
void MergeNode::Retranslate()
{
super::Retranslate();
SetInputName(kBaseIn, tr("Base"));
SetInputName(kBlendIn, tr("Blend"));
}
ShaderCode MergeNode::GetShaderCode(const ShaderRequest &request) const
{
Q_UNUSED(request)
return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/alphaover.frag"));
}
void MergeNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
TexturePtr base_tex = value[kBaseIn].toTexture();
TexturePtr blend_tex = value[kBlendIn].toTexture();
if (base_tex || blend_tex) {
if (!base_tex || (blend_tex && blend_tex->channel_count() < VideoParams::kRGBAChannelCount)) {
// We only have a blend texture or the blend texture is RGB only, no need to alpha over
table->Push(value[kBlendIn]);
} else if (!blend_tex) {
// We only have a base texture, no need to alpha over
table->Push(value[kBaseIn]);
} else {
table->Push(NodeValue::kTexture, base_tex->toJob(ShaderJob(value)), this);
}
}
}
}
| 2,506
|
C++
|
.cpp
| 70
| 32.971429
| 105
| 0.751452
|
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,027
|
mathbase.cpp
|
olive-editor_olive/app/node/math/math/mathbase.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 "math.h"
#include <QMatrix4x4>
#include <QVector2D>
#include "common/tohex.h"
#include "node/distort/transform/transformdistortnode.h"
namespace olive {
ShaderCode MathNodeBase::GetShaderCodeInternal(const QString &shader_id, const QString& param_a_in, const QString& param_b_in) const
{
QStringList code_id = shader_id.split('.');
Operation op = static_cast<Operation>(code_id.at(0).toInt());
Pairing pairing = static_cast<Pairing>(code_id.at(1).toInt());
NodeValue::Type type_a = static_cast<NodeValue::Type>(code_id.at(2).toInt());
NodeValue::Type type_b = static_cast<NodeValue::Type>(code_id.at(3).toInt());
QString operation, frag, vert;
if (pairing == kPairTextureMatrix && op == kOpMultiply) {
// Override the operation for this operation since we multiply texture COORDS by the matrix rather than
const QString& tex_in = (type_a == NodeValue::kTexture) ? param_a_in : param_b_in;
const QString& mat_in = (type_a == NodeValue::kTexture) ? param_b_in : param_a_in;
// No-op frag shader (can we return QString() instead?)
operation = QStringLiteral("texture(%1, ove_texcoord)").arg(tex_in);
vert = QStringLiteral("uniform mat4 %1;\n"
"\n"
"in vec4 a_position;\n"
"in vec2 a_texcoord;\n"
"\n"
"out vec2 ove_texcoord;\n"
"\n"
"void main() {\n"
" gl_Position = %1 * a_position;\n"
" ove_texcoord = a_texcoord;\n"
"}\n").arg(mat_in);
} else {
switch (op) {
case kOpAdd:
operation = QStringLiteral("%1 + %2");
break;
case kOpSubtract:
operation = QStringLiteral("%1 - %2");
break;
case kOpMultiply:
operation = QStringLiteral("%1 * %2");
break;
case kOpDivide:
operation = QStringLiteral("%1 / %2");
break;
case kOpPower:
if (pairing == kPairTextureNumber) {
// The "number" in this operation has to be declared a vec4
if (NodeValue::type_is_numeric(type_a)) {
operation = QStringLiteral("pow(%2, vec4(%1))");
} else {
operation = QStringLiteral("pow(%1, vec4(%2))");
}
} else {
operation = QStringLiteral("pow(%1, %2)");
}
break;
}
operation = operation.arg(GetShaderVariableCall(param_a_in, type_a),
GetShaderVariableCall(param_b_in, type_b));
}
frag = QStringLiteral("uniform %1 %3;\n"
"uniform %2 %4;\n"
"\n"
"in vec2 ove_texcoord;\n"
"out vec4 frag_color;\n"
"\n"
"void main(void) {\n"
" vec4 c = %5;\n"
" c.a = clamp(c.a, 0.0, 1.0);\n" // Ensure alpha is between 0.0 and 1.0
" frag_color = c;\n"
"}\n").arg(GetShaderUniformType(type_a),
GetShaderUniformType(type_b),
param_a_in,
param_b_in,
operation);
return ShaderCode(frag, vert);
}
QString MathNodeBase::GetShaderUniformType(const olive::NodeValue::Type &type)
{
switch (type) {
case NodeValue::kTexture:
return QStringLiteral("sampler2D");
case NodeValue::kColor:
return QStringLiteral("vec4");
case NodeValue::kMatrix:
return QStringLiteral("mat4");
default:
return QStringLiteral("float");
}
}
QString MathNodeBase::GetShaderVariableCall(const QString &input_id, const NodeValue::Type &type, const QString& coord_op)
{
if (type == NodeValue::kTexture) {
return QStringLiteral("texture(%1, ove_texcoord%2)").arg(input_id, coord_op);
}
return input_id;
}
QVector4D MathNodeBase::RetrieveVector(const NodeValue &val)
{
// QVariant doesn't know that QVector*D can convert themselves so we do it here
switch (val.type()) {
case NodeValue::kVec2:
return QVector4D(val.toVec2());
case NodeValue::kVec3:
return QVector4D(val.toVec3());
case NodeValue::kVec4:
default:
return val.toVec4();
}
}
void MathNodeBase::PushVector(NodeValueTable *output, olive::NodeValue::Type type, const QVector4D &vec) const
{
switch (type) {
case NodeValue::kVec2:
output->Push(type, QVector2D(vec), this);
break;
case NodeValue::kVec3:
output->Push(type, QVector3D(vec), this);
break;
case NodeValue::kVec4:
output->Push(type, vec, this);
break;
default:
break;
}
}
QString MathNodeBase::GetOperationName(Operation o)
{
switch (o) {
case kOpAdd: return tr("Add");
case kOpSubtract: return tr("Subtract");
case kOpMultiply: return tr("Multiply");
case kOpDivide: return tr("Divide");
case kOpPower: return tr("Power");
}
return QString();
}
void MathNodeBase::PerformAllOnFloatBuffer(Operation operation, float *a, float b, int start, int end)
{
for (int j=start;j<end;j++) {
a[j] = PerformAll(operation, a[j], b);
}
}
#if defined(Q_PROCESSOR_X86) || defined(Q_PROCESSOR_ARM)
void MathNodeBase::PerformAllOnFloatBufferSSE(Operation operation, float *a, float b, int start, int end)
{
int end_divisible_4 = (end / 4) * 4;
// Load number to multiply by into buffer
__m128 mult = _mm_load1_ps(&b);
switch (operation) {
case kOpAdd:
// Loop all values
for(int j = 0; j < end_divisible_4; j+=4) {
_mm_storeu_ps(a + start + j, _mm_add_ps(_mm_loadu_ps(a + start + j), mult));
}
break;
case kOpSubtract:
for(int j = 0; j < end_divisible_4; j+=4) {
_mm_storeu_ps(a + start + j, _mm_sub_ps(_mm_loadu_ps(a + start + j), mult));
}
break;
case kOpMultiply:
for(int j = 0; j < end_divisible_4; j+=4) {
_mm_storeu_ps(a + start + j, _mm_mul_ps(_mm_loadu_ps(a + start + j), mult));
}
break;
case kOpDivide:
for(int j = 0; j < end_divisible_4; j+=4) {
_mm_storeu_ps(a + start + j, _mm_div_ps(_mm_loadu_ps(a + start + j), mult));
}
break;
case kOpPower:
// Fallback for operations we can't support here
end_divisible_4 = 0;
break;
}
// Handle last 1-3 bytes if necessary, or all bytes if we couldn't
// support this op on SSE
PerformAllOnFloatBuffer(operation, a, b, end_divisible_4, end);
}
#endif
void MathNodeBase::ValueInternal(Operation operation, Pairing pairing, const QString& param_a_in, const NodeValue& val_a, const QString& param_b_in, const NodeValue& val_b, const NodeGlobals &globals, NodeValueTable *output) const
{
switch (pairing) {
case kPairNumberNumber:
{
if (val_a.type() == NodeValue::kRational && val_b.type() == NodeValue::kRational && operation != kOpPower) {
// Preserve rationals
output->Push(NodeValue::kRational,
QVariant::fromValue(PerformAddSubMultDiv<rational, rational>(operation, val_a.toRational(), val_b.toRational())),
this);
} else {
output->Push(NodeValue::kFloat,
PerformAll<float, float>(operation, RetrieveNumber(val_a), RetrieveNumber(val_b)),
this);
}
break;
}
case kPairVecVec:
{
// We convert all vectors to QVector4D just for simplicity and exploit the fact that kVec4 is higher than kVec2 in
// the enum to find the largest data type
PushVector(output,
qMax(val_a.type(), val_b.type()),
PerformAddSubMultDiv<QVector4D, QVector4D>(operation, RetrieveVector(val_a), RetrieveVector(val_b)));
break;
}
case kPairMatrixVec:
{
QMatrix4x4 matrix = (val_a.type() == NodeValue::kMatrix) ? val_a.toMatrix() : val_b.toMatrix();
QVector4D vec = (val_a.type() == NodeValue::kMatrix) ? RetrieveVector(val_b) : RetrieveVector(val_a);
// Only valid operation is multiply
PushVector(output,
qMax(val_a.type(), val_b.type()),
PerformMult<QVector4D, QMatrix4x4>(operation, vec, matrix));
break;
}
case kPairVecNumber:
{
QVector4D vec = (NodeValue::type_is_vector(val_a.type()) ? RetrieveVector(val_a) : RetrieveVector(val_b));
float number = RetrieveNumber((val_a.type() & NodeValue::kMatrix) ? val_b : val_a);
// Only multiply and divide are valid operations
PushVector(output, val_a.type(), PerformMultDiv<QVector4D, float>(operation, vec, number));
break;
}
case kPairMatrixMatrix:
{
QMatrix4x4 mat_a = val_a.toMatrix();
QMatrix4x4 mat_b = val_b.toMatrix();
output->Push(NodeValue::kMatrix, PerformAddSubMult<QMatrix4x4, QMatrix4x4>(operation, mat_a, mat_b), this);
break;
}
case kPairColorColor:
{
Color col_a = val_a.toColor();
Color col_b = val_b.toColor();
// Only add and subtract are valid operations
output->Push(NodeValue::kColor, QVariant::fromValue(PerformAddSub<Color, Color>(operation, col_a, col_b)), this);
break;
}
case kPairNumberColor:
{
Color col = (val_a.type() == NodeValue::kColor) ? val_a.toColor() : val_b.toColor();
float num = (val_a.type() == NodeValue::kColor) ? val_b.toDouble() : val_a.toDouble();
// Only multiply and divide are valid operations
output->Push(NodeValue::kColor, QVariant::fromValue(PerformMult<Color, float>(operation, col, num)), this);
break;
}
case kPairSampleSample:
{
SampleBuffer samples_a = val_a.toSamples();
SampleBuffer samples_b = val_b.toSamples();
size_t max_samples = qMax(samples_a.sample_count(), samples_b.sample_count());
size_t min_samples = qMin(samples_a.sample_count(), samples_b.sample_count());
SampleBuffer mixed_samples = SampleBuffer(samples_a.audio_params(), max_samples);
for (int i=0;i<mixed_samples.audio_params().channel_count();i++) {
// Mix samples that are in both buffers
for (size_t j=0;j<min_samples;j++) {
mixed_samples.data(i)[j] = PerformAll<float, float>(operation, samples_a.data(i)[j], samples_b.data(i)[j]);
}
}
if (max_samples > min_samples) {
// Fill in remainder space with 0s
size_t remainder = max_samples - min_samples;
const SampleBuffer &larger_buffer = (max_samples == samples_a.sample_count()) ? samples_a : samples_b;
for (int i=0;i<mixed_samples.audio_params().channel_count();i++) {
memcpy(&mixed_samples.data(i)[min_samples],
&larger_buffer.data(i)[min_samples],
remainder * sizeof(float));
}
}
output->Push(NodeValue::kSamples, QVariant::fromValue(mixed_samples), this);
break;
}
case kPairTextureColor:
case kPairTextureNumber:
case kPairTextureTexture:
case kPairTextureMatrix:
{
ShaderJob job;
job.SetShaderID(QStringLiteral("%1.%2.%3.%4").arg(QString::number(operation),
QString::number(pairing),
QString::number(val_a.type()),
QString::number(val_b.type())));
job.Insert(param_a_in, val_a);
job.Insert(param_b_in, val_b);
bool operation_is_noop = false;
const NodeValue& number_val = val_a.type() == NodeValue::kTexture ? val_b : val_a;
const NodeValue& texture_val = val_a.type() == NodeValue::kTexture ? val_a : val_b;
TexturePtr texture = texture_val.toTexture();
if (!texture) {
operation_is_noop = true;
} else if (pairing == kPairTextureNumber) {
if (NumberIsNoOp(operation, RetrieveNumber(number_val))) {
operation_is_noop = true;
}
} else if (pairing == kPairTextureMatrix) {
// Only allow matrix multiplication
const QVector2D &sequence_res = globals.nonsquare_resolution();
QVector2D texture_res(texture->params().width() * texture->pixel_aspect_ratio().toDouble(), texture->params().height());
QMatrix4x4 adjusted_matrix = TransformDistortNode::AdjustMatrixByResolutions(number_val.toMatrix(),
sequence_res,
texture->params().offset(),
texture_res);
if (operation != kOpMultiply || adjusted_matrix.isIdentity()) {
operation_is_noop = true;
} else {
// Replace with adjusted matrix
job.Insert(val_a.type() == NodeValue::kTexture ? param_b_in : param_a_in,
NodeValue(NodeValue::kMatrix, adjusted_matrix, this));
}
}
if (operation_is_noop) {
// Just push texture as-is
output->Push(texture_val);
} else {
// Push shader job
output->Push(NodeValue::kTexture, Texture::Job(globals.vparams(), job), this);
}
break;
}
case kPairSampleNumber:
{
// Queue a sample job
const NodeValue& number_val = val_a.type() == NodeValue::kSamples ? val_b : val_a;
const QString& number_param = val_a.type() == NodeValue::kSamples ? param_b_in : param_a_in;
float number = RetrieveNumber(number_val);
SampleBuffer buffer = val_a.type() == NodeValue::kSamples ? val_a.toSamples() : val_b.toSamples();
if (buffer.is_allocated()) {
if (IsInputStatic(number_param)) {
if (!NumberIsNoOp(operation, number)) {
for (int i=0;i<buffer.audio_params().channel_count();i++) {
#if defined(Q_PROCESSOR_X86) || defined(Q_PROCESSOR_ARM)
// Use SSE instructions for optimization
PerformAllOnFloatBufferSSE(operation, buffer.data(i), number, 0, buffer.sample_count());
#else
PerformAllOnFloatBuffer(operation, buffer.data(i), number, 0, buffer.sample_count());
#endif
}
}
output->Push(NodeValue::kSamples, QVariant::fromValue(buffer), this);
} else {
SampleJob job(globals.time(), val_a.type() == NodeValue::kSamples ? val_a : val_b);
job.Insert(number_param, NodeValue(NodeValue::kFloat, number, this));
output->Push(NodeValue::kSamples, QVariant::fromValue(job), this);
}
}
break;
}
case kPairNone:
case kPairCount:
break;
}
}
void MathNodeBase::ProcessSamplesInternal(const NodeValueRow &values, MathNodeBase::Operation operation, const QString ¶m_a_in, const QString ¶m_b_in, const olive::SampleBuffer &input, olive::SampleBuffer &output, int index) const
{
// This function is only used for sample+number pairing
NodeValue number_val = values[param_a_in];
if (number_val.type() == NodeValue::kNone) {
number_val = values[param_b_in];
if (number_val.type() == NodeValue::kNone) {
return;
}
}
float number_flt = RetrieveNumber(number_val);
for (int i=0;i<output.audio_params().channel_count();i++) {
output.data(i)[index] = PerformAll<float, float>(operation, input.data(i)[index], number_flt);
}
}
float MathNodeBase::RetrieveNumber(const NodeValue &val)
{
if (val.type() == NodeValue::kRational) {
return val.toRational().toDouble();
} else {
return val.toDouble();
}
}
bool MathNodeBase::NumberIsNoOp(const MathNodeBase::Operation &op, const float &number)
{
switch (op) {
case kOpAdd:
case kOpSubtract:
if (qIsNull(number)) {
return true;
}
break;
case kOpMultiply:
case kOpDivide:
case kOpPower:
if (qFuzzyCompare(number, 1.0f)) {
return true;
}
break;
}
return false;
}
MathNodeBase::PairingCalculator::PairingCalculator(const NodeValueTable &table_a, const NodeValueTable &table_b)
{
QVector<int> pair_likelihood_a = GetPairLikelihood(table_a);
QVector<int> pair_likelihood_b = GetPairLikelihood(table_b);
int weight_a = qMax(0, table_b.Count() - table_a.Count());
int weight_b = qMax(0, table_a.Count() - table_b.Count());
QVector<int> likelihoods(kPairCount);
for (int i=0;i<kPairCount;i++) {
if (pair_likelihood_a.at(i) == -1 || pair_likelihood_b.at(i) == -1) {
likelihoods.replace(i, -1);
} else {
likelihoods.replace(i, pair_likelihood_a.at(i) + weight_a + pair_likelihood_b.at(i) + weight_b);
}
}
most_likely_pairing_ = kPairNone;
for (int i=0;i<likelihoods.size();i++) {
if (likelihoods.at(i) > -1) {
if (most_likely_pairing_ == kPairNone
|| likelihoods.at(i) > likelihoods.at(most_likely_pairing_)) {
most_likely_pairing_ = static_cast<Pairing>(i);
}
}
}
if (most_likely_pairing_ != kPairNone) {
most_likely_value_a_ = table_a.at(pair_likelihood_a.at(most_likely_pairing_));
most_likely_value_b_ = table_b.at(pair_likelihood_b.at(most_likely_pairing_));
}
}
QVector<int> MathNodeBase::PairingCalculator::GetPairLikelihood(const NodeValueTable &table)
{
QVector<int> likelihood(kPairCount, -1);
for (int i=0;i<table.Count();i++) {
NodeValue::Type type = table.at(i).type();
int weight = i;
if (NodeValue::type_is_vector(type)) {
likelihood.replace(kPairVecVec, weight);
likelihood.replace(kPairVecNumber, weight);
likelihood.replace(kPairMatrixVec, weight);
} else if (type == NodeValue::kMatrix) {
likelihood.replace(kPairMatrixMatrix, weight);
likelihood.replace(kPairMatrixVec, weight);
likelihood.replace(kPairTextureMatrix, weight);
} else if (type == NodeValue::kColor) {
likelihood.replace(kPairColorColor, weight);
likelihood.replace(kPairNumberColor, weight);
likelihood.replace(kPairTextureColor, weight);
} else if (NodeValue::type_is_numeric(type)) {
likelihood.replace(kPairNumberNumber, weight);
likelihood.replace(kPairVecNumber, weight);
likelihood.replace(kPairNumberColor, weight);
likelihood.replace(kPairTextureNumber, weight);
likelihood.replace(kPairSampleNumber, weight);
} else if (type == NodeValue::kSamples) {
likelihood.replace(kPairSampleSample, weight);
likelihood.replace(kPairSampleNumber, weight);
} else if (type == NodeValue::kTexture) {
likelihood.replace(kPairTextureTexture, weight);
likelihood.replace(kPairTextureNumber, weight);
likelihood.replace(kPairTextureColor, weight);
likelihood.replace(kPairTextureMatrix, weight);
}
}
return likelihood;
}
bool MathNodeBase::PairingCalculator::FoundMostLikelyPairing() const
{
return (most_likely_pairing_ > kPairNone && most_likely_pairing_ < kPairCount);
}
MathNodeBase::Pairing MathNodeBase::PairingCalculator::GetMostLikelyPairing() const
{
return most_likely_pairing_;
}
const NodeValue &MathNodeBase::PairingCalculator::GetMostLikelyValueA() const
{
return most_likely_value_a_;
}
const NodeValue &MathNodeBase::PairingCalculator::GetMostLikelyValueB() const
{
return most_likely_value_b_;
}
template<typename T, typename U>
T MathNodeBase::PerformAll(Operation operation, T a, U b)
{
switch (operation) {
case kOpAdd:
return a + b;
case kOpSubtract:
return a - b;
case kOpMultiply:
return a * b;
case kOpDivide:
return a / b;
case kOpPower:
return std::pow(a, b);
}
return a;
}
template<typename T, typename U>
T MathNodeBase::PerformMultDiv(Operation operation, T a, U b)
{
switch (operation) {
case kOpMultiply:
return a * b;
case kOpDivide:
return a / b;
case kOpAdd:
case kOpSubtract:
case kOpPower:
break;
}
return a;
}
template<typename T, typename U>
T MathNodeBase::PerformAddSub(Operation operation, T a, U b)
{
switch (operation) {
case kOpAdd:
return a + b;
case kOpSubtract:
return a - b;
case kOpMultiply:
case kOpDivide:
case kOpPower:
break;
}
return a;
}
template<typename T, typename U>
T MathNodeBase::PerformMult(Operation operation, T a, U b)
{
switch (operation) {
case kOpMultiply:
return a * b;
case kOpAdd:
case kOpSubtract:
case kOpDivide:
case kOpPower:
break;
}
return a;
}
template<typename T, typename U>
T MathNodeBase::PerformAddSubMult(Operation operation, T a, U b)
{
switch (operation) {
case kOpAdd:
return a + b;
case kOpSubtract:
return a - b;
case kOpMultiply:
return a * b;
case kOpDivide:
case kOpPower:
break;
}
return a;
}
template<typename T, typename U>
T MathNodeBase::PerformAddSubMultDiv(Operation operation, T a, U b)
{
switch (operation) {
case kOpAdd:
return a + b;
case kOpSubtract:
return a - b;
case kOpMultiply:
return a * b;
case kOpDivide:
return a / b;
case kOpPower:
break;
}
return a;
}
}
| 21,366
|
C++
|
.cpp
| 586
| 30.230375
| 238
| 0.644515
|
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,028
|
math.cpp
|
olive-editor_olive/app/node/math/math/math.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 "math.h"
namespace olive {
const QString MathNode::kMethodIn = QStringLiteral("method_in");
const QString MathNode::kParamAIn = QStringLiteral("param_a_in");
const QString MathNode::kParamBIn = QStringLiteral("param_b_in");
const QString MathNode::kParamCIn = QStringLiteral("param_c_in");
#define super MathNodeBase
MathNode::MathNode()
{
AddInput(kMethodIn, NodeValue::kCombo, InputFlags(kInputFlagNotConnectable | kInputFlagNotKeyframable));
AddInput(kParamAIn, NodeValue::kFloat, 0.0);
SetInputProperty(kParamAIn, QStringLiteral("decimalplaces"), 8);
SetInputProperty(kParamAIn, QStringLiteral("autotrim"), true);
AddInput(kParamBIn, NodeValue::kFloat, 0.0);
SetInputProperty(kParamBIn, QStringLiteral("decimalplaces"), 8);
SetInputProperty(kParamBIn, QStringLiteral("autotrim"), true);
}
QString MathNode::Name() const
{
// Default to naming after the operation
if (parent()) {
QString op_name = GetOperationName(GetOperation());
if (!op_name.isEmpty()) {
return op_name;
}
}
return tr("Math");
}
QString MathNode::id() const
{
return QStringLiteral("org.olivevideoeditor.Olive.math");
}
QVector<Node::CategoryID> MathNode::Category() const
{
return {kCategoryMath};
}
QString MathNode::Description() const
{
return tr("Perform a mathematical operation between two values.");
}
void MathNode::Retranslate()
{
super::Retranslate();
SetInputName(kMethodIn, tr("Method"));
SetInputName(kParamAIn, tr("Value"));
SetInputName(kParamBIn, tr("Value"));
QStringList operations = {GetOperationName(kOpAdd),
GetOperationName(kOpSubtract),
GetOperationName(kOpMultiply),
GetOperationName(kOpDivide),
QString(),
GetOperationName(kOpPower)};
SetComboBoxStrings(kMethodIn, operations);
}
ShaderCode MathNode::GetShaderCode(const ShaderRequest &request) const
{
return GetShaderCodeInternal(request.id, kParamAIn, kParamBIn);
}
void MathNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const
{
// Auto-detect what values to operate with
// FIXME: Very inefficient
NodeValueTable at, bt;
at.Push(value[kParamAIn]);
bt.Push(value[kParamBIn]);
PairingCalculator calc(at, bt);
// Do nothing if no pairing was found
if (!calc.FoundMostLikelyPairing()) {
return;
}
return ValueInternal(GetOperation(),
calc.GetMostLikelyPairing(),
kParamAIn,
calc.GetMostLikelyValueA(),
kParamBIn,
calc.GetMostLikelyValueB(),
globals,
table);
}
void MathNode::ProcessSamples(const NodeValueRow &values, const SampleBuffer &input, SampleBuffer &output, int index) const
{
return ProcessSamplesInternal(values, GetOperation(), kParamAIn, kParamBIn, input, output, index);
}
}
| 3,711
|
C++
|
.cpp
| 98
| 32.397959
| 123
| 0.712214
|
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,029
|
draggable.cpp
|
olive-editor_olive/app/node/gizmo/draggable.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 "draggable.h"
namespace olive {
DraggableGizmo::DraggableGizmo(QObject *parent)
: NodeGizmo{parent},
drag_value_behavior_(kAbsolute)
{
}
void DraggableGizmo::DragStart(const NodeValueRow &row, double abs_x, double abs_y, const rational &time)
{
for (int i=0; i<draggers_.size(); i++) {
draggers_[i].Start(inputs_[i], time);
}
emit HandleStart(row, abs_x, abs_y, time);
}
void DraggableGizmo::DragMove(double x, double y, const Qt::KeyboardModifiers &modifiers)
{
emit HandleMovement(x, y, modifiers);
}
void DraggableGizmo::DragEnd(MultiUndoCommand *command)
{
for (int i=0; i<draggers_.size(); i++) {
draggers_[i].End(command);
}
}
}
| 1,389
|
C++
|
.cpp
| 39
| 33
| 105
| 0.747195
|
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,030
|
polygon.cpp
|
olive-editor_olive/app/node/gizmo/polygon.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 "polygon.h"
namespace olive {
PolygonGizmo::PolygonGizmo(QObject *parent)
: DraggableGizmo{parent}
{
}
void PolygonGizmo::Draw(QPainter *p) const
{
// Draw transposed black
QPolygonF transposed = p->transform().map(polygon_);
transposed.translate(1, 1);
transposed = p->transform().inverted().map(transposed);
p->setPen(QPen(Qt::black, 0));
p->drawPolyline(transposed);
// Draw normal white polygon
p->setPen(QPen(Qt::white, 0));
p->setBrush(Qt::NoBrush);
p->drawPolyline(polygon_);
}
}
| 1,235
|
C++
|
.cpp
| 34
| 33.647059
| 71
| 0.752101
|
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,031
|
point.cpp
|
olive-editor_olive/app/node/gizmo/point.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 "point.h"
#include <QApplication>
namespace olive {
PointGizmo::PointGizmo(const Shape &shape, bool smaller, QObject *parent) :
DraggableGizmo{parent},
shape_(shape),
smaller_(smaller)
{
}
PointGizmo::PointGizmo(const Shape &shape, QObject *parent) :
PointGizmo(shape, false, parent)
{
}
PointGizmo::PointGizmo(QObject *parent) :
PointGizmo(kSquare, parent)
{
}
void PointGizmo::Draw(QPainter *p) const
{
QRectF rect = GetDrawingRect(p->transform(), GetStandardRadius());
if (shape_ != kAnchorPoint) {
p->setPen(QPen(Qt::black, 0));
p->setBrush(Qt::white);
}
switch (shape_) {
case kSquare:
p->drawRect(rect);
break;
case kCircle:
p->drawEllipse(rect);
break;
case kAnchorPoint:
p->setPen(QPen(Qt::white, 0));
p->setBrush(Qt::NoBrush);
p->drawEllipse(rect);
p->drawLines({QPointF(rect.left(), rect.center().y()),
QPointF(rect.right(), rect.center().y()),
QPointF(rect.center().x(), rect.top()),
QPointF(rect.center().x(), rect.bottom())});
break;
}
}
QRectF PointGizmo::GetClickingRect(const QTransform &t) const
{
return GetDrawingRect(t, GetStandardRadius());
}
double PointGizmo::GetStandardRadius()
{
return QFontMetrics(qApp->font()).height() * 0.25;
}
QRectF PointGizmo::GetDrawingRect(const QTransform &transform, double radius) const
{
QRectF r(0,0, radius, radius);
r = transform.inverted().mapRect(r);
double width = r.width();
double height = r.height();
if (shape_ == kAnchorPoint) {
width *= 2;
height *= 2;
}
if (smaller_) {
width *= 0.5;
height *= 0.5;
}
return QRectF(point_.x() - width,
point_.y() - height,
2*width,
2*height);
}
}
| 2,498
|
C++
|
.cpp
| 84
| 25.666667
| 83
| 0.681172
|
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,032
|
gizmo.cpp
|
olive-editor_olive/app/node/gizmo/gizmo.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 "gizmo.h"
namespace olive {
NodeGizmo::NodeGizmo(QObject *parent) :
visible_(true)
{
setParent(parent);
}
NodeGizmo::~NodeGizmo()
{
setParent(nullptr);
}
}
| 887
|
C++
|
.cpp
| 26
| 31.576923
| 71
| 0.766157
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.