26 #include <QRegularExpression>
27 #include <unordered_map>
35 is_open(false), auto_map_clips(true), managed_cache(true),
path(
""), max_time(0.0), cache_epoch(0)
81 info.width, info.height, info.fps, info.sample_rate,
82 info.channels, info.channel_layout) {}
86 is_open(false), auto_map_clips(true), managed_cache(true),
path(projectPath), max_time(0.0), cache_epoch(0) {
105 QFileInfo filePath(QString::fromStdString(path));
106 if (!filePath.exists()) {
107 throw InvalidFile(
"Timeline project file could not be opened.", path);
113 if (!openshotPath.exists()) {
116 QDir openshotTransPath(openshotPath.filePath(
"transitions"));
117 if (!openshotTransPath.exists()) {
118 throw InvalidFile(
"PATH_OPENSHOT_INSTALL/transitions could not be found.", openshotTransPath.path().toStdString());
122 QString asset_name = filePath.baseName().left(30) +
"_assets";
123 QDir asset_folder(filePath.dir().filePath(asset_name));
124 if (!asset_folder.exists()) {
126 asset_folder.mkpath(
".");
130 QFile projectFile(QString::fromStdString(path));
131 projectFile.open(QFile::ReadOnly);
132 QString projectContents = QString::fromUtf8(projectFile.readAll());
135 if (convert_absolute_paths) {
139 QRegularExpression allPathsRegex(QStringLiteral(
"\"(image|path)\":.*?\"(.*?)\""));
140 std::vector<QRegularExpressionMatch> matchedPositions;
141 QRegularExpressionMatchIterator i = allPathsRegex.globalMatch(projectContents);
142 while (i.hasNext()) {
143 QRegularExpressionMatch match = i.next();
144 if (match.hasMatch()) {
146 matchedPositions.push_back(match);
151 std::vector<QRegularExpressionMatch>::reverse_iterator itr;
152 for (itr = matchedPositions.rbegin(); itr != matchedPositions.rend(); itr++) {
153 QRegularExpressionMatch match = *itr;
154 QString relativeKey = match.captured(1);
155 QString relativePath = match.captured(2);
156 QString absolutePath =
"";
159 if (relativePath.startsWith(
"@assets")) {
160 absolutePath = QFileInfo(asset_folder.absoluteFilePath(relativePath.replace(
"@assets",
"."))).canonicalFilePath();
161 }
else if (relativePath.startsWith(
"@transitions")) {
162 absolutePath = QFileInfo(openshotTransPath.absoluteFilePath(relativePath.replace(
"@transitions",
"."))).canonicalFilePath();
164 absolutePath = QFileInfo(filePath.absoluteDir().absoluteFilePath(relativePath)).canonicalFilePath();
168 if (!absolutePath.isEmpty()) {
169 projectContents.replace(match.capturedStart(0), match.capturedLength(0),
"\"" + relativeKey +
"\": \"" + absolutePath +
"\"");
173 matchedPositions.clear();
177 SetJson(projectContents.toStdString());
181 float calculated_duration = 0.0;
182 for (
auto clip : clips)
185 if (clip_last_frame > calculated_duration)
186 calculated_duration = clip_last_frame;
187 if (
clip->Reader() &&
clip->Reader()->info.has_audio)
189 if (
clip->Reader() &&
clip->Reader()->info.has_video)
222 if (managed_cache && final_cache) {
232 auto iterator = tracked_objects.find(trackedObject->Id());
234 if (iterator != tracked_objects.end()){
236 iterator->second = trackedObject;
240 tracked_objects[trackedObject->Id()] = trackedObject;
250 auto iterator = tracked_objects.find(
id);
252 if (iterator != tracked_objects.end()){
254 std::shared_ptr<openshot::TrackedObjectBase> trackedObject = iterator->second;
255 return trackedObject;
267 std::list<std::string> trackedObjects_ids;
270 for (
auto const& it: tracked_objects){
272 trackedObjects_ids.push_back(it.first);
275 return trackedObjects_ids;
283 Json::Value trackedObjectJson;
286 auto iterator = tracked_objects.find(
id);
288 if (iterator != tracked_objects.end())
291 std::shared_ptr<TrackedObjectBBox> trackedObject = std::static_pointer_cast<TrackedObjectBBox>(iterator->second);
294 if (trackedObject->ExactlyContains(frame_number)){
295 BBox box = trackedObject->GetBox(frame_number);
296 float x1 = box.
cx - (box.
width/2);
298 float x2 = box.
cx + (box.
width/2);
300 float rotation = box.
angle;
302 trackedObjectJson[
"x1"] = x1;
303 trackedObjectJson[
"y1"] = y1;
304 trackedObjectJson[
"x2"] = x2;
305 trackedObjectJson[
"y2"] = y2;
306 trackedObjectJson[
"rotation"] = rotation;
309 BBox box = trackedObject->BoxVec.begin()->second;
310 float x1 = box.
cx - (box.
width/2);
312 float x2 = box.
cx + (box.
width/2);
314 float rotation = box.
angle;
316 trackedObjectJson[
"x1"] = x1;
317 trackedObjectJson[
"y1"] = y1;
318 trackedObjectJson[
"x2"] = x2;
319 trackedObjectJson[
"y2"] = y2;
320 trackedObjectJson[
"rotation"] = rotation;
326 trackedObjectJson[
"x1"] = 0;
327 trackedObjectJson[
"y1"] = 0;
328 trackedObjectJson[
"x2"] = 0;
329 trackedObjectJson[
"y2"] = 0;
330 trackedObjectJson[
"rotation"] = 0;
333 return trackedObjectJson.toStyledString();
341 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
344 clip->ParentTimeline(
this);
347 if (
clip->Reader() &&
clip->Reader()->GetCache())
348 clip->Reader()->GetCache()->Clear();
351 if (auto_map_clips) {
353 apply_mapper_to_clip(
clip);
357 clips.push_back(
clip);
367 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
370 effect->ParentTimeline(
this);
373 effects.push_back(effect);
383 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
385 effects.remove(effect);
388 if (allocated_effects.count(effect)) {
389 allocated_effects.erase(effect);
402 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
407 if (allocated_clips.count(
clip)) {
408 allocated_clips.erase(
clip);
421 for (
const auto&
clip : clips) {
433 for (
const auto& effect : effects) {
434 if (effect->Id() ==
id) {
444 for (
const auto&
clip : clips) {
445 const auto e =
clip->GetEffect(
id);
457 std::list<EffectBase*> timelineEffectsList;
460 for (
const auto&
clip : clips) {
463 std::list<EffectBase*> clipEffectsList =
clip->Effects();
466 timelineEffectsList.insert(timelineEffectsList.end(), clipEffectsList.begin(), clipEffectsList.end());
469 return timelineEffectsList;
482 const double frames = t * fps;
483 constexpr
double frame_boundary_epsilon = 1e-4;
486 if (frames > 0.0 && frames < frame_boundary_epsilon)
488 return static_cast<int64_t
>(std::ceil(frames - frame_boundary_epsilon));
496 return static_cast<int64_t
>(std::floor(t * fps)) + 1;
506 void Timeline::apply_mapper_to_clip(
Clip* clip)
509 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
513 if (
clip->Reader()->Name() ==
"FrameMapper")
526 allocated_frame_mappers.insert(mapper);
531 clip->Reader(clip_reader);
541 for (
auto clip : clips)
544 apply_mapper_to_clip(
clip);
549 double Timeline::calculate_time(int64_t number,
Fraction rate)
552 double raw_fps = rate.
ToFloat();
555 return double(number - 1) / raw_fps;
563 "Timeline::apply_effects",
564 "frame->number", frame->number,
565 "timeline_frame_number", timeline_frame_number,
569 for (
auto effect : effects)
573 int64_t effect_start_position =
static_cast<int64_t
>(std::llround(effect->Position() * fpsD)) + 1;
574 int64_t effect_end_position =
static_cast<int64_t
>(std::llround((effect->Position() + effect->Duration()) * fpsD));
576 bool does_effect_intersect = (effect_start_position <= timeline_frame_number && effect_end_position >= timeline_frame_number && effect->Layer() == layer);
579 if (does_effect_intersect)
582 int64_t effect_start_frame =
static_cast<int64_t
>(std::llround(effect->Start() * fpsD)) + 1;
583 int64_t effect_frame_number = timeline_frame_number - effect_start_position + effect_start_frame;
593 "Timeline::apply_effects (Process Effect)",
594 "effect_frame_number", effect_frame_number,
595 "does_effect_intersect", does_effect_intersect);
598 frame = effect->ProcessFrame(frame, effect_frame_number);
608 std::shared_ptr<Frame> Timeline::GetOrCreateFrame(std::shared_ptr<Frame> background_frame,
Clip* clip, int64_t number,
openshot::TimelineInfoStruct* options)
610 std::shared_ptr<Frame> new_frame;
618 "Timeline::GetOrCreateFrame (from reader)",
620 "samples_in_frame", samples_in_frame);
623 new_frame = std::shared_ptr<Frame>(
clip->
GetFrame(background_frame, number, options));
636 "Timeline::GetOrCreateFrame (create blank)",
638 "samples_in_frame", samples_in_frame);
645 void Timeline::add_layer(std::shared_ptr<Frame> new_frame,
Clip* source_clip, int64_t clip_frame_number,
bool is_top_clip,
float max_volume)
653 std::shared_ptr<Frame> source_frame;
654 source_frame = GetOrCreateFrame(new_frame, source_clip, clip_frame_number, &options);
662 "Timeline::add_layer",
663 "new_frame->number", new_frame->number,
664 "clip_frame_number", clip_frame_number);
667 if (source_clip->
Reader()->info.has_audio) {
670 "Timeline::add_layer (Copy Audio)",
671 "source_clip->Reader()->info.has_audio", source_clip->
Reader()->info.has_audio,
672 "source_frame->GetAudioChannelsCount()", source_frame->GetAudioChannelsCount(),
674 "clip_frame_number", clip_frame_number);
679 if (new_frame->GetAudioSamplesCount() != source_frame->GetAudioSamplesCount()){
684 const auto transition_audio_gains = ResolveTransitionAudioGains(source_clip, new_frame->number, is_top_clip);
686 for (
int channel = 0; channel < source_frame->GetAudioChannelsCount(); channel++)
689 float previous_volume = source_clip->
volume.
GetValue(clip_frame_number - 1);
691 previous_volume *= transition_audio_gains.first;
692 volume *= transition_audio_gains.second;
699 previous_volume = previous_volume / max_volume;
700 volume = volume / max_volume;
704 previous_volume = previous_volume * 0.77;
705 volume = volume * 0.77;
709 if (channel_filter != -1 && channel_filter != channel)
713 if (previous_volume == 0.0 && volume == 0.0)
717 if (channel_mapping == -1)
718 channel_mapping = channel;
721 if (!isEqual(previous_volume, 1.0) || !isEqual(volume, 1.0))
722 source_frame->ApplyGainRamp(channel_mapping, 0, source_frame->GetAudioSamplesCount(), previous_volume, volume);
726 new_frame->AddAudio(
false, channel_mapping, 0, source_frame->GetAudioSamples(channel), source_frame->GetAudioSamplesCount(), 1.0);
732 "Timeline::add_layer (No Audio Copied - Wrong # of Channels)",
733 "source_clip->Reader()->info.has_audio",
734 source_clip->
Reader()->info.has_audio,
735 "source_frame->GetAudioChannelsCount()",
736 source_frame->GetAudioChannelsCount(),
738 "clip_frame_number", clip_frame_number);
743 "Timeline::add_layer (Transform: Composite Image Layer: Completed)",
744 "source_frame->number", source_frame->number,
745 "new_frame->GetImage()->width()", new_frame->GetWidth(),
746 "new_frame->GetImage()->height()", new_frame->GetHeight());
750 void Timeline::update_open_clips(
Clip *clip,
bool does_clip_intersect)
753 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
756 "Timeline::update_open_clips (before)",
757 "does_clip_intersect", does_clip_intersect,
758 "closing_clips.size()", closing_clips.size(),
759 "open_clips.size()", open_clips.size());
762 bool clip_found = open_clips.count(
clip);
764 if (clip_found && !does_clip_intersect)
767 open_clips.erase(
clip);
772 else if (!clip_found && does_clip_intersect)
788 "Timeline::update_open_clips (after)",
789 "does_clip_intersect", does_clip_intersect,
790 "clip_found", clip_found,
791 "closing_clips.size()", closing_clips.size(),
792 "open_clips.size()", open_clips.size());
796 void Timeline::calculate_max_duration() {
797 double last_clip = 0.0;
798 double last_effect = 0.0;
799 double first_clip = std::numeric_limits<double>::max();
800 double first_effect = std::numeric_limits<double>::max();
803 if (!clips.empty()) {
805 const auto max_clip = std::max_element(
807 last_clip = (*max_clip)->Position() + (*max_clip)->Duration();
810 const auto min_clip = std::min_element(
812 return lhs->Position() < rhs->Position();
814 first_clip = (*min_clip)->Position();
818 if (!effects.empty()) {
820 const auto max_effect = std::max_element(
822 last_effect = (*max_effect)->Position() + (*max_effect)->Duration();
825 const auto min_effect = std::min_element(
827 return lhs->Position() < rhs->Position();
829 first_effect = (*min_effect)->Position();
833 max_time = std::max(last_clip, last_effect);
834 min_time = std::min(first_clip, first_effect);
837 if (clips.empty() && effects.empty()) {
844 void Timeline::sort_clips()
847 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
851 "Timeline::SortClips",
852 "clips.size()", clips.size());
858 calculate_max_duration();
862 void Timeline::sort_effects()
865 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
871 calculate_max_duration();
880 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
883 for (
auto clip : clips)
885 update_open_clips(
clip,
false);
888 bool allocated = allocated_clips.count(
clip);
895 allocated_clips.clear();
898 for (
auto effect : effects)
901 bool allocated = allocated_effects.count(effect);
908 allocated_effects.clear();
911 for (
auto mapper : allocated_frame_mappers)
917 allocated_frame_mappers.clear();
926 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
929 for (
auto clip : clips)
932 update_open_clips(
clip,
false);
949 bool Timeline::isEqual(
double a,
double b)
951 return fabs(a - b) < 0.000001;
958 if (requested_frame < 1)
961 const bool past_timeline_end = (max_frame > 0 && requested_frame > max_frame);
964 std::shared_ptr<Frame> frame;
965 if (!past_timeline_end)
966 frame = final_cache->
GetFrame(requested_frame);
970 "Timeline::GetFrame (Cached frame found)",
971 "requested_frame", requested_frame);
979 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
982 std::shared_ptr<Frame> frame;
983 if (!past_timeline_end)
984 frame = final_cache->
GetFrame(requested_frame);
988 "Timeline::GetFrame (Cached frame found on 2nd check)",
989 "requested_frame", requested_frame);
996 std::vector<Clip *> nearby_clips;
997 nearby_clips = find_intersecting_clips(requested_frame, 1,
true);
1001 "Timeline::GetFrame (processing frame)",
1002 "requested_frame", requested_frame,
1003 "omp_get_thread_num()", omp_get_thread_num());
1010 new_frame->AddAudioSilence(samples_in_frame);
1016 "Timeline::GetFrame (Adding solid color)",
1017 "requested_frame", requested_frame,
1029 "Timeline::GetFrame (Loop through clips)",
1030 "requested_frame", requested_frame,
1031 "clips.size()", clips.size(),
1032 "nearby_clips.size()", nearby_clips.size());
1039 int64_t start_frame;
1040 int64_t frame_number;
1043 std::vector<ClipInfo> clip_infos;
1044 clip_infos.reserve(nearby_clips.size());
1047 for (
auto clip : nearby_clips) {
1048 int64_t start_pos =
static_cast<int64_t
>(std::llround(
clip->
Position() * fpsD)) + 1;
1049 int64_t end_pos =
static_cast<int64_t
>(std::llround((
clip->
Position() +
clip->Duration()) * fpsD));
1050 bool intersects = (start_pos <= requested_frame && end_pos >= requested_frame);
1051 int64_t start_frame =
static_cast<int64_t
>(std::llround(
clip->
Start() * fpsD)) + 1;
1052 int64_t frame_number = requested_frame - start_pos + start_frame;
1053 clip_infos.push_back({
clip, start_pos, end_pos, start_frame, frame_number, intersects});
1057 std::unordered_map<int, int64_t> top_start_for_layer;
1058 std::unordered_map<int, Clip*> top_clip_for_layer;
1059 for (
const auto& ci : clip_infos) {
1060 if (!ci.intersects)
continue;
1061 const int layer = ci.clip->Layer();
1062 auto it = top_start_for_layer.find(layer);
1063 if (it == top_start_for_layer.end() || ci.start_pos > it->second) {
1064 top_start_for_layer[layer] = ci.start_pos;
1065 top_clip_for_layer[layer] = ci.clip;
1070 float max_volume_sum = 0.0f;
1071 for (
const auto& ci : clip_infos) {
1072 if (!ci.intersects)
continue;
1073 if (ci.clip->Reader() && ci.clip->Reader()->info.has_audio &&
1074 ci.clip->has_audio.GetInt(ci.frame_number) != 0) {
1075 max_volume_sum +=
static_cast<float>(ci.clip->volume.GetValue(ci.frame_number));
1080 for (
const auto& ci : clip_infos) {
1083 "Timeline::GetFrame (Does clip intersect)",
1084 "requested_frame", requested_frame,
1085 "clip->Position()", ci.clip->Position(),
1086 "clip->Duration()", ci.clip->Duration(),
1087 "does_clip_intersect", ci.intersects);
1090 if (ci.intersects) {
1092 bool is_top_clip =
false;
1093 const int layer = ci.clip->Layer();
1094 auto top_it = top_clip_for_layer.find(layer);
1095 if (top_it != top_clip_for_layer.end())
1096 is_top_clip = (top_it->second == ci.clip);
1099 int64_t clip_frame_number = ci.frame_number;
1103 "Timeline::GetFrame (Calculate clip's frame #)",
1104 "clip->Position()", ci.clip->Position(),
1105 "clip->Start()", ci.clip->Start(),
1107 "clip_frame_number", clip_frame_number);
1110 add_layer(new_frame, ci.clip, clip_frame_number, is_top_clip, max_volume_sum);
1115 "Timeline::GetFrame (clip does not intersect)",
1116 "requested_frame", requested_frame,
1117 "does_clip_intersect", ci.intersects);
1124 "Timeline::GetFrame (Add frame to cache)",
1125 "requested_frame", requested_frame,
1130 new_frame->SetFrameNumber(requested_frame);
1133 if (!past_timeline_end)
1134 final_cache->
Add(new_frame);
1143 std::vector<Clip*> Timeline::find_intersecting_clips(int64_t requested_frame,
int number_of_frames,
bool include)
1146 std::vector<Clip*> matching_clips;
1149 const int64_t min_requested_frame = requested_frame;
1150 const int64_t max_requested_frame = requested_frame + (number_of_frames - 1);
1153 matching_clips.reserve(clips.size());
1155 for (
auto clip : clips)
1158 int64_t clip_start_position =
static_cast<int64_t
>(std::llround(
clip->
Position() * fpsD)) + 1;
1159 int64_t clip_end_position =
static_cast<int64_t
>(std::llround((
clip->
Position() +
clip->Duration()) * fpsD)) + 1;
1161 bool does_clip_intersect =
1162 (clip_start_position <= min_requested_frame || clip_start_position <= max_requested_frame) &&
1163 (clip_end_position >= min_requested_frame || clip_end_position >= max_requested_frame);
1167 "Timeline::find_intersecting_clips (Is clip near or intersecting)",
1168 "requested_frame", requested_frame,
1169 "min_requested_frame", min_requested_frame,
1170 "max_requested_frame", max_requested_frame,
1172 "does_clip_intersect", does_clip_intersect);
1175 update_open_clips(
clip, does_clip_intersect);
1178 if (does_clip_intersect && include)
1180 matching_clips.push_back(
clip);
1182 else if (!does_clip_intersect && !include)
1184 matching_clips.push_back(
clip);
1189 return matching_clips;
1195 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1198 if (managed_cache && final_cache) {
1201 managed_cache =
false;
1205 final_cache = new_cache;
1220 root[
"type"] =
"Timeline";
1225 root[
"path"] = path;
1228 root[
"clips"] = Json::Value(Json::arrayValue);
1231 for (
const auto existing_clip : clips)
1233 root[
"clips"].append(existing_clip->JsonValue());
1237 root[
"effects"] = Json::Value(Json::arrayValue);
1240 for (
const auto existing_effect: effects)
1242 root[
"effects"].append(existing_effect->JsonValue());
1253 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1262 catch (
const std::exception& e)
1265 throw InvalidJSON(
"JSON is invalid (missing keys or invalid data types)");
1273 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1276 bool was_open = is_open;
1283 if (!root[
"path"].isNull())
1284 path = root[
"path"].asString();
1286 if (!root[
"clips"].isNull()) {
1291 for (
const Json::Value existing_clip : root[
"clips"]) {
1293 if (existing_clip.isNull()) {
1301 allocated_clips.insert(c);
1318 if (!root[
"effects"].isNull()) {
1323 for (
const Json::Value existing_effect :root[
"effects"]) {
1325 if (existing_effect.isNull()) {
1332 if (!existing_effect[
"type"].isNull()) {
1334 if ( (e =
EffectInfo().CreateEffect(existing_effect[
"type"].asString())) ) {
1337 allocated_effects.insert(e);
1349 if (!root[
"duration"].isNull()) {
1375 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1382 for (
const Json::Value change : root) {
1383 std::string change_key = change[
"key"][(uint)0].asString();
1386 if (change_key ==
"clips")
1388 apply_json_to_clips(change);
1390 else if (change_key ==
"effects")
1392 apply_json_to_effects(change);
1396 apply_json_to_timeline(change);
1401 if (!root.empty()) {
1405 catch (
const std::exception& e)
1408 throw InvalidJSON(
"JSON is invalid (missing keys or invalid data types)");
1412 void Timeline::BumpCacheEpoch() {
1413 cache_epoch.fetch_add(1, std::memory_order_relaxed);
1417 void Timeline::apply_json_to_clips(Json::Value change) {
1420 std::string change_type = change[
"type"].asString();
1421 std::string clip_id =
"";
1422 Clip *existing_clip = NULL;
1425 for (
auto key_part : change[
"key"]) {
1427 if (key_part.isObject()) {
1429 if (!key_part[
"id"].isNull()) {
1431 clip_id = key_part[
"id"].asString();
1434 for (
auto c : clips)
1436 if (c->Id() == clip_id) {
1448 if (existing_clip && change[
"key"].size() == 4 && change[
"key"][2] ==
"effects")
1451 Json::Value key_part = change[
"key"][3];
1453 if (key_part.isObject()) {
1455 if (!key_part[
"id"].isNull())
1458 std::string effect_id = key_part[
"id"].asString();
1461 std::list<EffectBase*> effect_list = existing_clip->
Effects();
1462 for (
auto e : effect_list)
1464 if (e->Id() == effect_id) {
1466 apply_json_to_effects(change, e);
1475 int64_t new_ending_frame = ((existing_clip->
Position() + existing_clip->Duration()) *
info.
fps.
ToDouble()) + 1;
1476 final_cache->
Remove(new_starting_frame - 8, new_ending_frame + 8);
1486 if (change_type ==
"insert") {
1492 allocated_clips.insert(
clip);
1496 clip->ParentTimeline(
this);
1507 final_cache->
Remove(new_starting_frame - 8, new_ending_frame + 8);
1509 }
else if (change_type ==
"update") {
1512 if (existing_clip) {
1515 int64_t old_ending_frame = ((existing_clip->
Position() + existing_clip->Duration()) *
info.
fps.
ToDouble()) + 1;
1522 int64_t new_ending_frame = ((existing_clip->
Position() + existing_clip->Duration()) *
info.
fps.
ToDouble()) + 1;
1525 final_cache->
Remove(old_starting_frame - 8, old_ending_frame + 8);
1526 final_cache->
Remove(new_starting_frame - 8, new_ending_frame + 8);
1529 if (auto_map_clips) {
1530 apply_mapper_to_clip(existing_clip);
1534 }
else if (change_type ==
"delete") {
1537 if (existing_clip) {
1543 int64_t old_ending_frame = ((existing_clip->
Position() + existing_clip->Duration()) *
info.
fps.
ToDouble()) + 1;
1544 final_cache->
Remove(old_starting_frame - 8, old_ending_frame + 8);
1554 void Timeline::apply_json_to_effects(Json::Value change) {
1557 std::string change_type = change[
"type"].asString();
1561 for (
auto key_part : change[
"key"]) {
1563 if (key_part.isObject()) {
1565 if (!key_part[
"id"].isNull())
1568 std::string effect_id = key_part[
"id"].asString();
1571 for (
auto e : effects)
1573 if (e->Id() == effect_id) {
1574 existing_effect = e;
1584 if (existing_effect || change_type ==
"insert") {
1586 apply_json_to_effects(change, existing_effect);
1591 void Timeline::apply_json_to_effects(Json::Value change,
EffectBase* existing_effect) {
1594 std::string change_type = change[
"type"].asString();
1597 if (!change[
"value"].isArray() && !change[
"value"][
"position"].isNull()) {
1598 int64_t new_starting_frame = (change[
"value"][
"position"].asDouble() *
info.
fps.
ToDouble()) + 1;
1599 int64_t new_ending_frame = ((change[
"value"][
"position"].asDouble() + change[
"value"][
"end"].asDouble() - change[
"value"][
"start"].asDouble()) *
info.
fps.
ToDouble()) + 1;
1600 final_cache->
Remove(new_starting_frame - 8, new_ending_frame + 8);
1604 if (change_type ==
"insert") {
1607 std::string effect_type = change[
"value"][
"type"].asString();
1616 allocated_effects.insert(e);
1625 }
else if (change_type ==
"update") {
1628 if (existing_effect) {
1632 int64_t old_ending_frame = ((existing_effect->
Position() + existing_effect->Duration()) *
info.
fps.
ToDouble()) + 1;
1633 final_cache->
Remove(old_starting_frame - 8, old_ending_frame + 8);
1639 }
else if (change_type ==
"delete") {
1642 if (existing_effect) {
1646 int64_t old_ending_frame = ((existing_effect->
Position() + existing_effect->Duration()) *
info.
fps.
ToDouble()) + 1;
1647 final_cache->
Remove(old_starting_frame - 8, old_ending_frame + 8);
1660 void Timeline::apply_json_to_timeline(Json::Value change) {
1661 bool cache_dirty =
true;
1664 std::string change_type = change[
"type"].asString();
1665 std::string root_key = change[
"key"][(uint)0].asString();
1666 std::string sub_key =
"";
1667 if (change[
"key"].size() >= 2)
1668 sub_key = change[
"key"][(uint)1].asString();
1671 if (change_type ==
"insert" || change_type ==
"update") {
1675 if (root_key ==
"color")
1678 else if (root_key ==
"viewport_scale")
1681 else if (root_key ==
"viewport_x")
1684 else if (root_key ==
"viewport_y")
1687 else if (root_key ==
"duration") {
1693 cache_dirty =
false;
1695 else if (root_key ==
"width") {
1700 else if (root_key ==
"height") {
1705 else if (root_key ==
"fps" && sub_key ==
"" && change[
"value"].isObject()) {
1707 if (!change[
"value"][
"num"].isNull())
1708 info.
fps.
num = change[
"value"][
"num"].asInt();
1709 if (!change[
"value"][
"den"].isNull())
1710 info.
fps.
den = change[
"value"][
"den"].asInt();
1712 else if (root_key ==
"fps" && sub_key ==
"num")
1715 else if (root_key ==
"fps" && sub_key ==
"den")
1718 else if (root_key ==
"display_ratio" && sub_key ==
"" && change[
"value"].isObject()) {
1720 if (!change[
"value"][
"num"].isNull())
1722 if (!change[
"value"][
"den"].isNull())
1725 else if (root_key ==
"display_ratio" && sub_key ==
"num")
1728 else if (root_key ==
"display_ratio" && sub_key ==
"den")
1731 else if (root_key ==
"pixel_ratio" && sub_key ==
"" && change[
"value"].isObject()) {
1733 if (!change[
"value"][
"num"].isNull())
1735 if (!change[
"value"][
"den"].isNull())
1738 else if (root_key ==
"pixel_ratio" && sub_key ==
"num")
1741 else if (root_key ==
"pixel_ratio" && sub_key ==
"den")
1745 else if (root_key ==
"sample_rate")
1748 else if (root_key ==
"channels")
1751 else if (root_key ==
"channel_layout")
1756 throw InvalidJSONKey(
"JSON change key is invalid", change.toStyledString());
1759 }
else if (change[
"type"].asString() ==
"delete") {
1763 if (root_key ==
"color") {
1769 else if (root_key ==
"viewport_scale")
1771 else if (root_key ==
"viewport_x")
1773 else if (root_key ==
"viewport_y")
1777 throw InvalidJSONKey(
"JSON change key is invalid", change.toStyledString());
1790 const std::lock_guard<std::recursive_mutex> guard(
getFrameMutex);
1794 final_cache->
Clear();
1799 for (
const auto clip : clips) {
1801 if (
clip->Reader()) {
1802 if (
auto rc =
clip->Reader()->GetCache())
1806 if (deep &&
clip->Reader()->Name() ==
"FrameMapper") {
1808 if (nested_reader->
Reader()) {
1816 if (
auto cc =
clip->GetCache())
1835 display_ratio_size.scale(proposed_size, Qt::KeepAspectRatio);
1843 std::pair<float, float> Timeline::ResolveTransitionAudioGains(
Clip* source_clip, int64_t timeline_frame_number,
bool is_top_clip)
const
1845 constexpr
double half_pi = 1.57079632679489661923;
1848 return {1.0f, 1.0f};
1851 Mask* active_mask =
nullptr;
1852 int64_t effect_start_position = 0;
1853 int64_t effect_end_position = 0;
1856 for (
auto effect : effects) {
1857 if (effect->Layer() != source_clip->
Layer())
1860 auto* mask =
dynamic_cast<Mask*
>(effect);
1861 if (!mask || !mask->fade_audio_hint)
1864 const int64_t start_pos =
static_cast<int64_t
>(std::llround(effect->Position() * fpsD)) + 1;
1865 const int64_t end_pos =
static_cast<int64_t
>(std::llround((effect->Position() + effect->Duration()) * fpsD));
1866 if (start_pos > timeline_frame_number || end_pos < timeline_frame_number)
1870 return {1.0f, 1.0f};
1873 effect_start_position = start_pos;
1874 effect_end_position = end_pos;
1878 return {1.0f, 1.0f};
1880 struct AudibleClipInfo {
1886 std::vector<AudibleClipInfo> audible_clips;
1887 audible_clips.reserve(2);
1890 for (
auto clip : clips) {
1893 if (!
clip->Reader() || !
clip->Reader()->info.has_audio)
1896 const int64_t clip_start_pos =
static_cast<int64_t
>(std::llround(
clip->
Position() * fpsD)) + 1;
1897 const int64_t clip_end_pos =
static_cast<int64_t
>(std::llround((
clip->
Position() +
clip->Duration()) * fpsD));
1898 if (clip_start_pos > timeline_frame_number || clip_end_pos < timeline_frame_number)
1901 const int64_t clip_start_frame =
static_cast<int64_t
>(std::llround(
clip->
Start() * fpsD)) + 1;
1902 const int64_t clip_frame_number = timeline_frame_number - clip_start_pos + clip_start_frame;
1903 if (
clip->has_audio.GetInt(clip_frame_number) == 0)
1906 audible_clips.push_back({
clip, clip_start_pos, clip_end_pos});
1907 if (audible_clips.size() > 2)
1908 return {1.0f, 1.0f};
1911 if (audible_clips.empty())
1912 return {1.0f, 1.0f};
1915 const auto source_it = std::find_if(
1916 audible_clips.begin(),
1917 audible_clips.end(),
1918 [source_clip](
const AudibleClipInfo&
info) {
1919 return info.clip == source_clip;
1921 if (source_it == audible_clips.end())
1922 return {1.0f, 1.0f};
1925 if (audible_clips.size() == 2) {
1926 auto top_it = std::max_element(
1927 audible_clips.begin(),
1928 audible_clips.end(),
1929 [](
const AudibleClipInfo& lhs,
const AudibleClipInfo& rhs) {
1930 if (lhs.start_pos != rhs.start_pos)
1931 return lhs.start_pos < rhs.start_pos;
1932 return std::less<Clip*>()(lhs.clip, rhs.clip);
1934 if ((is_top_clip && source_clip != top_it->clip) || (!is_top_clip && source_clip == top_it->clip))
1935 return {1.0f, 1.0f};
1939 const int64_t left_distance = std::llabs(effect_start_position - source_it->start_pos);
1940 const int64_t right_distance = std::llabs(effect_end_position - source_it->end_pos);
1941 const bool clip_fades_in = left_distance <= right_distance;
1944 const auto compute_gain = [&](int64_t frame_number) ->
float {
1945 if (effect_end_position <= effect_start_position)
1948 const double span =
static_cast<double>(effect_end_position - effect_start_position);
1949 double t =
static_cast<double>(frame_number - effect_start_position) / span;
1955 return static_cast<float>(clip_fades_in ? std::sin(t * half_pi) : std::cos(t * half_pi));
1958 return {compute_gain(timeline_frame_number - 1), compute_gain(timeline_frame_number)};