build: split the engine into liboakengine.so; worker drops the UI entirely

Physical split: app/{audio,cli,codec,common,config,node,pluginSupport,
render,task,timeline,undo,tool,shaders} plus coreengine, version and
ui/icons+colorcoding move to a new top-level engine/ tree, built as
liboakengine.so (shared). The render backends (oakgl/oakvulkan) move
with it and link the engine library instead of embedding a static
render-core subset (libolive-rendercore is gone).

- oak-render-worker now links liboakengine instead of the whole
  libolive-editor object set: 336MB -> 2.9MB, no Qt Widgets UI
- the editor links liboakengine for the engine and keeps only UI
  objects in libolive-editor
- install/packaging: GNUInstallDirs libdir on Linux, bundle copy on
  macOS, oakengine.dll staged for NSIS, AppImage validation entry
- fix backend lookup for the new layout: DynamicRenderer searched
  ../app but backends now live in engine/; a stale pre-split liboakgl
  in the build tree got dlopened instead, re-initialized and later
  destroyed the interposed engine statics (full-suite segfault at
  DialogSequenceParameterTab, found via gdb watchpoint)
This commit is contained in:
2026-07-20 03:23:28 +08:00
parent 026ff94b5e
commit 28c4426236
604 changed files with 243 additions and 172 deletions
+31
View File
@@ -0,0 +1,31 @@
# 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/>.
add_subdirectory(conform)
add_subdirectory(customcache)
add_subdirectory(export)
add_subdirectory(precache)
add_subdirectory(project)
add_subdirectory(proxy)
add_subdirectory(render)
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/task.h
task/taskmanager.h
task/taskmanager.cpp
PARENT_SCOPE
)
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/conform/conform.h
task/conform/conform.cpp
PARENT_SCOPE
)
+62
View File
@@ -0,0 +1,62 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "conform.h"
namespace olive
{
ConformTask::ConformTask(const QString &decoder_id,
const Decoder::CodecStream &stream,
const AudioParams &params,
const QVector<QString> &output_filenames)
: decoder_id_(decoder_id)
, stream_(stream)
, params_(params)
, output_filenames_(output_filenames)
{
set_title(tr("Conforming Audio %1:%2")
.arg(stream.filename(), QString::number(stream.stream())));
}
bool ConformTask::run()
{
DecoderPtr decoder = Decoder::create_from_id(decoder_id_);
if (!decoder->open(stream_)) {
set_error(tr("Failed to open decoder for audio conform"));
return false;
}
connect(decoder.get(), &Decoder::index_progress, this,
&ConformTask::progress_changed);
qDebug() << "Starting conform of" << stream_.filename() << stream_.stream();
bool ret =
decoder->conform_audio(output_filenames_, params_, get_cancel_atom());
decoder->close();
return ret;
}
}
+54
View File
@@ -0,0 +1,54 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_CONFORMTASK_H
#define OAK_CONFORMTASK_H
#include "codec/decoder.h"
#include "node/project/footage/footage.h"
#include "task/task.h"
namespace olive
{
class ConformTask : public Task {
Q_OBJECT
public:
ConformTask(const QString &decoder_id, const Decoder::CodecStream &stream,
const AudioParams &params,
const QVector<QString> &output_filenames);
protected:
virtual bool run() override;
private:
QString decoder_id_;
Decoder::CodecStream stream_;
AudioParams params_;
QVector<QString> output_filenames_;
};
}
#endif // OAK_CONFORMTASK_H
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/customcache/customcachetask.cpp
task/customcache/customcachetask.h
PARENT_SCOPE
)
@@ -0,0 +1,64 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "customcachetask.h"
namespace olive
{
CustomCacheTask::CustomCacheTask(const QString &sequence_name)
: cancelled_through_finish_(false)
{
set_title(tr("Caching custom range for \"%1\"").arg(sequence_name));
}
void CustomCacheTask::finish()
{
mutex_.lock();
cancelled_through_finish_ = true;
Cancel();
mutex_.unlock();
}
bool CustomCacheTask::run()
{
mutex_.lock();
while (!is_cancelled()) {
wait_cond_.wait(&mutex_);
}
mutex_.unlock();
return true;
}
void CustomCacheTask::CancelEvent()
{
if (!cancelled_through_finish_) {
emit cancelled();
}
wait_cond_.wakeOne();
}
}
+58
View File
@@ -0,0 +1,58 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_CUSTOMCACHETASK_H
#define OAK_CUSTOMCACHETASK_H
#include <QMutex>
#include <QWaitCondition>
#include "task/task.h"
namespace olive
{
class CustomCacheTask : public Task {
Q_OBJECT
public:
CustomCacheTask(const QString &sequence_name);
void finish();
signals:
void cancelled();
protected:
virtual bool run() override;
virtual void CancelEvent() override;
private:
QMutex mutex_;
QWaitCondition wait_cond_;
bool cancelled_through_finish_;
};
}
#endif // OAK_CUSTOMCACHETASK_H
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/export/export.h
task/export/export.cpp
PARENT_SCOPE
)
+298
View File
@@ -0,0 +1,298 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "export.h"
#include "node/color/colormanager/colormanager.h"
namespace olive
{
ExportTask::ExportTask(ViewerOutput *viewer_node, ColorManager *color_manager,
const EncodingParams &params)
: params_(params)
{
// Create a copy of the project
copier_ = new ProjectCopier(this);
copier_->set_project(viewer_node->project());
set_viewer(copier_->get_copy(viewer_node));
color_manager_ = copier_->get_copied_project()->color_manager();
// Adjust video params to have no divider
VideoParams vp = viewer_node->get_video_params();
vp.set_divider(1);
vp.set_time_base(params.video_params().time_base());
vp.set_frame_rate(params.video_params().frame_rate());
set_video_params(vp);
set_audio_params(viewer_node->get_audio_params());
set_title(tr("Exporting \"%1\"").arg(viewer_node->get_label()));
set_native_progress_signalling_enabled(false);
}
bool ExportTask::run()
{
// For safety, if we're overwriting, we save to a temporary filename and then only overwrite it
// at the end
QString real_filename = params_.filename();
if (QFileInfo::exists(params_.filename())) {
// Generate a filename that definitely doesn't exist
params_.set_filename(
FileFunctions::get_safe_temporary_filename(real_filename));
}
// If we're exporting to a sidecar subtitle file, disable the subtitles in the main encoder
bool subtitles_enabled = params_.subtitles_enabled();
EncodingParams sidecar_params = params_;
if (subtitles_enabled && params_.subtitles_are_sidecar()) {
params_.disable_subtitles();
}
encoder_ = std::shared_ptr<Encoder>(Encoder::create_from_params(params_));
if (!encoder_) {
set_error(tr("Failed to create encoder"));
return false;
}
if (!encoder_->open()) {
set_error(tr("Failed to open file: %1").arg(encoder_->get_error()));
return false;
}
if (subtitles_enabled && params_.subtitles_are_sidecar()) {
// Construct sidecar params
sidecar_params.disable_video();
sidecar_params.disable_audio();
QString sidecar_filename;
{
QFileInfo fi(real_filename);
sidecar_filename = fi.completeBaseName();
sidecar_filename.append('.');
sidecar_filename.append(ExportFormat::get_extension(
sidecar_params.subtitle_sidecar_fmt()));
sidecar_filename = fi.dir().filePath(sidecar_filename);
}
sidecar_params.set_filename(sidecar_filename);
subtitle_encoder_ = std::shared_ptr<Encoder>(Encoder::create_from_format(
sidecar_params.subtitle_sidecar_fmt(), sidecar_params));
if (!subtitle_encoder_) {
set_error(tr("Failed to create subtitle encoder"));
return false;
}
if (!subtitle_encoder_->open()) {
set_error(tr("Failed to open subtitle sidecar file: %1")
.arg(sidecar_filename));
return false;
}
} else {
subtitle_encoder_ = encoder_;
}
if (params_.has_custom_range()) {
// Render custom range only
export_range_ = params_.custom_range();
} else {
// Render entire sequence
export_range_ = TimeRange(0, viewer()->get_length());
}
frame_time_ = 0;
QSize video_force_size;
QMatrix4x4 video_force_matrix;
if (params_.video_enabled()) {
// If a transformation matrix is applied to this video, create it here
if (video_params().width() != params_.video_params().width() ||
video_params().height() != params_.video_params().height()) {
video_force_size = QSize(params_.video_params().width(),
params_.video_params().height());
if (params_.video_scaling_method() != EncodingParams::k_stretch) {
video_force_matrix = EncodingParams::generate_matrix(
params_.video_scaling_method(), video_params().width(),
video_params().height(), params_.video_params().width(),
params_.video_params().height());
}
} else {
// Disables forcing size in the renderer
video_force_size = QSize(0, 0);
}
// Create color processor
color_processor_ = ColorProcessor::create(
color_manager_, color_manager_->get_reference_color_space(),
params_.color_transform());
}
// Start render process
TimeRangeList video_range, audio_range;
TimeRange subtitle_range;
if (params_.video_enabled()) {
if (export_range_.in() > 0) {
export_range_.set_in(Timecode::snap_time_to_timebase(
export_range_.in(), video_params().frame_rate_as_time_base()));
}
video_range = { export_range_ };
}
if (params_.audio_enabled()) {
audio_range = { export_range_ };
}
if (subtitles_enabled) {
subtitle_range = export_range_;
}
render(color_manager_, video_range, audio_range, subtitle_range,
RenderMode::k_online, nullptr, video_force_size, video_force_matrix,
encoder_->get_desired_pixel_format(), VideoParams::k_rgba_channel_count,
color_processor_, params_.color_transform());
bool success = true;
encoder_->close();
if (!encoder_->get_error().isEmpty()) {
set_error(encoder_->get_error());
success = false;
}
if (subtitle_encoder_ != encoder_) {
subtitle_encoder_->close();
if (!subtitle_encoder_->get_error().isEmpty()) {
set_error(subtitle_encoder_->get_error());
success = false;
}
}
// If cancelled, delete the file we made, which is always a file we created since we write to a
// temp file during the actual encoding process
if (is_cancelled()) {
QFile::remove(params_.filename());
} else if (params_.filename() != real_filename) {
// If we were writing to a temp file, overwrite now
if (!FileFunctions::rename_file_allow_overwrite(params_.filename(),
real_filename)) {
set_error(
tr("Failed to overwrite \"%1\". Export has been saved as \"%2\" instead.")
.arg(real_filename, params_.filename()));
success = false;
}
}
return success;
}
bool ExportTask::frame_downloaded(FramePtr f, const Rational &time)
{
Rational actual_time = time - export_range_.in();
time_map_.insert(actual_time, f);
while (!is_cancelled()) {
Rational real_time = Timecode::timestamp_to_time(
frame_time_, video_params().frame_rate_as_time_base());
if (!time_map_.contains(real_time)) {
break;
}
// Unfortunately this can't be done in another thread since the frames need to be sent
// one after the other chronologically.
if (!encoder_->write_frame(time_map_.take(real_time), real_time)) {
set_error(encoder_->get_error());
return false;
}
frame_time_++;
emit progress_changed(double(frame_time_) /
double(get_total_number_of_frames()));
}
return true;
}
bool ExportTask::audio_downloaded(const TimeRange &range,
const SampleBuffer &samples)
{
TimeRange adjusted_range = range - export_range_.in();
if (adjusted_range.in() == audio_time_) {
if (!write_audio_loop(adjusted_range, samples)) {
return false;
}
} else {
audio_map_.insert(adjusted_range, samples);
}
return true;
}
bool ExportTask::encode_subtitle(const SubtitleBlock *sub)
{
if (!subtitle_encoder_->write_subtitle(sub)) {
set_error(subtitle_encoder_->get_error());
return false;
} else {
return true;
}
}
bool ExportTask::write_audio_loop(const TimeRange &time,
const SampleBuffer &samples)
{
if (!encoder_->write_audio(samples)) {
set_error(encoder_->get_error());
return false;
}
audio_time_ = time.out();
for (auto it = audio_map_.begin(); it != audio_map_.end(); it++) {
TimeRange t = it.key();
SampleBuffer s = it.value();
if (t.in() == audio_time_) {
// Erase from audio map since we're just about to write it
audio_map_.erase(it);
// Call recursively to write the next sample buffer
if (!write_audio_loop(t, s)) {
return false;
}
// Break out of loop
break;
}
}
return true;
}
}
+84
View File
@@ -0,0 +1,84 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_EXPORTTASK_H
#define OAK_EXPORTTASK_H
#include "codec/encoder.h"
#include "node/output/viewer/viewer.h"
#include "render/colorprocessor.h"
#include "render/projectcopier.h"
#include "task/render/render.h"
#include "task/task.h"
namespace olive
{
class ExportTask : public RenderTask {
Q_OBJECT
public:
ExportTask(ViewerOutput *viewer_node, ColorManager *color_manager,
const EncodingParams &params);
protected:
virtual bool run() override;
virtual bool frame_downloaded(FramePtr frame, const Rational &time) override;
virtual bool audio_downloaded(const TimeRange &range,
const SampleBuffer &samples) override;
virtual bool encode_subtitle(const SubtitleBlock *sub) override;
virtual bool two_step_frame_rendering() const override
{
return false;
}
private:
bool write_audio_loop(const TimeRange &time, const SampleBuffer &samples);
ProjectCopier *copier_;
QHash<Rational, FramePtr> time_map_;
QHash<TimeRange, SampleBuffer> audio_map_;
ColorManager *color_manager_;
EncodingParams params_;
std::shared_ptr<Encoder> encoder_;
std::shared_ptr<Encoder> subtitle_encoder_;
ColorProcessorPtr color_processor_;
int64_t frame_time_;
Rational audio_time_;
TimeRange export_range_;
};
}
#endif // OAK_EXPORTTASK_H
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/precache/precachetask.h
task/precache/precachetask.cpp
PARENT_SCOPE
)
+113
View File
@@ -0,0 +1,113 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "precachetask.h"
#include "node/project.h"
namespace olive
{
PreCacheTask::PreCacheTask(Footage *footage, int index, Sequence *sequence)
{
// Set video and audio params
set_video_params(sequence->get_video_params());
set_audio_params(sequence->get_audio_params());
// Create new project
project_ = new Project();
// Create viewer with same parameters as the sequence
set_viewer(new ViewerOutput());
viewer()->setParent(project_);
viewer()->set_video_params(sequence->get_video_params());
viewer()->set_audio_params(sequence->get_audio_params());
// Copy project config nodes
Project::copy_settings(footage->project(), project_);
// Copy footage node so it can precache without any modifications from the user screwing it up
footage_ = static_cast<Footage *>(footage->copy());
footage_->setParent(project_);
Node::copy_inputs(footage, footage_, false);
Node::connect_edge(footage_,
NodeInput(viewer(), ViewerOutput::k_texture_input));
viewer()->set_value_hint_for_input(
ViewerOutput::k_texture_input,
Node::ValueHint({ NodeValue::k_texture },
Track::Reference(Track::k_video, index).to_string()));
set_title(tr("Pre-caching %1:%2")
.arg(footage_->filename(), QString::number(index)));
}
PreCacheTask::~PreCacheTask()
{
// This should delete the footage we copied and the viewer we created
delete project_;
}
bool PreCacheTask::run()
{
// Get list of invalidated ranges
TimeRange intersection;
if (footage_->get_work_area()->enabled()) {
// If we're caching only in-out, limit the range to that
intersection = footage_->get_work_area()->range();
} else {
// Otherwise use full length
intersection = TimeRange(0, footage_->get_video_length());
}
TimeRangeList video_range =
viewer()->video_frame_cache()->get_invalidated_ranges(intersection);
render(project_->color_manager(), video_range, TimeRangeList(), TimeRange(),
RenderMode::k_online, viewer()->video_frame_cache());
return true;
}
bool PreCacheTask::frame_downloaded(FramePtr frame, const Rational &time)
{
// Do nothing. Pre-cache essentially just creates more frames in the cache, it doesn't need to do
// anything else.
Q_UNUSED(frame)
Q_UNUSED(time)
return true;
}
bool PreCacheTask::audio_downloaded(const TimeRange &range,
const SampleBuffer &samples)
{
// Pre-cache doesn't cache any audio
Q_UNUSED(range)
Q_UNUSED(samples)
return true;
}
}
+56
View File
@@ -0,0 +1,56 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PRECACHETASK_H
#define OAK_PRECACHETASK_H
#include "node/project/footage/footage.h"
#include "node/project/sequence/sequence.h"
#include "task/render/render.h"
namespace olive
{
class PreCacheTask : public RenderTask {
Q_OBJECT
public:
PreCacheTask(Footage *footage, int index, Sequence *sequence);
virtual ~PreCacheTask() override;
protected:
virtual bool run() override;
virtual bool frame_downloaded(FramePtr frame,
const Rational &times) override;
virtual bool audio_downloaded(const TimeRange &range,
const SampleBuffer &samples) override;
private:
Project *project_;
Footage *footage_;
};
}
#endif // OAK_PRECACHETASK_H
+29
View File
@@ -0,0 +1,29 @@
# 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/>.
if (OpenTimelineIO_FOUND)
add_subdirectory(loadotio)
add_subdirectory(saveotio)
endif ()
add_subdirectory(import)
add_subdirectory(load)
add_subdirectory(save)
set(OLIVE_SOURCES
${OLIVE_SOURCES}
PARENT_SCOPE
)
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/project/import/import.h
task/project/import/import.cpp
PARENT_SCOPE
)
+302
View File
@@ -0,0 +1,302 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "import.h"
#include <QDir>
#include <QFileInfo>
#include "config/config.h"
#include "coreengine.h"
#include "node/nodeundo.h"
#include "node/project/footage/footage.h"
namespace olive
{
ProjectImportTask::ProjectImportTask(Folder *folder,
const QStringList &filenames)
: command_(nullptr)
, folder_(folder)
{
foreach (const QString &f, filenames) {
filenames_.append(QFileInfo(f));
}
file_count_ = EngineCore::count_files_in_file_list(filenames_);
set_title(tr("Importing %n file(s)", nullptr, file_count_));
}
const int &ProjectImportTask::get_file_count() const
{
return file_count_;
}
bool ProjectImportTask::run()
{
command_ = new MultiUndoCommand();
int imported = 0;
import(folder_, filenames_, imported, command_);
if (is_cancelled()) {
delete command_;
command_ = nullptr;
return false;
} else {
return true;
}
}
void ProjectImportTask::import(Folder *folder, QFileInfoList entries,
int &counter, MultiUndoCommand *parent_command)
{
for (int i = 0; i < entries.size(); i++) {
if (is_cancelled()) {
break;
}
const QFileInfo &file_info = entries.at(i);
// Check if this file is a directory
if (file_info.isDir()) {
// QDir::entryList only returns filenames, we can use entryInfoList() to get full paths
QFileInfoList entry_list =
QDir(file_info.absoluteFilePath()).entryInfoList();
// Strip out "." and ".." (for some reason QDir::NoDotAndDotDot doesn't work with entryInfoList, so we have to
// check manually)
for (int j = 0; j < entry_list.size(); j++) {
if (entry_list.at(j).fileName() == QStringLiteral(".") ||
entry_list.at(j).fileName() == QStringLiteral("..")) {
entry_list.removeAt(j);
j--;
}
}
// Only proceed if the empty actually has files in it
if (!entry_list.isEmpty()) {
// Create a folder corresponding to the directory
Folder *f = new Folder();
f->set_label(file_info.fileName());
// Create undoable command that adds the items to the model
add_item_to_folder(folder, f, parent_command);
// Recursively follow this path
import(f, entry_list, counter, parent_command);
}
} else {
Footage *footage = new Footage();
footage->set_cancel_pointer(this->get_cancel_atom());
footage->set_filename(file_info.absoluteFilePath());
footage->set_label(file_info.fileName());
footage->set_cancel_pointer(nullptr);
if (footage->is_valid()) {
// See if this footage is an image sequence
validate_image_sequence(footage, entries, i);
// Create undoable command that adds the items to the model
add_item_to_folder(folder, footage, parent_command);
// Add to vector
imported_footage_.push_back(footage);
} else {
// Add to list so we can tell the user about it later
invalid_files_.append(file_info.absoluteFilePath());
delete footage;
}
counter++;
emit progress_changed(static_cast<double>(counter) /
static_cast<double>(file_count_));
}
}
}
void ProjectImportTask::validate_image_sequence(Footage *footage,
QFileInfoList &info_list,
int index)
{
// Heuristically determine whether this file is part of an image sequence or not
//
// By this point we've established that video contains a single still image stream. Now we'll
// see if it ends with numbers.
if (Decoder::get_image_sequence_digit_count(footage->filename()) > 0 &&
!image_sequence_ignore_files_.contains(footage->filename()) &&
footage->input_array_size(Footage::k_video_params_input)) {
VideoParams video_stream = footage->get_video_params(0);
QSize dim(video_stream.width(), video_stream.height());
int64_t ind = Decoder::get_image_sequence_index(footage->filename());
// Check if files around exist around it with that follow a sequence
QString previous_img_fn = Decoder::transform_image_sequence_file_name(
footage->filename(), ind - 1);
QString next_img_fn = Decoder::transform_image_sequence_file_name(
footage->filename(), ind + 1);
Footage *previous_file = new Footage(previous_img_fn);
Footage *next_file = new Footage(next_img_fn);
// Finally see if these files have the same dimensions
if ((previous_file->is_valid() &&
compare_still_image_size(previous_file, dim)) ||
(next_file->is_valid() && compare_still_image_size(next_file, dim))) {
// By this point, we've established this file is a still image with a number at the end of
// the filename surrounded by adjacent numbers. It could be a still image! But let's ask the
// user just in case...
bool is_sequence;
QMetaObject::invokeMethod(EngineCore::instance(), "confirm_image_sequence",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, is_sequence),
Q_ARG(QString, footage->filename()));
int64_t seq_index =
Decoder::get_image_sequence_index(footage->filename());
// Heuristic to find the first and last images (users can always override this later in
// FootagePropertiesDialog)
int64_t start_index =
get_image_sequence_limit(footage->filename(), seq_index, false);
int64_t end_index =
get_image_sequence_limit(footage->filename(), seq_index, true);
// Depending on the user's choice, either remove them from the list or don't ask for the
// remainders
for (int64_t j = start_index; j <= end_index; j++) {
QString entry_fn = Decoder::transform_image_sequence_file_name(
footage->filename(), j);
if (is_sequence) {
// If this is part of the sequence we're importing here, remove it
for (int i = index + 1; i < info_list.size(); i++) {
if (info_list.at(i).absoluteFilePath() == entry_fn) {
if (is_sequence) {
info_list.removeAt(i);
}
break;
}
}
} else {
image_sequence_ignore_files_.append(entry_fn);
}
}
if (is_sequence) {
// User has confirmed it is a still image, let's set it accordingly.
video_stream.set_video_type(
VideoParams::k_video_type_image_sequence);
Rational default_timebase =
OAK_CONFIG("DefaultSequenceFrameRate").value<Rational>();
video_stream.set_time_base(default_timebase);
video_stream.set_frame_rate(default_timebase.flipped());
video_stream.set_start_time(start_index);
video_stream.set_duration(end_index - start_index + 1);
footage->set_video_params(video_stream, 0);
}
}
delete previous_file;
delete next_file;
}
}
void ProjectImportTask::add_item_to_folder(Folder *folder, Node *item,
MultiUndoCommand *command)
{
// Create undoable command that adds the items to the model
Project *project = folder_->project();
NodeAddCommand *nac = new NodeAddCommand(project, item);
nac->push_to_thread(project->thread());
command->add_child(nac);
command->add_child(new FolderAddChild(folder, item));
}
bool ProjectImportTask::item_is_still_image_footage_only(Footage *footage)
{
if (footage->get_total_stream_count() != 1) {
// Footage with more than one stream (usually video+audio) most likely isn't an image sequence
return false;
}
VideoParams vp = footage->get_video_params(0);
// Footage must be valid and video stream must be a still image to be an image sequence
return vp.is_valid() && vp.video_type() == VideoParams::k_video_type_still;
}
bool ProjectImportTask::compare_still_image_size(Footage *footage, const QSize &sz)
{
if (!item_is_still_image_footage_only(footage)) {
return false;
}
VideoParams stream = footage->get_video_params(0);
return stream.width() == sz.width() && stream.height() == sz.height();
}
int64_t ProjectImportTask::get_image_sequence_limit(const QString &start_fn,
int64_t start, bool up)
{
QString test_filename;
int test_index;
forever
{
if (up) {
test_index = start + 1;
} else {
test_index = start - 1;
}
test_filename =
Decoder::transform_image_sequence_file_name(start_fn, test_index);
if (!QFileInfo::exists(test_filename)) {
// Reached end of index
break;
}
start = test_index;
}
return start;
}
}
+99
View File
@@ -0,0 +1,99 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PROJECTIMPORTMANAGER_H
#define OAK_PROJECTIMPORTMANAGER_H
#include <QFileInfoList>
#include <QUndoCommand>
#include "codec/decoder.h"
#include "node/project/footage/footage.h"
#include "node/project/folder/folder.h"
#include "task/task.h"
namespace olive
{
class ProjectImportTask : public Task {
Q_OBJECT
public:
ProjectImportTask(Folder *folder, const QStringList &filenames);
const int &get_file_count() const;
MultiUndoCommand *get_command() const
{
return command_;
}
const QStringList &get_invalid_files() const
{
return invalid_files_;
}
bool has_invalid_files() const
{
return !invalid_files_.isEmpty();
}
const QVector<Footage *> &get_imported_footage() const
{
return imported_footage_;
}
protected:
virtual bool run() override;
private:
void import(Folder *folder, QFileInfoList entries, int &counter,
MultiUndoCommand *parent_command);
void validate_image_sequence(Footage *footage, QFileInfoList &info_list,
int index);
void add_item_to_folder(Folder *folder, Node *item, MultiUndoCommand *command);
static bool item_is_still_image_footage_only(Footage *footage);
static bool compare_still_image_size(Footage *footage, const QSize &sz);
static int64_t get_image_sequence_limit(const QString &start_fn, int64_t start,
bool up);
MultiUndoCommand *command_;
Folder *folder_;
QFileInfoList filenames_;
int file_count_;
QStringList invalid_files_;
QList<QString> image_sequence_ignore_files_;
QVector<Footage *> imported_footage_;
};
}
#endif // OAK_PROJECTIMPORTMANAGER_H
+24
View File
@@ -0,0 +1,24 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/project/load/load.h
task/project/load/load.cpp
task/project/load/loadbasetask.h
task/project/load/loadbasetask.cpp
PARENT_SCOPE
)
+90
View File
@@ -0,0 +1,90 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "load.h"
#include <QApplication>
#include "node/project/serializer/serializer.h"
namespace olive
{
ProjectLoadTask::ProjectLoadTask(const QString &filename)
: ProjectLoadBaseTask(filename)
{
}
bool ProjectLoadTask::run()
{
project_ = new Project();
project_->set_filename(get_filename());
ProjectSerializer::Result result = ProjectSerializer::load(
project_, get_filename(), ProjectSerializer::k_project);
layout_ = result.get_load_data().layout;
switch (result.code()) {
case ProjectSerializer::k_success:
break;
case ProjectSerializer::k_project_too_old:
set_error(tr(
"This project is from a version of Oak Video Editor that is no longer supported in this version."));
break;
case ProjectSerializer::k_project_too_new:
set_error(tr(
"This project is from a newer version of Oak Video Editor and cannot be opened in this version."));
break;
case ProjectSerializer::k_unknown_version:
set_error(tr("Failed to determine project version."));
break;
case ProjectSerializer::k_file_error:
set_error(
tr("Failed to read file \"%1\" for reading.").arg(get_filename()));
break;
case ProjectSerializer::k_xml_error:
set_error(
tr("Failed to read XML document. File may be corrupt. Error was: %1")
.arg(result.get_details()));
break;
case ProjectSerializer::k_no_data:
set_error(tr("Failed to find any data to parse."));
break;
// Errors that should never be thrown by a load
case ProjectSerializer::k_overwrite_error:
set_error(tr("Unknown error."));
break;
}
if (result == ProjectSerializer::k_success) {
project_->moveToThread(qApp->thread());
return true;
} else {
delete project_;
project_ = nullptr;
return false;
}
}
}
+42
View File
@@ -0,0 +1,42 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PROJECTLOADMANAGER_H
#define OAK_PROJECTLOADMANAGER_H
#include "loadbasetask.h"
#include "node/project/serializer/mainwindowlayoutinfo.h"
namespace olive
{
class ProjectLoadTask : public ProjectLoadBaseTask {
Q_OBJECT
public:
ProjectLoadTask(const QString &filename);
protected:
virtual bool run() override;
};
}
#endif // OAK_PROJECTLOADMANAGER_H
+34
View File
@@ -0,0 +1,34 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "loadbasetask.h"
namespace olive
{
ProjectLoadBaseTask::ProjectLoadBaseTask(const QString &filename)
: project_(nullptr)
, filename_(filename)
{
set_title(tr("Loading '%1'").arg(filename));
}
}
+63
View File
@@ -0,0 +1,63 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PROJECTLOADBASETASK_H
#define OAK_PROJECTLOADBASETASK_H
#include "node/project.h"
#include "node/project/serializer/mainwindowlayoutinfo.h"
#include "task/task.h"
namespace olive
{
class ProjectLoadBaseTask : public Task {
Q_OBJECT
public:
ProjectLoadBaseTask(const QString &filename);
Project *get_loaded_project() const
{
return project_;
}
const QString &get_filename() const
{
return filename_;
}
const MainWindowLayoutInfo &get_loaded_layout() const
{
return layout_;
}
protected:
Project *project_;
MainWindowLayoutInfo layout_;
private:
QString filename_;
};
}
#endif // LOADBASETASK_H
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/project/loadotio/loadotio.h
task/project/loadotio/loadotio.cpp
PARENT_SCOPE
)
+378
View File
@@ -0,0 +1,378 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "loadotio.h"
#ifdef USE_OTIO
#include <opentimelineio/clip.h>
#include <opentimelineio/externalReference.h>
#include <opentimelineio/gap.h>
#include <opentimelineio/serializableCollection.h>
#include <opentimelineio/timeline.h>
#include <opentimelineio/transition.h>
#include <QApplication>
#include <QFileInfo>
#include <QThread>
#include "coreengine.h"
#include "node/audio/volume/volume.h"
#include "node/block/clip/clip.h"
#include "node/block/gap/gap.h"
#include "node/block/transition/crossdissolve/crossdissolvetransition.h"
#include "node/distort/transform/transformdistortnode.h"
#include "node/generator/matrix/matrix.h"
#include "node/math/math/math.h"
#include "node/nodeundo.h"
#include "node/project/folder/folder.h"
#include "node/project/footage/footage.h"
#include "node/project/sequence/sequence.h"
#include "timeline/timelineundogeneral.h"
#include "window/mainwindow/mainwindowundo.h"
namespace olive
{
LoadOTIOTask::LoadOTIOTask(const QString &s)
: ProjectLoadBaseTask(s)
{
}
bool LoadOTIOTask::Run()
{
OTIO::ErrorStatus es;
auto root = OTIO::SerializableObjectWithMetadata::from_json_file(
GetFilename().toStdString(), &es);
if (es.outcome != OTIO::ErrorStatus::Outcome::OK) {
SetError(
tr("Failed to load OpenTimelineIO from file \"%1\" \n\nOpenTimelineIO Error:\n\n%2")
.arg(GetFilename(),
QString::fromStdString(es.full_description)));
return false;
}
project_ = new Project();
project_->Initialize();
project_->set_modified(true);
std::vector<OTIO::Timeline *> timelines;
if (root->schema_name() == "SerializableCollection") {
// This is a number of timelines
std::vector<OTIO::SerializableObject::Retainer<OTIO::SerializableObject>>
&root_children =
static_cast<OTIO::SerializableCollection *>(root)->children();
timelines.resize(root_children.size());
for (size_t j = 0; j < root_children.size(); j++) {
timelines[j] =
static_cast<OTIO::Timeline *>(root_children[j].value);
}
} else if (root->schema_name() == "Timeline") {
// This is a single timeline
timelines.push_back(static_cast<OTIO::Timeline *>(root));
} else {
// Unknown root, we don't know what to do with this
SetError(tr("Unknown OpenTimelineIO root element"));
delete project_;
project_ = nullptr;
return false;
}
// Keep track of imported footage
QMap<QString, Footage *> imported_footage;
QMap<OTIO::Timeline *, Sequence *> timeline_sequnce_map;
// Variables used for loading bar
float number_of_clips = 0;
float clips_done = 0;
// Generate a list of sequences with the same names as the timelines.
// Assumes each timeline has a unique name.
int unnamed_sequence_count = 0;
foreach (auto timeline, timelines) {
Sequence *sequence = new Sequence();
if (!timeline->name().empty()) {
sequence->SetLabel(QString::fromStdString(timeline->name()));
} else {
// If the otio timeline does not provide a name, create a default one here
unnamed_sequence_count++;
QString label = tr("Sequence %1").arg(unnamed_sequence_count);
sequence->SetLabel(QString::fromStdString(label.toStdString()));
}
// Set default params incase they aren't edited.
sequence->set_default_parameters();
timeline_sequnce_map.insert(timeline, sequence);
// Get number of clips for loading bar
foreach (auto track, timeline->tracks()->children()) {
auto otio_track = static_cast<OTIO::Track *>(track.value);
number_of_clips += otio_track->children().size();
}
}
// Dialog has to be called from the main thread so we pass the list of sequences here.
bool accepted = false;
QMetaObject::invokeMethod(
EngineCore::instance(), "show_otio_import_dialog", Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, accepted),
Q_ARG(QList<Sequence *>, timeline_sequnce_map.values()));
if (!accepted) {
// Cancel to indicate to caller that this task did not complete and to simply dispose of it
Cancel();
qDeleteAll(timeline_sequnce_map); // Clear sequences
return true;
}
foreach (auto timeline, timeline_sequnce_map.keys()) {
Sequence *sequence = timeline_sequnce_map.value(timeline);
sequence->setParent(project_);
FolderAddChild(project_->root(), sequence).redo_now();
// Create a folder for this sequence's footage
Folder *sequence_footage = new Folder();
sequence_footage->SetLabel(QString::fromStdString(timeline->name()));
sequence_footage->setParent(project_);
FolderAddChild(project_->root(), sequence_footage).redo_now();
// Iterate through tracks
for (auto c : timeline->tracks()->children()) {
auto otio_track = static_cast<OTIO::Track *>(c.value);
// Create a new track
Track *track = nullptr;
// Determine what kind of track it is
if (otio_track->kind() == "Video" ||
otio_track->kind() == "Audio") {
Track::Type type;
if (otio_track->kind() == "Video") {
type = Track::kVideo;
} else {
type = Track::kAudio;
}
// Create track
TimelineAddTrackCommand t(sequence->track_list(type));
t.redo_now();
track = t.track();
} else {
qWarning() << "Found unknown track type:"
<< otio_track->kind().c_str();
continue;
}
// Get clips from track
auto clip_map = otio_track->children();
if (es.outcome != OTIO::ErrorStatus::Outcome::OK) {
SetError(tr("Failed to load clip"));
return false;
}
Block *previous_block = nullptr;
bool prev_block_transition = false;
for (auto otio_block_retainer : clip_map) {
auto otio_block = otio_block_retainer.value;
Block *block = nullptr;
if (otio_block->schema_name() == "Clip") {
block = new ClipBlock();
} else if (otio_block->schema_name() == "Gap") {
block = new GapBlock();
} else if (otio_block->schema_name() == "Transition") {
// Todo: Look into OTIO supported transitions and add them to Olive
block = new CrossDissolveTransition();
} else {
// We don't know what this is yet, just create a gap for now so that *something* is there
qWarning() << "Found unknown block type:"
<< otio_block->schema_name().c_str();
block = new GapBlock();
}
block->setParent(project_);
block->SetLabel(QString::fromStdString(otio_block->name()));
track->AppendBlock(block);
Rational start_time;
Rational duration;
if (otio_block->schema_name() == "Clip" ||
otio_block->schema_name() == "Gap") {
start_time = Rational::fromDouble(
static_cast<OTIO::Item *>(otio_block)
->source_range()
->start_time()
.to_seconds());
duration = Rational::fromDouble(
static_cast<OTIO::Item *>(otio_block)
->source_range()
->duration()
.to_seconds());
if (otio_block->schema_name() == "Clip") {
static_cast<ClipBlock *>(block)->set_media_in(
start_time);
}
block->set_length_and_media_out(duration);
}
// If the previous block was a transition, connect the current block to it
if (prev_block_transition) {
TransitionBlock *previous_transition_block =
static_cast<TransitionBlock *>(previous_block);
Node::ConnectEdge(
block, NodeInput(previous_transition_block,
TransitionBlock::kInBlockInput));
prev_block_transition = false;
}
if (otio_block->schema_name() == "Transition") {
TransitionBlock *transition_block =
static_cast<TransitionBlock *>(block);
OTIO::Transition *otio_block_transition =
static_cast<OTIO::Transition *>(otio_block);
// Set how far the transition eats into the previous clip
transition_block->set_offsets_and_length(
Rational::fromRationalTime(
otio_block_transition->in_offset()),
Rational::fromRationalTime(
otio_block_transition->out_offset()));
if (previous_block) {
Node::ConnectEdge(
previous_block,
NodeInput(transition_block,
TransitionBlock::kOutBlockInput));
}
prev_block_transition = true;
// Add nodes to the graph and set up contexts
block->setParent(sequence->parent());
// Position transition in its own context
block->SetNodePositionInContext(block, QPointF(0, 0));
}
if (otio_block->schema_name() == "Gap") {
// Add nodes to the graph and set up contexts
block->setParent(sequence->parent());
// Position transition in its own context
block->SetNodePositionInContext(block, QPointF(0, 0));
}
// Update this after it's used but before any continue statements
previous_block = block;
if (otio_block->schema_name() == "Clip") {
auto otio_clip = static_cast<OTIO::Clip *>(otio_block);
if (!otio_clip->media_reference()) {
continue;
}
if (otio_clip->media_reference()->schema_name() ==
"ExternalReference") {
// Link footage
QString footage_url = QString::fromStdString(
static_cast<OTIO::ExternalReference *>(
otio_clip->media_reference())
->target_url());
Footage *probed_item;
if (imported_footage.contains(footage_url)) {
probed_item = imported_footage.value(footage_url);
} else {
probed_item = new Footage(footage_url);
imported_footage.insert(footage_url, probed_item);
probed_item->setParent(project_);
QFileInfo info(probed_item->filename());
probed_item->SetLabel(info.fileName());
FolderAddChild add(sequence_footage, probed_item);
add.redo_now();
}
// Add nodes to the graph and set up contexts
block->setParent(sequence->parent());
// Position clip in its own context
block->SetNodePositionInContext(block, QPointF(0, 0));
// Position footage in its context
block->SetNodePositionInContext(probed_item,
QPointF(-2, 0));
if (track->type() == Track::kVideo) {
TransformDistortNode *transform =
new TransformDistortNode();
transform->setParent(sequence->parent());
Node::ConnectEdge(
probed_item,
NodeInput(transform,
TransformDistortNode::kTextureInput));
Node::ConnectEdge(transform,
NodeInput(block,
ClipBlock::kBufferIn));
block->SetNodePositionInContext(transform,
QPointF(-1, 0));
} else {
VolumeNode *volume_node = new VolumeNode();
volume_node->setParent(sequence->parent());
Node::ConnectEdge(
probed_item,
NodeInput(volume_node,
VolumeNode::kSamplesInput));
Node::ConnectEdge(volume_node,
NodeInput(block,
ClipBlock::kBufferIn));
block->SetNodePositionInContext(volume_node,
QPointF(-1, 0));
}
}
}
clips_done++;
emit ProgressChanged(clips_done / number_of_clips);
}
}
}
project_->moveToThread(qApp->thread());
return true;
}
}
#endif // USE_OTIO
+47
View File
@@ -0,0 +1,47 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_OTIODECODER_H
#define OAK_OTIODECODER_H
#ifdef USE_OTIO
#include "common/otioutils.h"
#include "node/project.h"
#include "task/project/load/loadbasetask.h"
namespace olive
{
class LoadOTIOTask : public ProjectLoadBaseTask {
Q_OBJECT
public:
LoadOTIOTask(const QString &filename);
protected:
virtual bool Run() override;
};
}
#endif
#endif // OAK_OTIODECODER_H
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/project/save/save.h
task/project/save/save.cpp
PARENT_SCOPE
)
+88
View File
@@ -0,0 +1,88 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "save.h"
#include <QDir>
#include <QFile>
#include <QXmlStreamWriter>
#include "common/filefunctions.h"
#include "node/project/serializer/serializer.h"
namespace olive
{
ProjectSaveTask::ProjectSaveTask(Project *project, bool use_compression)
: project_(project)
, use_compression_(use_compression)
{
set_title(tr("Saving '%1'").arg(project->filename()));
}
bool ProjectSaveTask::run()
{
QString using_filename = override_filename_.isEmpty() ?
project_->filename() :
override_filename_;
ProjectSerializer::SaveData data(ProjectSerializer::k_project);
data.set_filename(using_filename);
data.set_project(project_);
data.set_layout(layout_);
ProjectSerializer::Result result =
ProjectSerializer::save(data, use_compression_);
bool success = false;
switch (result.code()) {
case ProjectSerializer::k_success:
success = true;
break;
case ProjectSerializer::k_xml_error:
set_error(tr("Failed to write XML data."));
break;
case ProjectSerializer::k_file_error:
set_error(tr("Failed to open file \"%1\" for writing.")
.arg(result.get_details()));
break;
case ProjectSerializer::k_overwrite_error:
set_error(
tr("Failed to overwrite \"%1\". Project has been saved as \"%2\" instead.")
.arg(using_filename, result.get_details()));
success = true;
break;
// Errors that should never be thrown by a save
case ProjectSerializer::k_project_too_new:
case ProjectSerializer::k_project_too_old:
case ProjectSerializer::k_unknown_version:
case ProjectSerializer::k_no_data:
set_error(tr("Unknown error."));
break;
}
return success;
}
}
+67
View File
@@ -0,0 +1,67 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PROJECTSAVEMANAGER_H
#define OAK_PROJECTSAVEMANAGER_H
#include "node/project.h"
#include "node/project/serializer/mainwindowlayoutinfo.h"
#include "task/task.h"
namespace olive
{
class ProjectSaveTask : public Task {
Q_OBJECT
public:
ProjectSaveTask(Project *project, bool use_compression);
Project *get_project() const
{
return project_;
}
void set_override_filename(const QString &filename)
{
override_filename_ = filename;
}
void set_layout(const MainWindowLayoutInfo &layout)
{
layout_ = layout;
}
protected:
virtual bool run() override;
private:
Project *project_;
QString override_filename_;
bool use_compression_;
MainWindowLayoutInfo layout_;
};
}
#endif // OAK_PROJECTSAVEMANAGER_H
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/project/saveotio/saveotio.h
task/project/saveotio/saveotio.cpp
PARENT_SCOPE
)
+278
View File
@@ -0,0 +1,278 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "saveotio.h"
#ifdef USE_OTIO
#include <opentimelineio/clip.h>
#include <opentimelineio/externalReference.h>
#include <opentimelineio/gap.h>
#include <opentimelineio/serializableCollection.h>
#include <opentimelineio/serializableObject.h>
#include <opentimelineio/transition.h>
#include "node/block/clip/clip.h"
#include "node/block/gap/gap.h"
#include "node/block/transition/transition.h"
#include "node/project/footage/footage.h"
namespace olive
{
SaveOTIOTask::SaveOTIOTask(Project *project)
: project_(project)
{
SetTitle(tr("Exporting project to OpenTimelineIO"));
}
bool SaveOTIOTask::Run()
{
QVector<Sequence *> sequences =
project_->root()->ListChildrenOfType<Sequence>();
if (sequences.isEmpty()) {
SetError(tr("Project contains no sequences to export."));
return false;
}
std::vector<OTIO::SerializableObject *> serialized;
foreach (Sequence *seq, sequences) {
auto otio_timeline = SerializeTimeline(seq);
if (otio_timeline) {
// Append to list
serialized.push_back(otio_timeline);
} else {
// Delete all existing timelines
foreach (auto s, serialized) {
s->possibly_delete();
}
// Error out of function
SetError(
tr("Failed to serialize sequence \"%1\"").arg(seq->GetLabel()));
return false;
}
}
OTIO::ErrorStatus es;
if (serialized.size() == 1) {
// Serialize timeline on its own
auto t = serialized.front();
t->to_json_file(project_->filename().toStdString(), &es);
t->possibly_delete();
} else {
// Serialize all into a SerializableCollection
auto collection =
new OTIO::SerializableCollection("Sequences", serialized);
collection->to_json_file(project_->filename().toStdString(), &es);
collection->possibly_delete();
// Delete all existing timelines
foreach (auto s, serialized) {
s->possibly_delete();
}
}
return (es.outcome == OTIO::ErrorStatus::Outcome::OK);
}
OTIO::Timeline *SaveOTIOTask::SerializeTimeline(Sequence *sequence)
{
auto otio_timeline = new OTIO::Timeline(sequence->GetLabel().toStdString());
// Retainers clean themselves up when the final user is removed
OTIO::Timeline::Retainer<OTIO::Timeline> *timeline_retainer =
new OTIO::Timeline::Retainer<OTIO::Timeline>(otio_timeline);
// Suppress unused variable warning
Q_UNUSED(timeline_retainer);
double rate = sequence->GetVideoParams().frame_rate().toDouble();
if (qIsNaN(rate)) {
return nullptr;
}
if (!SerializeTrackList(sequence->track_list(Track::kVideo), otio_timeline,
rate) ||
!SerializeTrackList(sequence->track_list(Track::kAudio), otio_timeline,
rate)) {
otio_timeline->possibly_delete();
return nullptr;
}
return otio_timeline;
}
OTIO::Track *SaveOTIOTask::SerializeTrack(Track *track, double sequence_rate,
Rational max_track_length)
{
auto otio_track = new OTIO::Track();
OTIO::ErrorStatus es;
switch (track->type()) {
case Track::kVideo:
otio_track->set_kind("Video");
break;
case Track::kAudio:
otio_track->set_kind("Audio");
break;
default:
qWarning()
<< "Don't know OTIO track kind for native type" << track->type();
goto fail;
}
foreach (Block *block, track->Blocks()) {
OTIO::Composable *otio_block = nullptr;
if (dynamic_cast<ClipBlock *>(block)) {
auto otio_clip = new OTIO::Clip(block->GetLabel().toStdString());
otio_clip->set_source_range(
OTIO::TimeRange(block->in().toRationalTime(sequence_rate),
block->length().toRationalTime(sequence_rate)));
QVector<Footage *> media_nodes = block->FindInputNodes<Footage>();
if (!media_nodes.isEmpty()) {
OTIO::TimeRange available_range;
if (otio_track->kind().compare("Video") == 0) {
// OTIO ExternalReference uses the source clips frame rate (or sample rate) as opposed to
// the sequences rate
double source_frame_rate = static_cast<ClipBlock *>(block)
->connected_viewer()
->GetVideoParams()
.frame_rate()
.toDouble();
available_range = OTIO::TimeRange(
OTIO::RationalTime(0, source_frame_rate),
OTIO::RationalTime(
media_nodes.first()->GetVideoParams().duration(),
source_frame_rate));
} else if (otio_track->kind().compare("Audio") == 0) {
available_range = OTIO::TimeRange(
OTIO::RationalTime(
0,
media_nodes.first()->GetAudioParams().sample_rate()),
OTIO::RationalTime(
media_nodes.first()->GetAudioParams().duration(),
media_nodes.first()->GetAudioParams().sample_rate()));
}
auto media_ref = new OTIO::ExternalReference(
media_nodes.first()->filename().toStdString(),
available_range);
otio_clip->set_media_reference(media_ref);
}
otio_block = otio_clip;
} else if (dynamic_cast<GapBlock *>(block)) {
otio_block =
new OTIO::Gap(OTIO::TimeRange(block->in().toRationalTime(),
block->length().toRationalTime()),
block->GetLabel().toStdString());
} else if (dynamic_cast<TransitionBlock *>(block)) {
auto otio_transition =
new OTIO::Transition(block->GetLabel().toStdString());
TransitionBlock *our_transition =
static_cast<TransitionBlock *>(block);
otio_transition->set_in_offset(
our_transition->in_offset().toRationalTime());
otio_transition->set_out_offset(
our_transition->out_offset().toRationalTime());
otio_block = new OTIO::Transition();
}
if (!otio_block) {
// We shouldn't ever get here, but catch without crashing if we ever do
goto fail;
}
otio_track->append_child(otio_block, &es);
if (es.outcome != OTIO::ErrorStatus::Outcome::OK) {
goto fail;
}
}
// All OTIO tracks must have the same duration so we add a Gap to fill the remaining time
if (otio_track->duration(&es).to_seconds() < max_track_length.toDouble()) {
double time_left = max_track_length.toDouble() -
otio_track->duration(&es).to_seconds();
OTIO::Gap *gap = new OTIO::Gap(OTIO::TimeRange(
otio_track->duration(&es), OTIO::RationalTime(time_left, 1.0)));
otio_track->append_child(gap, &es);
if (es.outcome != OTIO::ErrorStatus::Outcome::OK) {
goto fail;
}
}
return otio_track;
fail:
otio_track->possibly_delete();
return nullptr;
}
bool SaveOTIOTask::SerializeTrackList(TrackList *list,
OTIO::Timeline *otio_timeline,
double sequence_rate)
{
OTIO::ErrorStatus es;
Rational max_track_length = RATIONAL_MIN;
foreach (Track *track, list->GetTracks()) {
if (track->track_length() > max_track_length) {
max_track_length = track->track_length();
}
}
foreach (Track *track, list->GetTracks()) {
auto otio_track =
SerializeTrack(track, sequence_rate, max_track_length);
if (!otio_track) {
return false;
}
otio_timeline->tracks()->append_child(otio_track, &es);
if (es.outcome != OTIO::ErrorStatus::Outcome::OK) {
otio_track->possibly_delete();
return false;
}
}
return true;
}
}
#endif // USE_OTIO
+61
View File
@@ -0,0 +1,61 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_PROJECTSAVEASOTIOTASK_H
#define OAK_PROJECTSAVEASOTIOTASK_H
#ifdef USE_OTIO
#include <opentimelineio/timeline.h>
#include <opentimelineio/track.h>
#include "common/otioutils.h"
#include "node/project.h"
#include "task/task.h"
namespace olive
{
class SaveOTIOTask : public Task {
Q_OBJECT
public:
SaveOTIOTask(Project *project);
protected:
virtual bool Run() override;
private:
OTIO::Timeline *SerializeTimeline(Sequence *sequence);
OTIO::Track *SerializeTrack(Track *track, double sequence_rate,
Rational max_track_length);
bool SerializeTrackList(TrackList *list, OTIO::Timeline *otio_timeline,
double sequence_rate);
Project *project_;
};
}
#endif
#endif // OAK_PROJECTSAVEASOTIOTASK_H
+9
View File
@@ -0,0 +1,9 @@
# Oak Video Editor - Non-Linear Video Editor
# Copyright (C) 2026 Oak Team
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/proxy/proxy.h
task/proxy/proxy.cpp
PARENT_SCOPE
)
+256
View File
@@ -0,0 +1,256 @@
/***
Oak - Non-Linear Video Editor
Copyright (C) 2026 Oak 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 "proxy.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include "config/config.h"
namespace olive
{
ProxyTask::ProxyTask(const QString &source_filename, int stream_index,
const ProxyManager::ProxyParams &params,
const QString &output_filename)
: source_filename_(source_filename)
, stream_index_(stream_index)
, params_(params)
, output_filename_(output_filename)
{
set_title(tr("Generating Proxy %1:%2")
.arg(source_filename_, QString::number(stream_index_)));
}
QStringList ProxyTask::build_arguments(const QString &source_filename,
int stream_index,
const ProxyManager::ProxyParams &params,
const QString &output_filename)
{
QString scale_filter;
if (params.divider > 1) {
// Fraction of the source resolution, rounded down to even dimensions
// as required by yuv420p
scale_filter =
QStringLiteral("scale=w=trunc(iw/%1/2)*2:h=trunc(ih/%1/2)*2")
.arg(QString::number(params.divider));
} else {
scale_filter =
QStringLiteral("scale=w=%1:h=%2:force_original_aspect_ratio=decrease")
.arg(QString::number(params.width),
QString::number(params.height));
}
const QString container_format =
params.extension.isEmpty() ? QStringLiteral("mp4") : params.extension;
QStringList args;
args << QStringLiteral("-y")
// Report machine-readable progress on stdout for the task dialog
<< QStringLiteral("-nostats") << QStringLiteral("-progress")
<< QStringLiteral("pipe:1") << QStringLiteral("-i") << source_filename
// Map the requested video stream first so it is stream 0 in the proxy
<< QStringLiteral("-map") << QStringLiteral("0:%1").arg(stream_index);
if (params.include_audio) {
// Keep the source audio (if any) so the proxy can also be used for
// audio preview. Audio streams follow the video stream in source order.
args << QStringLiteral("-map") << QStringLiteral("0:a?")
<< QStringLiteral("-c:a") << QStringLiteral("aac")
<< QStringLiteral("-b:a") << QStringLiteral("128k");
} else {
args << QStringLiteral("-an");
}
args << QStringLiteral("-vf") << scale_filter << QStringLiteral("-c:v")
<< QStringLiteral("libx264") << QStringLiteral("-preset")
<< params.preset << QStringLiteral("-crf")
<< QString::number(params.crf) << QStringLiteral("-pix_fmt")
<< QStringLiteral("yuv420p") << QStringLiteral("-movflags")
<< QStringLiteral("+faststart") << QStringLiteral("-f")
<< container_format << output_filename;
return args;
}
double ProxyTask::parse_progress(const QString &line, double duration_seconds)
{
if (duration_seconds <= 0.0) {
return -1.0;
}
qint64 out_time_us = -1;
if (line.startsWith(QStringLiteral("out_time_us="))) {
out_time_us = line.mid(12).toLongLong();
} else if (line.startsWith(QStringLiteral("out_time_ms="))) {
// Despite the name, ffmpeg reports this value in microseconds
out_time_us = line.mid(12).toLongLong();
}
if (out_time_us < 0) {
return -1.0;
}
return qBound(0.0, out_time_us / 1000000.0 / duration_seconds, 1.0);
}
namespace
{
/**
* @brief Probes the source duration with the ffprobe next to ffmpeg
*
* Returns 0 when ffprobe is unavailable or the duration cannot be
* determined, in which case the task simply reports no intermediate
* progress.
*/
double probe_source_duration_seconds(const QString &ffmpeg_path,
const QString &source_filename)
{
QString ffprobe =
QFileInfo(ffmpeg_path).dir().filePath(QStringLiteral("ffprobe"));
#if defined(Q_OS_WIN)
ffprobe += QStringLiteral(".exe");
#endif
if (!QFileInfo::exists(ffprobe)) {
return 0.0;
}
QProcess probe;
probe.start(ffprobe,
{ QStringLiteral("-v"), QStringLiteral("error"),
QStringLiteral("-show_entries"), QStringLiteral("format=duration"),
QStringLiteral("-of"),
QStringLiteral("default=noprint_wrappers=1:nokey=1"),
source_filename });
if (!probe.waitForFinished(10000) || probe.exitCode() != 0) {
return 0.0;
}
bool ok = false;
const double duration =
QString::fromUtf8(probe.readAllStandardOutput()).trimmed().toDouble(&ok);
return ok ? duration : 0.0;
}
} // namespace
bool ProxyTask::run()
{
const QString ffmpeg = ProxyManager::find_f_fmpeg_executable(
OAK_CONFIG("FFmpegPath").toString());
if (ffmpeg.isEmpty()) {
set_error(
tr("Failed to generate proxy: ffmpeg executable was not found. Set "
"the ffmpeg path in Preferences > Disk > Proxy Settings."));
qWarning() << "ProxyTask: ffmpeg executable not found";
return false;
}
QDir output_dir = QFileInfo(output_filename_).dir();
if (!output_dir.exists() && !output_dir.mkpath(QStringLiteral("."))) {
set_error(tr("Failed to create proxy output directory"));
qWarning() << "ProxyTask: failed to create output directory"
<< output_dir.absolutePath();
return false;
}
qDebug()
<< "ProxyTask: starting ffmpeg proxy generation:" << source_filename_
<< "->" << output_filename_;
QFile::remove(output_filename_);
const QStringList args = build_arguments(source_filename_, stream_index_,
params_, output_filename_);
QProcess process;
process.setProgram(ffmpeg);
process.setArguments(args);
process.setProcessChannelMode(QProcess::MergedChannels);
const double duration_seconds =
probe_source_duration_seconds(ffmpeg, source_filename_);
process.start();
if (!process.waitForStarted()) {
set_error(tr("Failed to start ffmpeg for proxy generation"));
qWarning()
<< "ProxyTask: failed to start ffmpeg" << process.errorString();
return false;
}
QString progress_buffer;
double last_progress = 0.0;
const auto drain_progress = [&]() {
progress_buffer += QString::fromUtf8(process.readAll());
int newline = -1;
while ((newline = progress_buffer.indexOf(QLatin1Char('\n'))) >= 0) {
const QString line = progress_buffer.left(newline).trimmed();
progress_buffer.remove(0, newline + 1);
const double progress = parse_progress(line, duration_seconds);
if (progress >= 0.0 && progress - last_progress > 0.001) {
last_progress = progress;
emit progress_changed(progress);
}
}
};
while (!process.waitForFinished(100)) {
drain_progress();
if (is_cancelled()) {
process.kill();
process.waitForFinished();
QFile::remove(output_filename_);
set_error(tr("Proxy generation was cancelled"));
return false;
}
}
drain_progress();
if (process.exitStatus() != QProcess::NormalExit ||
process.exitCode() != 0) {
const QString output = QString::fromUtf8(process.readAll()).trimmed();
QFile::remove(output_filename_);
set_error(tr("ffmpeg failed to generate proxy: %1").arg(output));
qWarning() << "ProxyTask: ffmpeg failed with exit code"
<< process.exitCode() << "output:" << output;
return false;
}
if (!QFileInfo::exists(output_filename_)) {
set_error(tr("ffmpeg finished but proxy file was not created"));
qWarning() << "ProxyTask: ffmpeg finished but output file missing"
<< output_filename_;
return false;
}
qDebug() << "ProxyTask: proxy generation succeeded:" << output_filename_;
emit progress_changed(1.0);
return true;
}
}
+69
View File
@@ -0,0 +1,69 @@
/*
* Oak Video Editor - Non-Linear Video Editor
* Copyright (C) 2026 Oak Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OAK_PROXYTASK_H
#define OAK_PROXYTASK_H
#include "codec/proxymanager.h"
#include "task/task.h"
namespace olive
{
class ProxyTask : public Task {
Q_OBJECT
public:
ProxyTask(const QString &source_filename, int stream_index,
const ProxyManager::ProxyParams &params,
const QString &output_filename);
/**
* @brief Builds the ffmpeg command line for a proxy generation run
*
* Extracted for testability. The video stream is always mapped first so
* that it is stream 0 in the proxy file; audio streams (when enabled)
* follow in source order.
*/
static QStringList build_arguments(const QString &source_filename,
int stream_index,
const ProxyManager::ProxyParams &params,
const QString &output_filename);
/**
* @brief Parses one line of ffmpeg "-progress" output
*
* Extracted for testability. If the line carries an output timestamp
* ("out_time_us=" or "out_time_ms="), returns the progress fraction in
* the range [0, 1] against duration_seconds. Returns a negative value
* when the line carries no timestamp or duration_seconds is unknown.
*/
static double parse_progress(const QString &line, double duration_seconds);
protected:
virtual bool run() override;
private:
QString source_filename_;
int stream_index_;
ProxyManager::ProxyParams params_;
QString output_filename_;
};
}
#endif // OAK_PROXYTASK_H
+22
View File
@@ -0,0 +1,22 @@
# 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/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
task/render/render.h
task/render/render.cpp
PARENT_SCOPE
)
+352
View File
@@ -0,0 +1,352 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "render.h"
#include "node/project/sequence/sequence.h"
#include "render/rendermanager.h"
namespace olive
{
RenderTask::RenderTask()
: running_tickets_(0)
, native_progress_signalling_(true)
{
}
RenderTask::~RenderTask()
{
}
bool RenderTask::render(ColorManager *manager, const TimeRangeList &video_range,
const TimeRangeList &audio_range,
const TimeRange &subtitle_range, RenderMode::Mode mode,
FrameHashCache *cache, const QSize &force_size,
const QMatrix4x4 &force_matrix,
PixelFormat force_format, int force_channel_count,
ColorProcessorPtr force_color_output,
const ColorTransform &force_color_transform)
{
QMetaObject::invokeMethod(RenderManager::instance(),
"SetAggressiveGarbageCollection",
Q_ARG(bool, true));
// Run watchers in another thread so they can accept signals even while this thread is blocked
QThread watcher_thread;
watcher_thread.start();
double progress_counter = 0;
double total_length = 0;
// Store real time before any rendering takes place
// Queue audio jobs
foreach (const TimeRange &range, audio_range) {
// Don't count audio progress, since it's generally a lot faster than video and is weighted at
// 50%, which makes the progress bar look weird to the uninitiated
//total_length += r.length().toDouble();
RenderManager::RenderAudioParams rap(
viewer_->get_connected_sample_output(), range, audio_params_,
RenderMode::k_online);
RenderTicketWatcher *watcher = new RenderTicketWatcher();
watcher->setProperty("range", QVariant::fromValue(range));
prepare_watcher(watcher, &watcher_thread);
increment_running_tickets();
watcher->set_ticket(RenderManager::instance()->render_audio(rap));
}
// Look up hashes
TimeRangeListFrameIterator iterator(
video_range, video_params().frame_rate_as_time_base());
total_number_of_frames_ = iterator.size();
total_length += total_number_of_frames_;
// Start a render of a limited amount, and then render one frame for each frame that gets
// finished. This prevents rendered frames from stacking up in memory indefinitely while the
// encoder is processing them. The amount is kind of arbitrary, but we use the thread count so
// each of the system's threads are utilized as memory allows.
const int maximum_rendered_frames = QThread::idealThreadCount();
Rational next_frame;
for (int i = 0;
i < maximum_rendered_frames && iterator.get_next(&next_frame); i++) {
start_ticket(&watcher_thread, manager, next_frame, mode, cache,
force_size, force_matrix, force_format, force_channel_count,
force_color_output, force_color_transform);
}
bool result = true;
// Subtitle loop, loops over all blocks in sequence on all tracks
if (!subtitle_range.length().isNull()) {
if (Sequence *sequence = dynamic_cast<Sequence *>(viewer_)) {
TrackList *list = sequence->track_list(Track::k_subtitle);
QVector<int> block_indexes(list->get_track_count(), 0);
QVector<int> tracks_to_push;
do {
tracks_to_push.clear();
for (int i = 0; i < block_indexes.size(); i++) {
Track *this_track = list->get_track_at(i);
if (this_track->is_muted()) {
continue;
}
int &this_block_index = block_indexes[i];
if (this_block_index >= this_track->blocks().size()) {
continue;
}
Block *this_block =
this_track->blocks().at(this_block_index);
Track *compare_track =
tracks_to_push.isEmpty() ?
nullptr :
list->get_track_at(tracks_to_push.first());
const int &compare_block_index =
tracks_to_push.isEmpty() ?
-1 :
block_indexes.at(tracks_to_push.first());
Block *compare_block =
compare_track ?
compare_track->blocks().at(compare_block_index) :
nullptr;
if (!compare_track ||
compare_block->in() >= this_block->in()) {
if (compare_track &&
compare_block->in() != this_block->in()) {
tracks_to_push.clear();
}
tracks_to_push.append(i);
}
}
for (int i = 0; i < tracks_to_push.size(); i++) {
Track *this_track = list->get_track_at(tracks_to_push.at(i));
Block *this_block = this_track->blocks().at(
block_indexes.at(tracks_to_push.at(i)));
if (const SubtitleBlock *sub =
dynamic_cast<const SubtitleBlock *>(this_block)) {
if (sub->is_enabled()) {
if (!encode_subtitle(sub)) {
result = false;
break;
}
}
}
block_indexes[tracks_to_push.at(i)]++;
}
} while (!tracks_to_push.isEmpty());
}
}
finished_watcher_mutex_.lock();
while (result && !is_cancelled()) {
while (!finished_watchers_.empty() && !is_cancelled() && result) {
RenderTicketWatcher *watcher = finished_watchers_.front();
finished_watchers_.pop_front();
finished_watcher_mutex_.unlock();
// Analyze watcher here
RenderManager::TicketType ticket_type =
watcher->get_ticket()
->property("type")
.value<RenderManager::TicketType>();
if (ticket_type == RenderManager::k_type_audio) {
TimeRange range = watcher->property("range").value<TimeRange>();
if (!audio_downloaded(range,
watcher->get().value<SampleBuffer>())) {
result = false;
}
// Don't count audio progress, since it's generally a lot faster than video and is weighted at
// 50%, which makes the progress bar look weird to the uninitiated
//progress_counter += range.length().toDouble();
//emit ProgressChanged(progress_counter / total_length);
} else if (ticket_type == RenderManager::k_type_video &&
two_step_frame_rendering()) {
if (!download_frame(
&watcher_thread, watcher->get().value<FramePtr>(),
watcher->property("time").value<Rational>())) {
result = false;
}
if (native_progress_signalling_) {
progress_counter += 0.5;
emit progress_changed(progress_counter / total_length);
}
} else {
// Assume single-step video or video download ticket
if (!frame_downloaded(
watcher->get().value<FramePtr>(),
watcher->property("time").value<Rational>())) {
result = false;
}
if (native_progress_signalling_) {
double progress_to_add = 1.0;
if (two_step_frame_rendering()) {
progress_to_add *= 0.5;
}
progress_counter += progress_to_add;
emit progress_changed(progress_counter / total_length);
}
if (iterator.get_next(&next_frame)) {
start_ticket(&watcher_thread, manager, next_frame, mode,
cache, force_size, force_matrix, force_format,
force_channel_count, force_color_output,
force_color_transform);
}
}
delete watcher;
running_watchers_.removeOne(watcher);
finished_watcher_mutex_.lock();
}
if (is_cancelled() || !result) {
break;
}
// Run out of finished watchers. If we still have running tickets, wait for the next one to finish.
if (running_tickets_ > 0) {
finished_watcher_wait_cond_.wait(&finished_watcher_mutex_);
} else {
// No more running tickets or finished tickets, wem ust be
break;
}
}
finished_watcher_mutex_.unlock();
if (is_cancelled() || !result) {
// Cancel every watcher we created
foreach (RenderTicketWatcher *watcher, running_watchers_) {
watcher->cancel();
disconnect(watcher, &RenderTicketWatcher::finished, this,
&RenderTask::ticket_done);
RenderManager::instance()->remove_ticket(watcher->get_ticket());
}
foreach (RenderTicketWatcher *watcher, running_watchers_) {
watcher->wait_for_finished();
}
}
watcher_thread.quit();
watcher_thread.wait();
QMetaObject::invokeMethod(RenderManager::instance(),
"SetAggressiveGarbageCollection",
Q_ARG(bool, false));
return result;
}
bool RenderTask::download_frame(QThread *thread, FramePtr frame,
const Rational &time)
{
//RenderTicketWatcher* watcher = new RenderTicketWatcher();
//PrepareWatcher(watcher, thread);
//IncrementRunningTickets();
//watcher->SetTicket(RenderManager::instance()->SaveFrameToCache(viewer_->video_frame_cache(), frame, time));
// NOTE: Doesn't reflect the actual return result of SaveFrameToCache
return true;
}
bool RenderTask::encode_subtitle(const SubtitleBlock *subtitle)
{
Q_UNUSED(subtitle)
return true;
}
void RenderTask::prepare_watcher(RenderTicketWatcher *watcher, QThread *thread)
{
watcher->moveToThread(thread);
connect(watcher, &RenderTicketWatcher::finished, this,
&RenderTask::ticket_done, Qt::DirectConnection);
running_watchers_.append(watcher);
}
void RenderTask::increment_running_tickets()
{
finished_watcher_mutex_.lock();
running_tickets_++;
finished_watcher_mutex_.unlock();
}
void RenderTask::start_ticket(QThread *watcher_thread, ColorManager *manager,
const Rational &time, RenderMode::Mode mode,
FrameHashCache *cache, const QSize &force_size,
const QMatrix4x4 &force_matrix,
PixelFormat force_format, int force_channel_count,
ColorProcessorPtr force_color_output,
const ColorTransform &force_color_transform)
{
RenderManager::RenderVideoParams rvp(viewer_->get_connected_texture_output(),
video_params_, audio_params_, time,
manager, mode);
rvp.force_size = force_size;
rvp.force_matrix = force_matrix;
rvp.force_format = force_format;
rvp.force_color_output = force_color_output;
rvp.force_color_transform = force_color_transform;
rvp.force_channel_count = force_channel_count;
if (cache) {
rvp.add_cache(cache);
}
RenderTicketWatcher *watcher = new RenderTicketWatcher();
watcher->setProperty("time", QVariant::fromValue(time));
prepare_watcher(watcher, watcher_thread);
increment_running_tickets();
watcher->set_ticket(RenderManager::instance()->render_frame(rvp));
}
void RenderTask::ticket_done(RenderTicketWatcher *watcher)
{
finished_watcher_mutex_.lock();
finished_watchers_.push_back(watcher);
finished_watcher_wait_cond_.wakeAll();
running_tickets_--;
finished_watcher_mutex_.unlock();
}
}
+154
View File
@@ -0,0 +1,154 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_RENDERTASK_H
#define OAK_RENDERTASK_H
#include <QtConcurrent/QtConcurrent>
#include "node/block/subtitle/subtitle.h"
#include "node/color/colormanager/colormanager.h"
#include "node/output/viewer/viewer.h"
#include "task/task.h"
#include "render/renderticket.h"
namespace olive
{
class RenderTask : public Task {
Q_OBJECT
public:
RenderTask();
virtual ~RenderTask() override;
protected:
bool render(ColorManager *manager, const TimeRangeList &video_range,
const TimeRangeList &audio_range,
const TimeRange &subtitle_range, RenderMode::Mode mode,
FrameHashCache *cache, const QSize &force_size = QSize(0, 0),
const QMatrix4x4 &force_matrix = QMatrix4x4(),
PixelFormat force_format = PixelFormat::invalid,
int force_channel_count = 0,
ColorProcessorPtr force_color_output = nullptr,
const ColorTransform &force_color_transform = ColorTransform());
virtual bool download_frame(QThread *thread, FramePtr frame,
const Rational &time);
virtual bool frame_downloaded(FramePtr frame, const Rational &time) = 0;
virtual bool audio_downloaded(const TimeRange &range,
const SampleBuffer &samples) = 0;
virtual bool encode_subtitle(const SubtitleBlock *subtitle);
ViewerOutput *viewer() const
{
return viewer_;
}
void set_viewer(ViewerOutput *v)
{
viewer_ = v;
}
const VideoParams &video_params() const
{
return video_params_;
}
void set_video_params(const VideoParams &video_params)
{
video_params_ = video_params;
}
const AudioParams &audio_params() const
{
return audio_params_;
}
void set_audio_params(const AudioParams &audio_params)
{
audio_params_ = audio_params;
}
virtual void CancelEvent() override
{
finished_watcher_mutex_.lock();
finished_watcher_wait_cond_.wakeAll();
finished_watcher_mutex_.unlock();
}
virtual bool two_step_frame_rendering() const
{
return true;
}
void set_native_progress_signalling_enabled(bool e)
{
native_progress_signalling_ = e;
}
/**
* @brief Only valid after Render() is called
*/
int64_t get_total_number_of_frames() const
{
return total_number_of_frames_;
}
private:
void prepare_watcher(RenderTicketWatcher *watcher, QThread *thread);
void increment_running_tickets();
void start_ticket(QThread *watcher_thread, ColorManager *manager,
const Rational &time, RenderMode::Mode mode,
FrameHashCache *cache, const QSize &force_size,
const QMatrix4x4 &force_matrix, PixelFormat force_format,
int force_channel_count,
ColorProcessorPtr force_color_output,
const ColorTransform &force_color_transform);
ViewerOutput *viewer_;
VideoParams video_params_;
AudioParams audio_params_;
QVector<RenderTicketWatcher *> running_watchers_;
std::list<RenderTicketWatcher *> finished_watchers_;
int running_tickets_;
QMutex finished_watcher_mutex_;
QWaitCondition finished_watcher_wait_cond_;
bool native_progress_signalling_;
int64_t total_number_of_frames_;
private slots:
void ticket_done(RenderTicketWatcher *watcher);
};
}
#endif // OAK_RENDERTASK_H
+188
View File
@@ -0,0 +1,188 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_TASK_H
#define OAK_TASK_H
#include <memory>
#include <QDateTime>
#include <QDebug>
#include <QObject>
#include "common/cancelableobject.h"
namespace olive
{
/**
* @brief A base class for background tasks running in Olive.
*
* Tasks are multithreaded by design (i.e. they will always spawn
* a new thread and run in it).
*
* To subclass your own Task, override Action() and return TRUE on success or FALSE on failure. Note that a Task can
* provide a "negative" output and still have succeeded. For example, the ProbeTask's role is to determine whether a
* certain media file can be used in Olive. Even if the probe *fails* to find a Decoder for this file, the Task itself
* has *succeeded* at discovering this. A failure of ProbeTask would indicate a catastrophic failure meaning it was
* unable to determine anything about the file.
*
* Tasks should be used with the TaskManager which will manage starting and deleting them. It'll also only start as
* many Tasks as there are threads on the system as to not overload them.
*
* Tasks support "dependency tasks", i.e. a Task that should be complete before another Task begins.
*/
class Task : public QObject, public CancelableObject {
Q_OBJECT
public:
/**
* @brief Task Constructor
*/
Task()
: title_(tr("Task"))
, error_(tr("Unknown error"))
, start_time_(0)
{
}
/**
* @brief Retrieve the current title of this Task
*/
const QString &get_title() const
{
return title_;
}
/**
* @brief Returns the error that occurred if Run() returns false
*/
const QString &get_error() const
{
return error_;
}
const qint64 &get_start_time() const
{
return start_time_;
}
public slots:
/**
* @brief Run this task
*
* @return True if the task completed successfully, false if not.
*
* \see GetError() if this returns false.
*/
bool start()
{
start_time_ = QDateTime::currentMSecsSinceEpoch();
emit started(start_time_);
bool ret = run();
// Print how long this task took for debugging purposes
qDebug() << this << "took"
<< (QDateTime::currentMSecsSinceEpoch() - start_time_);
emit finished(this, ret);
return ret;
}
/**
* @brief Reset state so that Run() can be called again.
*
* Override this if your class holds any persistent state that should be cleared/modified before
* it's safe for Run() to run again.
*/
virtual void reset()
{
}
/**
* @brief Cancel the Task
*
* Sends a signal to the Task to stop as soon as possible. Always call this directly or connect
* with Qt::DirectConnection, or else it'll be queued *after* the task has already finished.
*/
void Cancel()
{
CancelableObject::cancel();
}
protected:
virtual bool run() = 0;
/**
* @brief Set the error message
*
* It is recommended to use this if your Action() function ever returns FALSE to tell the user why the failure
* occurred.
*/
void set_error(const QString &s)
{
error_ = s;
}
/**
* @brief Set the Task title
*
* Used in the UI Task Manager to distinguish Tasks from each other. Generally this should be set in the constructor
* and shouldn't need to change during the life of the Task. To show an error message, it's recommended to use
* set_error() instead.
*/
void set_title(const QString &s)
{
title_ = s;
}
signals:
void started(qint64 start_time);
/**
* @brief Signal emitted whenever progress is made
*
* Emit this throughout Action() to update any attached ProgressBars on the progress of this Task.
*
* @param p
*
* A progress value between 0.0 and 1.0.
*/
void progress_changed(double d);
/**
* @brief Emitted when task is finished
*
* Do NOT delete immediately after this signal, call deleteLater() instead.
*/
void finished(Task *task, bool succeeded);
private:
QString title_;
QString error_;
qint64 start_time_;
};
}
#endif // OAK_TASK_H
+148
View File
@@ -0,0 +1,148 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can 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 "taskmanager.h"
#include <QDebug>
#include <QThread>
namespace olive
{
TaskManager *TaskManager::instance_ = nullptr;
TaskManager::TaskManager()
{
thread_pool_.setMaxThreadCount(1);
}
TaskManager::~TaskManager()
{
thread_pool_.clear();
foreach (Task *t, tasks_) {
t->Cancel();
}
thread_pool_.waitForDone();
foreach (Task *t, tasks_) {
t->deleteLater();
}
}
void TaskManager::create_instance()
{
instance_ = new TaskManager();
}
void TaskManager::destroy_instance()
{
delete instance_;
instance_ = nullptr;
}
TaskManager *TaskManager::instance()
{
return instance_;
}
int TaskManager::get_task_count() const
{
return tasks_.size();
}
Task *TaskManager::get_first_task() const
{
return tasks_.begin().value();
}
void TaskManager::cancel_task_and_wait(Task *t)
{
t->Cancel();
QFutureWatcher<bool> *w = tasks_.key(t);
if (w) {
w->waitForFinished();
}
}
void TaskManager::add_task(Task *t)
{
// Create a watcher for signalling
QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
connect(watcher, &QFutureWatcher<bool>::finished, this,
&TaskManager::task_finished);
// Add the Task to the queue
tasks_.insert(watcher, t);
// Run task concurrently
watcher->setFuture(
#if QT_VERSION_MAJOR >= 6
QtConcurrent::run(&thread_pool_, &Task::start, t)
#else
QtConcurrent::run(&thread_pool_, t, &Task::Start)
#endif
);
// Emit signal that a Task was added
emit task_added(t);
emit task_list_changed();
}
void TaskManager::cancel_task(Task *t)
{
if (std::find(failed_tasks_.begin(), failed_tasks_.end(), t) !=
failed_tasks_.end()) {
failed_tasks_.remove(t);
emit task_removed(t);
t->deleteLater();
} else {
t->Cancel();
}
}
void TaskManager::task_finished()
{
QFutureWatcher<bool> *watcher =
static_cast<QFutureWatcher<bool> *>(sender());
Task *t = tasks_.value(watcher);
tasks_.remove(watcher);
if (watcher->result()) {
// Task completed successfully
emit task_removed(t);
t->deleteLater();
} else {
// Task failed, keep it so the user can see the error message
emit task_failed(t);
failed_tasks_.push_back(t);
}
watcher->deleteLater();
emit task_list_changed();
}
}
+141
View File
@@ -0,0 +1,141 @@
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
Modifications Copyright (C) 2025 mikesolar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OAK_TASKMANAGER_H
#define OAK_TASKMANAGER_H
#include <QtConcurrent/QtConcurrent>
#include <QVector>
#include <QUndoCommand>
#include "task/task.h"
namespace olive
{
/**
* @brief An object that manages background Task objects, handling their start and end
*
* TaskManager handles the life of a Task object. After a new Task is created, it should be sent to TaskManager through
* AddTask(). TaskManager will take ownership of the task and add it to a queue until it system resources are available
* for it to run. Currently, TaskManager will run no more Tasks than there are threads on the system (one task per
* thread). As Tasks finished, TaskManager will start the next in the queue.
*/
class TaskManager : public QObject {
Q_OBJECT
public:
/**
* @brief TaskManager Constructor
*/
TaskManager();
/**
* @brief TaskManager Destructor
*
* Ensures all Tasks are deleted
*/
virtual ~TaskManager();
static void create_instance();
static void destroy_instance();
static TaskManager *instance();
int get_task_count() const;
Task *get_first_task() const;
void cancel_task_and_wait(Task *t);
public slots:
/**
* @brief Add a new Task
*
* Adds a new Task to the queue. If there are available threads to run it, it'll also run immediately. Otherwise,
* it'll be placed into the queue and run when resources are available.
*
* NOTE: This function is NOT thread-safe and is currently intended to only be used from the main/GUI thread.
*
* NOTE: A Task object should only be added once. Adding the same Task object more than once will result in undefined
* behavior.
*
* @param t
*
* The task to add and run. TaskManager takes ownership of this Task and will be responsible for freeing it.
*/
void add_task(Task *t);
void cancel_task(Task *t);
signals:
/**
* @brief Signal emitted when a Task is added by AddTask()
*
* @param t
*
* Task that was added
*/
void task_added(Task *t);
/**
* @brief Signal emitted when any change to the running task list has been made
*/
void task_list_changed();
/**
* @brief Signal emitted when a task is deleted
*/
void task_removed(Task *t);
/**
* @brief Signal emitted when a task fails
*/
void task_failed(Task *t);
private:
/**
* @brief Internal task array
*/
QHash<QFutureWatcher<bool> *, Task *> tasks_;
/**
* @brief Internal list of failed tasks
*/
std::list<Task *> failed_tasks_;
/**
* @brief Task thread pool
*/
QThreadPool thread_pool_;
/**
* @brief TaskManager singleton instance_
*/
static TaskManager *instance_;
private slots:
void task_finished();
};
}
#endif // OAK_TASKMANAGER_H