OpenShot Library | libopenshot  0.7.0
Timeline.cpp
Go to the documentation of this file.
1 
9 // Copyright (c) 2008-2019 OpenShot Studios, LLC
10 //
11 // SPDX-License-Identifier: LGPL-3.0-or-later
12 
13 #include "Timeline.h"
14 
15 #include "CacheBase.h"
16 #include "CacheDisk.h"
17 #include "CacheMemory.h"
18 #include "CrashHandler.h"
19 #include "FrameMapper.h"
20 #include "Exceptions.h"
21 #include "effects/Mask.h"
22 
23 #include <algorithm>
24 #include <QDir>
25 #include <QFileInfo>
26 #include <QRegularExpression>
27 #include <unordered_map>
28 #include <cmath>
29 #include <cstdint>
30 
31 using namespace openshot;
32 
33 // Default Constructor for the timeline (which sets the canvas width and height)
34 Timeline::Timeline(int width, int height, Fraction fps, int sample_rate, int channels, ChannelLayout channel_layout) :
35  is_open(false), auto_map_clips(true), managed_cache(true), path(""), max_time(0.0), cache_epoch(0)
36 {
37  // Create CrashHandler and Attach (incase of errors)
39 
40  // Init viewport size (curve based, because it can be animated)
41  viewport_scale = Keyframe(100.0);
42  viewport_x = Keyframe(0.0);
43  viewport_y = Keyframe(0.0);
44 
45  // Init background color
46  color.red = Keyframe(0.0);
47  color.green = Keyframe(0.0);
48  color.blue = Keyframe(0.0);
49 
50  // Init FileInfo struct (clear all values)
51  info.width = width;
52  info.height = height;
55  info.fps = fps;
56  info.sample_rate = sample_rate;
57  info.channels = channels;
58  info.channel_layout = channel_layout;
60  info.duration = 60 * 30; // 30 minute default duration
61  info.has_audio = true;
62  info.has_video = true;
64  info.display_ratio = openshot::Fraction(width, height);
67  info.acodec = "openshot::timeline";
68  info.vcodec = "openshot::timeline";
69 
70  // Init max image size
72 
73  // Init cache
74  final_cache = new CacheMemory();
75  const int cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, OPEN_MP_NUM_PROCESSORS * 4);
76  final_cache->SetMaxBytesFromInfo(cache_frames, info.width, info.height, info.sample_rate, info.channels);
77 }
78 
79 // Delegating constructor that copies parameters from a provided ReaderInfo
81  info.width, info.height, info.fps, info.sample_rate,
82  info.channels, info.channel_layout) {}
83 
84 // Constructor for the timeline (which loads a JSON structure from a file path, and initializes a timeline)
85 Timeline::Timeline(const std::string& projectPath, bool convert_absolute_paths) :
86  is_open(false), auto_map_clips(true), managed_cache(true), path(projectPath), max_time(0.0), cache_epoch(0) {
87 
88  // Create CrashHandler and Attach (incase of errors)
90 
91  // Init final cache as NULL (will be created after loading json)
92  final_cache = NULL;
93 
94  // Init viewport size (curve based, because it can be animated)
95  viewport_scale = Keyframe(100.0);
96  viewport_x = Keyframe(0.0);
97  viewport_y = Keyframe(0.0);
98 
99  // Init background color
100  color.red = Keyframe(0.0);
101  color.green = Keyframe(0.0);
102  color.blue = Keyframe(0.0);
103 
104  // Check if path exists
105  QFileInfo filePath(QString::fromStdString(path));
106  if (!filePath.exists()) {
107  throw InvalidFile("Timeline project file could not be opened.", path);
108  }
109 
110  // Check OpenShot Install Path exists
112  QDir openshotPath(QString::fromStdString(s->PATH_OPENSHOT_INSTALL));
113  if (!openshotPath.exists()) {
114  throw InvalidFile("PATH_OPENSHOT_INSTALL could not be found.", s->PATH_OPENSHOT_INSTALL);
115  }
116  QDir openshotTransPath(openshotPath.filePath("transitions"));
117  if (!openshotTransPath.exists()) {
118  throw InvalidFile("PATH_OPENSHOT_INSTALL/transitions could not be found.", openshotTransPath.path().toStdString());
119  }
120 
121  // Determine asset path
122  QString asset_name = filePath.baseName().left(30) + "_assets";
123  QDir asset_folder(filePath.dir().filePath(asset_name));
124  if (!asset_folder.exists()) {
125  // Create directory if needed
126  asset_folder.mkpath(".");
127  }
128 
129  // Load UTF-8 project file into QString
130  QFile projectFile(QString::fromStdString(path));
131  projectFile.open(QFile::ReadOnly);
132  QString projectContents = QString::fromUtf8(projectFile.readAll());
133 
134  // Convert all relative paths into absolute paths (if requested)
135  if (convert_absolute_paths) {
136 
137  // Find all "image" or "path" references in JSON (using regex). Must loop through match results
138  // due to our path matching needs, which are not possible with the QString::replace() function.
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()) {
145  // Push all match objects into a vector (so we can reverse them later)
146  matchedPositions.push_back(match);
147  }
148  }
149 
150  // Reverse the matches (bottom of file to top, so our replacements don't break our match positions)
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); // image or path
155  QString relativePath = match.captured(2); // relative file path
156  QString absolutePath = "";
157 
158  // Find absolute path of all path, image (including special replacements of @assets and @transitions)
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();
163  } else {
164  absolutePath = QFileInfo(filePath.absoluteDir().absoluteFilePath(relativePath)).canonicalFilePath();
165  }
166 
167  // Replace path in JSON content, if an absolute path was successfully found
168  if (!absolutePath.isEmpty()) {
169  projectContents.replace(match.capturedStart(0), match.capturedLength(0), "\"" + relativeKey + "\": \"" + absolutePath + "\"");
170  }
171  }
172  // Clear matches
173  matchedPositions.clear();
174  }
175 
176  // Set JSON of project
177  SetJson(projectContents.toStdString());
178 
179  // Calculate valid duration and set has_audio and has_video
180  // based on content inside this Timeline's clips.
181  float calculated_duration = 0.0;
182  for (auto clip : clips)
183  {
184  float clip_last_frame = clip->Position() + clip->Duration();
185  if (clip_last_frame > calculated_duration)
186  calculated_duration = clip_last_frame;
187  if (clip->Reader() && clip->Reader()->info.has_audio)
188  info.has_audio = true;
189  if (clip->Reader() && clip->Reader()->info.has_video)
190  info.has_video = true;
191 
192  }
193  info.video_length = calculated_duration * info.fps.ToFloat();
194  info.duration = calculated_duration;
195 
196  // Init FileInfo settings
197  info.acodec = "openshot::timeline";
198  info.vcodec = "openshot::timeline";
200  info.has_video = true;
201  info.has_audio = true;
202 
203  // Init max image size
205 
206  // Init cache
207  final_cache = new CacheMemory();
208  const int cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, OPEN_MP_NUM_PROCESSORS * 4);
209  final_cache->SetMaxBytesFromInfo(cache_frames, info.width, info.height, info.sample_rate, info.channels);
210 }
211 
213  if (is_open) {
214  // Auto Close if not already
215  Close();
216  }
217 
218  // Remove all clips, effects, and frame mappers
219  Clear();
220 
221  // Destroy previous cache (if managed by timeline)
222  if (managed_cache && final_cache) {
223  delete final_cache;
224  final_cache = NULL;
225  }
226 }
227 
228 // Add to the tracked_objects map a pointer to a tracked object (TrackedObjectBBox)
229 void Timeline::AddTrackedObject(std::shared_ptr<openshot::TrackedObjectBase> trackedObject){
230 
231  // Search for the tracked object on the map
232  auto iterator = tracked_objects.find(trackedObject->Id());
233 
234  if (iterator != tracked_objects.end()){
235  // Tracked object's id already present on the map, overwrite it
236  iterator->second = trackedObject;
237  }
238  else{
239  // Tracked object's id not present -> insert it on the map
240  tracked_objects[trackedObject->Id()] = trackedObject;
241  }
242 
243  return;
244 }
245 
246 // Return tracked object pointer by it's id
247 std::shared_ptr<openshot::TrackedObjectBase> Timeline::GetTrackedObject(std::string id) const{
248 
249  // Search for the tracked object on the map
250  auto iterator = tracked_objects.find(id);
251 
252  if (iterator != tracked_objects.end()){
253  // Id found, return the pointer to the tracked object
254  std::shared_ptr<openshot::TrackedObjectBase> trackedObject = iterator->second;
255  return trackedObject;
256  }
257  else {
258  // Id not found, return a null pointer
259  return nullptr;
260  }
261 }
262 
263 // Return the ID's of the tracked objects as a list of strings
264 std::list<std::string> Timeline::GetTrackedObjectsIds() const{
265 
266  // Create a list of strings
267  std::list<std::string> trackedObjects_ids;
268 
269  // Iterate through the tracked_objects map
270  for (auto const& it: tracked_objects){
271  // Add the IDs to the list
272  trackedObjects_ids.push_back(it.first);
273  }
274 
275  return trackedObjects_ids;
276 }
277 
278 #ifdef USE_OPENCV
279 // Return the trackedObject's properties as a JSON string
280 std::string Timeline::GetTrackedObjectValues(std::string id, int64_t frame_number) const {
281 
282  // Initialize the JSON object
283  Json::Value trackedObjectJson;
284 
285  // Search for the tracked object on the map
286  auto iterator = tracked_objects.find(id);
287 
288  if (iterator != tracked_objects.end())
289  {
290  // Id found, Get the object pointer and cast it as a TrackedObjectBBox
291  std::shared_ptr<TrackedObjectBBox> trackedObject = std::static_pointer_cast<TrackedObjectBBox>(iterator->second);
292 
293  // Get the trackedObject values for it's first frame
294  if (trackedObject->ExactlyContains(frame_number)){
295  BBox box = trackedObject->GetBox(frame_number);
296  float x1 = box.cx - (box.width/2);
297  float y1 = box.cy - (box.height/2);
298  float x2 = box.cx + (box.width/2);
299  float y2 = box.cy + (box.height/2);
300  float rotation = box.angle;
301 
302  trackedObjectJson["x1"] = x1;
303  trackedObjectJson["y1"] = y1;
304  trackedObjectJson["x2"] = x2;
305  trackedObjectJson["y2"] = y2;
306  trackedObjectJson["rotation"] = rotation;
307 
308  } else {
309  BBox box = trackedObject->BoxVec.begin()->second;
310  float x1 = box.cx - (box.width/2);
311  float y1 = box.cy - (box.height/2);
312  float x2 = box.cx + (box.width/2);
313  float y2 = box.cy + (box.height/2);
314  float rotation = box.angle;
315 
316  trackedObjectJson["x1"] = x1;
317  trackedObjectJson["y1"] = y1;
318  trackedObjectJson["x2"] = x2;
319  trackedObjectJson["y2"] = y2;
320  trackedObjectJson["rotation"] = rotation;
321  }
322 
323  }
324  else {
325  // Id not found, return all 0 values
326  trackedObjectJson["x1"] = 0;
327  trackedObjectJson["y1"] = 0;
328  trackedObjectJson["x2"] = 0;
329  trackedObjectJson["y2"] = 0;
330  trackedObjectJson["rotation"] = 0;
331  }
332 
333  return trackedObjectJson.toStyledString();
334 }
335 #endif
336 
337 // Add an openshot::Clip to the timeline
339 {
340  // Get lock (prevent getting frames while this happens)
341  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
342 
343  // Assign timeline to clip
344  clip->ParentTimeline(this);
345 
346  // Clear cache of clip and nested reader (if any)
347  if (clip->Reader() && clip->Reader()->GetCache())
348  clip->Reader()->GetCache()->Clear();
349 
350  // All clips should be converted to the frame rate of this timeline
351  if (auto_map_clips) {
352  // Apply framemapper (or update existing framemapper)
353  apply_mapper_to_clip(clip);
354  }
355 
356  // Add clip to list
357  clips.push_back(clip);
358 
359  // Sort clips
360  sort_clips();
361 }
362 
363 // Add an effect to the timeline
365 {
366  // Get lock (prevent getting frames while this happens)
367  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
368 
369  // Assign timeline to effect
370  effect->ParentTimeline(this);
371 
372  // Add effect to list
373  effects.push_back(effect);
374 
375  // Sort effects
376  sort_effects();
377 }
378 
379 // Remove an effect from the timeline
381 {
382  // Get lock (prevent getting frames while this happens)
383  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
384 
385  effects.remove(effect);
386 
387  // Delete effect object (if timeline allocated it)
388  if (allocated_effects.count(effect)) {
389  allocated_effects.erase(effect); // erase before nulling the pointer
390  delete effect;
391  effect = NULL;
392  }
393 
394  // Sort effects
395  sort_effects();
396 }
397 
398 // Remove an openshot::Clip to the timeline
400 {
401  // Get lock (prevent getting frames while this happens)
402  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
403 
404  clips.remove(clip);
405 
406  // Delete clip object (if timeline allocated it)
407  if (allocated_clips.count(clip)) {
408  allocated_clips.erase(clip); // erase before nulling the pointer
409  delete clip;
410  clip = NULL;
411  }
412 
413  // Sort clips
414  sort_clips();
415 }
416 
417 // Look up a clip
418 openshot::Clip* Timeline::GetClip(const std::string& id)
419 {
420  // Find the matching clip (if any)
421  for (const auto& clip : clips) {
422  if (clip->Id() == id) {
423  return clip;
424  }
425  }
426  return nullptr;
427 }
428 
429 // Look up a timeline effect
431 {
432  // Find the matching effect (if any)
433  for (const auto& effect : effects) {
434  if (effect->Id() == id) {
435  return effect;
436  }
437  }
438  return nullptr;
439 }
440 
442 {
443  // Search all clips for matching effect ID
444  for (const auto& clip : clips) {
445  const auto e = clip->GetEffect(id);
446  if (e != nullptr) {
447  return e;
448  }
449  }
450  return nullptr;
451 }
452 
453 // Return the list of effects on all clips
454 std::list<openshot::EffectBase*> Timeline::ClipEffects() const {
455 
456  // Initialize the list
457  std::list<EffectBase*> timelineEffectsList;
458 
459  // Loop through all clips
460  for (const auto& clip : clips) {
461 
462  // Get the clip's list of effects
463  std::list<EffectBase*> clipEffectsList = clip->Effects();
464 
465  // Append the clip's effects to the list
466  timelineEffectsList.insert(timelineEffectsList.end(), clipEffectsList.begin(), clipEffectsList.end());
467  }
468 
469  return timelineEffectsList;
470 }
471 
472 // Compute the end time of the latest timeline element
474  // Return cached max_time variable (threadsafe)
475  return max_time;
476 }
477 
478 // Compute the highest frame# based on the latest time and FPS
480  const double fps = info.fps.ToDouble();
481  const double t = GetMaxTime();
482  const double frames = t * fps;
483  constexpr double frame_boundary_epsilon = 1e-4;
484 
485  // End is exclusive; ignore tiny float overshoots at frame boundaries.
486  if (frames > 0.0 && frames < frame_boundary_epsilon)
487  return 1;
488  return static_cast<int64_t>(std::ceil(frames - frame_boundary_epsilon));
489 }
490 
491 // Compute the first frame# based on the first clip position
493  const double fps = info.fps.ToDouble();
494  const double t = GetMinTime();
495  // Inclusive start -> floor at the start boundary, then 1-index
496  return static_cast<int64_t>(std::floor(t * fps)) + 1;
497 }
498 
499 // Compute the start time of the first timeline clip
501  // Return cached min_time variable (threadsafe)
502  return min_time;
503 }
504 
505 // Apply a FrameMapper to a clip which matches the settings of this timeline
506 void Timeline::apply_mapper_to_clip(Clip* clip)
507 {
508  // Serialize mapper replacement/reconfiguration with active frame generation.
509  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
510 
511  // Determine type of reader
512  ReaderBase* clip_reader = NULL;
513  if (clip->Reader()->Name() == "FrameMapper")
514  {
515  // Get the existing reader
516  clip_reader = (ReaderBase*) clip->Reader();
517 
518  // Update the mapping
519  FrameMapper* clip_mapped_reader = (FrameMapper*) clip_reader;
521 
522  } else {
523 
524  // Create a new FrameMapper to wrap the current reader
526  allocated_frame_mappers.insert(mapper);
527  clip_reader = (ReaderBase*) mapper;
528  }
529 
530  // Update clip reader
531  clip->Reader(clip_reader);
532 }
533 
534 // Apply the timeline's framerate and samplerate to all clips
536 {
537  // Clear all cached frames
538  ClearAllCache();
539 
540  // Loop through all clips
541  for (auto clip : clips)
542  {
543  // Apply framemapper (or update existing framemapper)
544  apply_mapper_to_clip(clip);
545  }
546 }
547 
548 // Calculate time of a frame number, based on a framerate
549 double Timeline::calculate_time(int64_t number, Fraction rate)
550 {
551  // Get float version of fps fraction
552  double raw_fps = rate.ToFloat();
553 
554  // Return the time (in seconds) of this frame
555  return double(number - 1) / raw_fps;
556 }
557 
558 // Apply effects to the source frame (if any)
559 std::shared_ptr<Frame> Timeline::apply_effects(std::shared_ptr<Frame> frame, int64_t timeline_frame_number, int layer, TimelineInfoStruct* options)
560 {
561  // Debug output
563  "Timeline::apply_effects",
564  "frame->number", frame->number,
565  "timeline_frame_number", timeline_frame_number,
566  "layer", layer);
567 
568  // Find Effects at this position and layer
569  for (auto effect : effects)
570  {
571  // Does clip intersect the current requested time
572  const double fpsD = info.fps.ToDouble();
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));
575 
576  bool does_effect_intersect = (effect_start_position <= timeline_frame_number && effect_end_position >= timeline_frame_number && effect->Layer() == layer);
577 
578  // Clip is visible
579  if (does_effect_intersect)
580  {
581  // Determine the frame needed for this clip (based on the position on the timeline)
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;
584 
585  if (!options->is_top_clip)
586  continue; // skip effect, if overlapped/covered by another clip on same layer
587 
588  if (options->is_before_clip_keyframes != effect->info.apply_before_clip)
589  continue; // skip effect, if this filter does not match
590 
591  // Debug output
593  "Timeline::apply_effects (Process Effect)",
594  "effect_frame_number", effect_frame_number,
595  "does_effect_intersect", does_effect_intersect);
596 
597  // Apply the effect to this frame
598  frame = effect->ProcessFrame(frame, effect_frame_number);
599  }
600 
601  } // end effect loop
602 
603  // Return modified frame
604  return frame;
605 }
606 
607 // Get or generate a blank frame
608 std::shared_ptr<Frame> Timeline::GetOrCreateFrame(std::shared_ptr<Frame> background_frame, Clip* clip, int64_t number, openshot::TimelineInfoStruct* options)
609 {
610  std::shared_ptr<Frame> new_frame;
611 
612  // Init some basic properties about this frame
613  int samples_in_frame = Frame::GetSamplesPerFrame(number, info.fps, info.sample_rate, info.channels);
614 
615  try {
616  // Debug output
618  "Timeline::GetOrCreateFrame (from reader)",
619  "number", number,
620  "samples_in_frame", samples_in_frame);
621 
622  // Attempt to get a frame (but this could fail if a reader has just been closed)
623  new_frame = std::shared_ptr<Frame>(clip->GetFrame(background_frame, number, options));
624 
625  // Return real frame
626  return new_frame;
627 
628  } catch (const ReaderClosed & e) {
629  // ...
630  } catch (const OutOfBoundsFrame & e) {
631  // ...
632  }
633 
634  // Debug output
636  "Timeline::GetOrCreateFrame (create blank)",
637  "number", number,
638  "samples_in_frame", samples_in_frame);
639 
640  // Create blank frame
641  return new_frame;
642 }
643 
644 // Process a new layer of video or audio
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)
646 {
647  // Create timeline options (with details about this current frame request)
648  TimelineInfoStruct options{};
649  options.is_top_clip = is_top_clip;
650  options.is_before_clip_keyframes = true;
651 
652  // Get the clip's frame, composited on top of the current timeline frame
653  std::shared_ptr<Frame> source_frame;
654  source_frame = GetOrCreateFrame(new_frame, source_clip, clip_frame_number, &options);
655 
656  // No frame found... so bail
657  if (!source_frame)
658  return;
659 
660  // Debug output
662  "Timeline::add_layer",
663  "new_frame->number", new_frame->number,
664  "clip_frame_number", clip_frame_number);
665 
666  /* COPY AUDIO - with correct volume */
667  if (source_clip->Reader()->info.has_audio) {
668  // Debug output
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(),
673  "info.channels", info.channels,
674  "clip_frame_number", clip_frame_number);
675 
676  if (source_frame->GetAudioChannelsCount() == info.channels && source_clip->has_audio.GetInt(clip_frame_number) != 0)
677  {
678  // Ensure timeline frame matches the source samples once per frame
679  if (new_frame->GetAudioSamplesCount() != source_frame->GetAudioSamplesCount()){
680  new_frame->ResizeAudio(info.channels, source_frame->GetAudioSamplesCount(), info.sample_rate, info.channel_layout);
681  }
682 
683  // Apply transition-driven equal-power audio fades for clips covered by a Mask transition.
684  const auto transition_audio_gains = ResolveTransitionAudioGains(source_clip, new_frame->number, is_top_clip);
685 
686  for (int channel = 0; channel < source_frame->GetAudioChannelsCount(); channel++)
687  {
688  // Get volume from previous frame and this frame
689  float previous_volume = source_clip->volume.GetValue(clip_frame_number - 1);
690  float volume = source_clip->volume.GetValue(clip_frame_number);
691  previous_volume *= transition_audio_gains.first;
692  volume *= transition_audio_gains.second;
693  int channel_filter = source_clip->channel_filter.GetInt(clip_frame_number); // optional channel to filter (if not -1)
694  int channel_mapping = source_clip->channel_mapping.GetInt(clip_frame_number); // optional channel to map this channel to (if not -1)
695 
696  // Apply volume mixing strategy
697  if (source_clip->mixing == VOLUME_MIX_AVERAGE && max_volume > 1.0) {
698  // Don't allow this clip to exceed 100% (divide volume equally between all overlapping clips with volume
699  previous_volume = previous_volume / max_volume;
700  volume = volume / max_volume;
701  }
702  else if (source_clip->mixing == VOLUME_MIX_REDUCE && max_volume > 1.0) {
703  // Reduce clip volume by a bit, hoping it will prevent exceeding 100% (but it is very possible it will)
704  previous_volume = previous_volume * 0.77;
705  volume = volume * 0.77;
706  }
707 
708  // If channel filter enabled, check for correct channel (and skip non-matching channels)
709  if (channel_filter != -1 && channel_filter != channel)
710  continue; // skip to next channel
711 
712  // If no volume on this frame or previous frame, do nothing
713  if (previous_volume == 0.0 && volume == 0.0)
714  continue; // skip to next channel
715 
716  // If channel mapping disabled, just use the current channel
717  if (channel_mapping == -1)
718  channel_mapping = channel;
719 
720  // Apply ramp to source frame (if needed)
721  if (!isEqual(previous_volume, 1.0) || !isEqual(volume, 1.0))
722  source_frame->ApplyGainRamp(channel_mapping, 0, source_frame->GetAudioSamplesCount(), previous_volume, volume);
723 
724  // Copy audio samples (and set initial volume). Mix samples with existing audio samples. The gains are added together, to
725  // be sure to set the gain's correctly, so the sum does not exceed 1.0 (of audio distortion will happen).
726  new_frame->AddAudio(false, channel_mapping, 0, source_frame->GetAudioSamples(channel), source_frame->GetAudioSamplesCount(), 1.0);
727  }
728  }
729  else
730  // Debug output
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(),
737  "info.channels", info.channels,
738  "clip_frame_number", clip_frame_number);
739  }
740 
741  // Debug output
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());
747 }
748 
749 // Update the list of 'opened' clips
750 void Timeline::update_open_clips(Clip *clip, bool does_clip_intersect)
751 {
752  // Get lock (prevent getting frames while this happens)
753  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
754 
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());
760 
761  // is clip already in list?
762  bool clip_found = open_clips.count(clip);
763 
764  if (clip_found && !does_clip_intersect)
765  {
766  // Remove clip from 'opened' list, because it's closed now
767  open_clips.erase(clip);
768 
769  // Close clip
770  clip->Close();
771  }
772  else if (!clip_found && does_clip_intersect)
773  {
774  // Add clip to 'opened' list, because it's missing
775  open_clips[clip] = clip;
776 
777  try {
778  // Open the clip
779  clip->Open();
780 
781  } catch (const InvalidFile & e) {
782  // ...
783  }
784  }
785 
786  // Debug output
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());
793 }
794 
795 // Calculate the max and min duration (in seconds) of the timeline, based on all the clips, and cache the value
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();
801 
802  // Find the last and first clip
803  if (!clips.empty()) {
804  // Find the clip with the maximum end frame
805  const auto max_clip = std::max_element(
806  clips.begin(), clips.end(), CompareClipEndFrames());
807  last_clip = (*max_clip)->Position() + (*max_clip)->Duration();
808 
809  // Find the clip with the minimum start position (ignoring layer)
810  const auto min_clip = std::min_element(
811  clips.begin(), clips.end(), [](const openshot::Clip* lhs, const openshot::Clip* rhs) {
812  return lhs->Position() < rhs->Position();
813  });
814  first_clip = (*min_clip)->Position();
815  }
816 
817  // Find the last and first effect
818  if (!effects.empty()) {
819  // Find the effect with the maximum end frame
820  const auto max_effect = std::max_element(
821  effects.begin(), effects.end(), CompareEffectEndFrames());
822  last_effect = (*max_effect)->Position() + (*max_effect)->Duration();
823 
824  // Find the effect with the minimum start position
825  const auto min_effect = std::min_element(
826  effects.begin(), effects.end(), [](const openshot::EffectBase* lhs, const openshot::EffectBase* rhs) {
827  return lhs->Position() < rhs->Position();
828  });
829  first_effect = (*min_effect)->Position();
830  }
831 
832  // Calculate the max and min time
833  max_time = std::max(last_clip, last_effect);
834  min_time = std::min(first_clip, first_effect);
835 
836  // If no clips or effects exist, set min_time to 0
837  if (clips.empty() && effects.empty()) {
838  min_time = 0.0;
839  max_time = 0.0;
840  }
841 }
842 
843 // Sort clips by position on the timeline
844 void Timeline::sort_clips()
845 {
846  // Get lock (prevent getting frames while this happens)
847  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
848 
849  // Debug output
851  "Timeline::SortClips",
852  "clips.size()", clips.size());
853 
854  // sort clips
855  clips.sort(CompareClips());
856 
857  // calculate max timeline duration
858  calculate_max_duration();
859 }
860 
861 // Sort effects by position on the timeline
862 void Timeline::sort_effects()
863 {
864  // Get lock (prevent getting frames while this happens)
865  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
866 
867  // sort clips
868  effects.sort(CompareEffects());
869 
870  // calculate max timeline duration
871  calculate_max_duration();
872 }
873 
874 // Clear all clips from timeline
876 {
877  ZmqLogger::Instance()->AppendDebugMethod("Timeline::Clear");
878 
879  // Get lock (prevent getting frames while this happens)
880  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
881 
882  // Close all open clips
883  for (auto clip : clips)
884  {
885  update_open_clips(clip, false);
886 
887  // Delete clip object (if timeline allocated it)
888  bool allocated = allocated_clips.count(clip);
889  if (allocated) {
890  delete clip;
891  }
892  }
893  // Clear all clips
894  clips.clear();
895  allocated_clips.clear();
896 
897  // Close all effects
898  for (auto effect : effects)
899  {
900  // Delete effect object (if timeline allocated it)
901  bool allocated = allocated_effects.count(effect);
902  if (allocated) {
903  delete effect;
904  }
905  }
906  // Clear all effects
907  effects.clear();
908  allocated_effects.clear();
909 
910  // Delete all FrameMappers
911  for (auto mapper : allocated_frame_mappers)
912  {
913  mapper->Reader(NULL);
914  mapper->Close();
915  delete mapper;
916  }
917  allocated_frame_mappers.clear();
918 }
919 
920 // Close the reader (and any resources it was consuming)
922 {
923  ZmqLogger::Instance()->AppendDebugMethod("Timeline::Close");
924 
925  // Get lock (prevent getting frames while this happens)
926  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
927 
928  // Close all open clips
929  for (auto clip : clips)
930  {
931  // Open or Close this clip, based on if it's intersecting or not
932  update_open_clips(clip, false);
933  }
934 
935  // Mark timeline as closed
936  is_open = false;
937 
938  // Clear all cache (deep clear, including nested Readers)
939  ClearAllCache(true);
940 }
941 
942 // Open the reader (and start consuming resources)
944 {
945  is_open = true;
946 }
947 
948 // Compare 2 floating point numbers for equality
949 bool Timeline::isEqual(double a, double b)
950 {
951  return fabs(a - b) < 0.000001;
952 }
953 
954 // Get an openshot::Frame object for a specific frame number of this reader.
955 std::shared_ptr<Frame> Timeline::GetFrame(int64_t requested_frame)
956 {
957  // Adjust out of bounds frame number
958  if (requested_frame < 1)
959  requested_frame = 1;
960  const int64_t max_frame = GetMaxFrame();
961  const bool past_timeline_end = (max_frame > 0 && requested_frame > max_frame);
962 
963  // Check cache
964  std::shared_ptr<Frame> frame;
965  if (!past_timeline_end)
966  frame = final_cache->GetFrame(requested_frame);
967  if (frame) {
968  // Debug output
970  "Timeline::GetFrame (Cached frame found)",
971  "requested_frame", requested_frame);
972 
973  // Return cached frame
974  return frame;
975  }
976  else
977  {
978  // Prevent async calls to the following code
979  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
980 
981  // Check cache 2nd time
982  std::shared_ptr<Frame> frame;
983  if (!past_timeline_end)
984  frame = final_cache->GetFrame(requested_frame);
985  if (frame) {
986  // Debug output
988  "Timeline::GetFrame (Cached frame found on 2nd check)",
989  "requested_frame", requested_frame);
990 
991  // Return cached frame
992  return frame;
993  } else {
994  // Get a list of clips that intersect with the requested section of timeline
995  // This also opens the readers for intersecting clips, and marks non-intersecting clips as 'needs closing'
996  std::vector<Clip *> nearby_clips;
997  nearby_clips = find_intersecting_clips(requested_frame, 1, true);
998 
999  // Debug output
1001  "Timeline::GetFrame (processing frame)",
1002  "requested_frame", requested_frame,
1003  "omp_get_thread_num()", omp_get_thread_num());
1004 
1005  // Init some basic properties about this frame
1006  int samples_in_frame = Frame::GetSamplesPerFrame(requested_frame, info.fps, info.sample_rate, info.channels);
1007 
1008  // Create blank frame (which will become the requested frame)
1009  std::shared_ptr<Frame> new_frame(std::make_shared<Frame>(requested_frame, preview_width, preview_height, "#000000", samples_in_frame, info.channels));
1010  new_frame->AddAudioSilence(samples_in_frame);
1011  new_frame->SampleRate(info.sample_rate);
1012  new_frame->ChannelsLayout(info.channel_layout);
1013 
1014  // Debug output
1016  "Timeline::GetFrame (Adding solid color)",
1017  "requested_frame", requested_frame,
1018  "info.width", info.width,
1019  "info.height", info.height);
1020 
1021  // Add Background Color to 1st layer (if animated or not black)
1022  if ((color.red.GetCount() > 1 || color.green.GetCount() > 1 || color.blue.GetCount() > 1) ||
1023  (color.red.GetValue(requested_frame) != 0.0 || color.green.GetValue(requested_frame) != 0.0 ||
1024  color.blue.GetValue(requested_frame) != 0.0))
1025  new_frame->AddColor(preview_width, preview_height, color.GetColorHex(requested_frame));
1026 
1027  // Debug output
1029  "Timeline::GetFrame (Loop through clips)",
1030  "requested_frame", requested_frame,
1031  "clips.size()", clips.size(),
1032  "nearby_clips.size()", nearby_clips.size());
1033 
1034  // Precompute per-clip timing for this requested frame
1035  struct ClipInfo {
1036  Clip* clip;
1037  int64_t start_pos;
1038  int64_t end_pos;
1039  int64_t start_frame;
1040  int64_t frame_number;
1041  bool intersects;
1042  };
1043  std::vector<ClipInfo> clip_infos;
1044  clip_infos.reserve(nearby_clips.size());
1045  const double fpsD = info.fps.ToDouble();
1046 
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});
1054  }
1055 
1056  // Determine top clip per layer (linear, no nested loop)
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; // strictly greater to match prior logic
1065  top_clip_for_layer[layer] = ci.clip;
1066  }
1067  }
1068 
1069  // Compute max_volume across all overlapping clips once
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));
1076  }
1077  }
1078 
1079  // Compose intersecting clips in a single pass
1080  for (const auto& ci : clip_infos) {
1081  // Debug output
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);
1088 
1089  // Clip is visible
1090  if (ci.intersects) {
1091  // Is this the top clip on its layer?
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);
1097 
1098  // Determine the frame needed for this clip (based on the position on the timeline)
1099  int64_t clip_frame_number = ci.frame_number;
1100 
1101  // Debug output
1103  "Timeline::GetFrame (Calculate clip's frame #)",
1104  "clip->Position()", ci.clip->Position(),
1105  "clip->Start()", ci.clip->Start(),
1106  "info.fps.ToFloat()", info.fps.ToFloat(),
1107  "clip_frame_number", clip_frame_number);
1108 
1109  // Add clip's frame as layer
1110  add_layer(new_frame, ci.clip, clip_frame_number, is_top_clip, max_volume_sum);
1111 
1112  } else {
1113  // Debug output
1115  "Timeline::GetFrame (clip does not intersect)",
1116  "requested_frame", requested_frame,
1117  "does_clip_intersect", ci.intersects);
1118  }
1119 
1120  } // end clip loop
1121 
1122  // Debug output
1124  "Timeline::GetFrame (Add frame to cache)",
1125  "requested_frame", requested_frame,
1126  "info.width", info.width,
1127  "info.height", info.height);
1128 
1129  // Set frame # on mapped frame
1130  new_frame->SetFrameNumber(requested_frame);
1131 
1132  // Add final frame to cache (only for valid timeline range)
1133  if (!past_timeline_end)
1134  final_cache->Add(new_frame);
1135  // Return frame (or blank frame)
1136  return new_frame;
1137  }
1138  }
1139 }
1140 
1141 
1142 // Find intersecting clips (or non intersecting clips)
1143 std::vector<Clip*> Timeline::find_intersecting_clips(int64_t requested_frame, int number_of_frames, bool include)
1144 {
1145  // Find matching clips
1146  std::vector<Clip*> matching_clips;
1147 
1148  // Calculate time of frame
1149  const int64_t min_requested_frame = requested_frame;
1150  const int64_t max_requested_frame = requested_frame + (number_of_frames - 1);
1151 
1152  // Find Clips at this time
1153  matching_clips.reserve(clips.size());
1154  const double fpsD = info.fps.ToDouble();
1155  for (auto clip : clips)
1156  {
1157  // Does clip intersect the current requested time
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;
1160 
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);
1164 
1165  // Debug output
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,
1171  "clip->Position()", clip->Position(),
1172  "does_clip_intersect", does_clip_intersect);
1173 
1174  // Open (or schedule for closing) this clip, based on if it's intersecting or not
1175  update_open_clips(clip, does_clip_intersect);
1176 
1177  // Clip is visible
1178  if (does_clip_intersect && include)
1179  // Add the intersecting clip
1180  matching_clips.push_back(clip);
1181 
1182  else if (!does_clip_intersect && !include)
1183  // Add the non-intersecting clip
1184  matching_clips.push_back(clip);
1185 
1186  } // end clip loop
1187 
1188  // return list
1189  return matching_clips;
1190 }
1191 
1192 // Set the cache object used by this reader
1193 void Timeline::SetCache(CacheBase* new_cache) {
1194  // Get lock (prevent getting frames while this happens)
1195  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1196 
1197  // Destroy previous cache (if managed by timeline)
1198  if (managed_cache && final_cache) {
1199  delete final_cache;
1200  final_cache = NULL;
1201  managed_cache = false;
1202  }
1203 
1204  // Set new cache
1205  final_cache = new_cache;
1206 }
1207 
1208 // Generate JSON string of this object
1209 std::string Timeline::Json() const {
1210 
1211  // Return formatted string
1212  return JsonValue().toStyledString();
1213 }
1214 
1215 // Generate Json::Value for this object
1216 Json::Value Timeline::JsonValue() const {
1217 
1218  // Create root json object
1219  Json::Value root = ReaderBase::JsonValue(); // get parent properties
1220  root["type"] = "Timeline";
1221  root["viewport_scale"] = viewport_scale.JsonValue();
1222  root["viewport_x"] = viewport_x.JsonValue();
1223  root["viewport_y"] = viewport_y.JsonValue();
1224  root["color"] = color.JsonValue();
1225  root["path"] = path;
1226 
1227  // Add array of clips
1228  root["clips"] = Json::Value(Json::arrayValue);
1229 
1230  // Find Clips at this time
1231  for (const auto existing_clip : clips)
1232  {
1233  root["clips"].append(existing_clip->JsonValue());
1234  }
1235 
1236  // Add array of effects
1237  root["effects"] = Json::Value(Json::arrayValue);
1238 
1239  // loop through effects
1240  for (const auto existing_effect: effects)
1241  {
1242  root["effects"].append(existing_effect->JsonValue());
1243  }
1244 
1245  // return JsonValue
1246  return root;
1247 }
1248 
1249 // Load JSON string into this object
1250 void Timeline::SetJson(const std::string value) {
1251 
1252  // Get lock (prevent getting frames while this happens)
1253  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1254 
1255  // Parse JSON string into JSON objects
1256  try
1257  {
1258  const Json::Value root = openshot::stringToJson(value);
1259  // Set all values that match
1260  SetJsonValue(root);
1261  }
1262  catch (const std::exception& e)
1263  {
1264  // Error parsing JSON (or missing keys)
1265  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
1266  }
1267 }
1268 
1269 // Load Json::Value into this object
1270 void Timeline::SetJsonValue(const Json::Value root) {
1271 
1272  // Get lock (prevent getting frames while this happens)
1273  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1274 
1275  // Close timeline before we do anything (this closes all clips)
1276  bool was_open = is_open;
1277  Close();
1278 
1279  // Set parent data
1281 
1282  // Set data from Json (if key is found)
1283  if (!root["path"].isNull())
1284  path = root["path"].asString();
1285 
1286  if (!root["clips"].isNull()) {
1287  // Clear existing clips
1288  clips.clear();
1289 
1290  // loop through clips
1291  for (const Json::Value existing_clip : root["clips"]) {
1292  // Skip NULL nodes
1293  if (existing_clip.isNull()) {
1294  continue;
1295  }
1296 
1297  // Create Clip
1298  Clip *c = new Clip();
1299 
1300  // Keep track of allocated clip objects
1301  allocated_clips.insert(c);
1302 
1303  // When a clip is attached to an object, it searches for the object
1304  // on it's parent timeline. Setting the parent timeline of the clip here
1305  // allows attaching it to an object when exporting the project (because)
1306  // the exporter script initializes the clip and it's effects
1307  // before setting its parent timeline.
1308  c->ParentTimeline(this);
1309 
1310  // Load Json into Clip
1311  c->SetJsonValue(existing_clip);
1312 
1313  // Add Clip to Timeline
1314  AddClip(c);
1315  }
1316  }
1317 
1318  if (!root["effects"].isNull()) {
1319  // Clear existing effects
1320  effects.clear();
1321 
1322  // loop through effects
1323  for (const Json::Value existing_effect :root["effects"]) {
1324  // Skip NULL nodes
1325  if (existing_effect.isNull()) {
1326  continue;
1327  }
1328 
1329  // Create Effect
1330  EffectBase *e = NULL;
1331 
1332  if (!existing_effect["type"].isNull()) {
1333  // Create instance of effect
1334  if ( (e = EffectInfo().CreateEffect(existing_effect["type"].asString())) ) {
1335 
1336  // Keep track of allocated effect objects
1337  allocated_effects.insert(e);
1338 
1339  // Load Json into Effect
1340  e->SetJsonValue(existing_effect);
1341 
1342  // Add Effect to Timeline
1343  AddEffect(e);
1344  }
1345  }
1346  }
1347  }
1348 
1349  if (!root["duration"].isNull()) {
1350  // Update duration of timeline
1351  info.duration = root["duration"].asDouble();
1353  }
1354 
1355  // Update preview settings
1358 
1359  // Resort (and recalculate min/max duration)
1360  sort_clips();
1361  sort_effects();
1362 
1363  // Re-open if needed
1364  if (was_open)
1365  Open();
1366 
1367  // Timeline content changed: notify cache clients to rescan active window.
1368  BumpCacheEpoch();
1369 }
1370 
1371 // Apply a special formatted JSON object, which represents a change to the timeline (insert, update, delete)
1372 void Timeline::ApplyJsonDiff(std::string value) {
1373 
1374  // Get lock (prevent getting frames while this happens)
1375  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1376 
1377  // Parse JSON string into JSON objects
1378  try
1379  {
1380  const Json::Value root = openshot::stringToJson(value);
1381  // Process the JSON change array, loop through each item
1382  for (const Json::Value change : root) {
1383  std::string change_key = change["key"][(uint)0].asString();
1384 
1385  // Process each type of change
1386  if (change_key == "clips")
1387  // Apply to CLIPS
1388  apply_json_to_clips(change);
1389 
1390  else if (change_key == "effects")
1391  // Apply to EFFECTS
1392  apply_json_to_effects(change);
1393 
1394  else
1395  // Apply to TIMELINE
1396  apply_json_to_timeline(change);
1397 
1398  }
1399 
1400  // Timeline content changed: notify cache clients to rescan active window.
1401  if (!root.empty()) {
1402  BumpCacheEpoch();
1403  }
1404  }
1405  catch (const std::exception& e)
1406  {
1407  // Error parsing JSON (or missing keys)
1408  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
1409  }
1410 }
1411 
1412 void Timeline::BumpCacheEpoch() {
1413  cache_epoch.fetch_add(1, std::memory_order_relaxed);
1414 }
1415 
1416 // Apply JSON diff to clips
1417 void Timeline::apply_json_to_clips(Json::Value change) {
1418 
1419  // Get key and type of change
1420  std::string change_type = change["type"].asString();
1421  std::string clip_id = "";
1422  Clip *existing_clip = NULL;
1423 
1424  // Find id of clip (if any)
1425  for (auto key_part : change["key"]) {
1426  // Get each change
1427  if (key_part.isObject()) {
1428  // Check for id
1429  if (!key_part["id"].isNull()) {
1430  // Set the id
1431  clip_id = key_part["id"].asString();
1432 
1433  // Find matching clip in timeline (if any)
1434  for (auto c : clips)
1435  {
1436  if (c->Id() == clip_id) {
1437  existing_clip = c;
1438  break; // clip found, exit loop
1439  }
1440  }
1441  break; // id found, exit loop
1442  }
1443  }
1444  }
1445 
1446  // Check for a more specific key (targetting this clip's effects)
1447  // For example: ["clips", {"id:123}, "effects", {"id":432}]
1448  if (existing_clip && change["key"].size() == 4 && change["key"][2] == "effects")
1449  {
1450  // This change is actually targetting a specific effect under a clip (and not the clip)
1451  Json::Value key_part = change["key"][3];
1452 
1453  if (key_part.isObject()) {
1454  // Check for id
1455  if (!key_part["id"].isNull())
1456  {
1457  // Set the id
1458  std::string effect_id = key_part["id"].asString();
1459 
1460  // Find matching effect in timeline (if any)
1461  std::list<EffectBase*> effect_list = existing_clip->Effects();
1462  for (auto e : effect_list)
1463  {
1464  if (e->Id() == effect_id) {
1465  // Apply the change to the effect directly
1466  apply_json_to_effects(change, e);
1467 
1468  // Effect-only diffs must clear the owning clip cache.
1469  if (existing_clip->GetCache()) {
1470  existing_clip->GetCache()->Clear();
1471  }
1472 
1473  // Calculate start and end frames that this impacts, and remove those frames from the cache
1474  int64_t new_starting_frame = (existing_clip->Position() * info.fps.ToDouble()) + 1;
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);
1477 
1478  return; // effect found, don't update clip
1479  }
1480  }
1481  }
1482  }
1483  }
1484 
1485  // Determine type of change operation
1486  if (change_type == "insert") {
1487 
1488  // Create clip
1489  Clip *clip = new Clip();
1490 
1491  // Keep track of allocated clip objects
1492  allocated_clips.insert(clip);
1493 
1494  // Match full timeline JSON loading: parent timeline must be available
1495  // before clip JSON can inflate nested readers/effects.
1496  clip->ParentTimeline(this);
1497 
1498  // Set properties of clip from JSON
1499  clip->SetJsonValue(change["value"]);
1500 
1501  // Add clip to timeline
1502  AddClip(clip);
1503 
1504  // Calculate start and end frames that this impacts, and remove those frames from the cache
1505  int64_t new_starting_frame = (clip->Position() * info.fps.ToDouble()) + 1;
1506  int64_t new_ending_frame = ((clip->Position() + clip->Duration()) * info.fps.ToDouble()) + 1;
1507  final_cache->Remove(new_starting_frame - 8, new_ending_frame + 8);
1508 
1509  } else if (change_type == "update") {
1510 
1511  // Update existing clip
1512  if (existing_clip) {
1513  // Calculate start and end frames prior to the update
1514  int64_t old_starting_frame = (existing_clip->Position() * info.fps.ToDouble()) + 1;
1515  int64_t old_ending_frame = ((existing_clip->Position() + existing_clip->Duration()) * info.fps.ToDouble()) + 1;
1516 
1517  // Update clip properties from JSON
1518  existing_clip->SetJsonValue(change["value"]);
1519 
1520  // Calculate new start and end frames after the update
1521  int64_t new_starting_frame = (existing_clip->Position() * info.fps.ToDouble()) + 1;
1522  int64_t new_ending_frame = ((existing_clip->Position() + existing_clip->Duration()) * info.fps.ToDouble()) + 1;
1523 
1524  // Remove both the old and new ranges from the timeline cache
1525  final_cache->Remove(old_starting_frame - 8, old_ending_frame + 8);
1526  final_cache->Remove(new_starting_frame - 8, new_ending_frame + 8);
1527 
1528  // Apply framemapper (or update existing framemapper)
1529  if (auto_map_clips) {
1530  apply_mapper_to_clip(existing_clip);
1531  }
1532  }
1533 
1534  } else if (change_type == "delete") {
1535 
1536  // Remove existing clip
1537  if (existing_clip) {
1538  // Remove clip from timeline
1539  RemoveClip(existing_clip);
1540 
1541  // Calculate start and end frames that this impacts, and remove those frames from the cache
1542  int64_t old_starting_frame = (existing_clip->Position() * info.fps.ToDouble()) + 1;
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);
1545  }
1546 
1547  }
1548 
1549  // Re-Sort Clips (since they likely changed)
1550  sort_clips();
1551 }
1552 
1553 // Apply JSON diff to effects
1554 void Timeline::apply_json_to_effects(Json::Value change) {
1555 
1556  // Get key and type of change
1557  std::string change_type = change["type"].asString();
1558  EffectBase *existing_effect = NULL;
1559 
1560  // Find id of an effect (if any)
1561  for (auto key_part : change["key"]) {
1562 
1563  if (key_part.isObject()) {
1564  // Check for id
1565  if (!key_part["id"].isNull())
1566  {
1567  // Set the id
1568  std::string effect_id = key_part["id"].asString();
1569 
1570  // Find matching effect in timeline (if any)
1571  for (auto e : effects)
1572  {
1573  if (e->Id() == effect_id) {
1574  existing_effect = e;
1575  break; // effect found, exit loop
1576  }
1577  }
1578  break; // id found, exit loop
1579  }
1580  }
1581  }
1582 
1583  // Now that we found the effect, apply the change to it
1584  if (existing_effect || change_type == "insert") {
1585  // Apply change to effect
1586  apply_json_to_effects(change, existing_effect);
1587  }
1588 }
1589 
1590 // Apply JSON diff to effects (if you already know which effect needs to be updated)
1591 void Timeline::apply_json_to_effects(Json::Value change, EffectBase* existing_effect) {
1592 
1593  // Get key and type of change
1594  std::string change_type = change["type"].asString();
1595 
1596  // Calculate start and end frames that this impacts, and remove those frames from the cache
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);
1601  }
1602 
1603  // Determine type of change operation
1604  if (change_type == "insert") {
1605 
1606  // Determine type of effect
1607  std::string effect_type = change["value"]["type"].asString();
1608 
1609  // Create Effect
1610  EffectBase *e = NULL;
1611 
1612  // Init the matching effect object
1613  if ( (e = EffectInfo().CreateEffect(effect_type)) ) {
1614 
1615  // Keep track of allocated effect objects
1616  allocated_effects.insert(e);
1617 
1618  // Load Json into Effect
1619  e->SetJsonValue(change["value"]);
1620 
1621  // Add Effect to Timeline
1622  AddEffect(e);
1623  }
1624 
1625  } else if (change_type == "update") {
1626 
1627  // Update existing effect
1628  if (existing_effect) {
1629 
1630  // Calculate start and end frames that this impacts, and remove those frames from the cache
1631  int64_t old_starting_frame = (existing_effect->Position() * info.fps.ToDouble()) + 1;
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);
1634 
1635  // Update effect properties from JSON
1636  existing_effect->SetJsonValue(change["value"]);
1637  }
1638 
1639  } else if (change_type == "delete") {
1640 
1641  // Remove existing effect
1642  if (existing_effect) {
1643 
1644  // Calculate start and end frames that this impacts, and remove those frames from the cache
1645  int64_t old_starting_frame = (existing_effect->Position() * info.fps.ToDouble()) + 1;
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);
1648 
1649  // Remove effect from timeline
1650  RemoveEffect(existing_effect);
1651  }
1652 
1653  }
1654 
1655  // Re-Sort Effects (since they likely changed)
1656  sort_effects();
1657 }
1658 
1659 // Apply JSON diff to timeline properties
1660 void Timeline::apply_json_to_timeline(Json::Value change) {
1661  bool cache_dirty = true;
1662 
1663  // Get key and type of change
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();
1669 
1670  // Determine type of change operation
1671  if (change_type == "insert" || change_type == "update") {
1672 
1673  // INSERT / UPDATE
1674  // Check for valid property
1675  if (root_key == "color")
1676  // Set color
1677  color.SetJsonValue(change["value"]);
1678  else if (root_key == "viewport_scale")
1679  // Set viewport scale
1680  viewport_scale.SetJsonValue(change["value"]);
1681  else if (root_key == "viewport_x")
1682  // Set viewport x offset
1683  viewport_x.SetJsonValue(change["value"]);
1684  else if (root_key == "viewport_y")
1685  // Set viewport y offset
1686  viewport_y.SetJsonValue(change["value"]);
1687  else if (root_key == "duration") {
1688  // Update duration of timeline
1689  info.duration = change["value"].asDouble();
1691 
1692  // We don't want to clear cache for duration adjustments
1693  cache_dirty = false;
1694  }
1695  else if (root_key == "width") {
1696  // Set width
1697  info.width = change["value"].asInt();
1699  }
1700  else if (root_key == "height") {
1701  // Set height
1702  info.height = change["value"].asInt();
1704  }
1705  else if (root_key == "fps" && sub_key == "" && change["value"].isObject()) {
1706  // Set fps fraction
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();
1711  }
1712  else if (root_key == "fps" && sub_key == "num")
1713  // Set fps.num
1714  info.fps.num = change["value"].asInt();
1715  else if (root_key == "fps" && sub_key == "den")
1716  // Set fps.den
1717  info.fps.den = change["value"].asInt();
1718  else if (root_key == "display_ratio" && sub_key == "" && change["value"].isObject()) {
1719  // Set display_ratio fraction
1720  if (!change["value"]["num"].isNull())
1721  info.display_ratio.num = change["value"]["num"].asInt();
1722  if (!change["value"]["den"].isNull())
1723  info.display_ratio.den = change["value"]["den"].asInt();
1724  }
1725  else if (root_key == "display_ratio" && sub_key == "num")
1726  // Set display_ratio.num
1727  info.display_ratio.num = change["value"].asInt();
1728  else if (root_key == "display_ratio" && sub_key == "den")
1729  // Set display_ratio.den
1730  info.display_ratio.den = change["value"].asInt();
1731  else if (root_key == "pixel_ratio" && sub_key == "" && change["value"].isObject()) {
1732  // Set pixel_ratio fraction
1733  if (!change["value"]["num"].isNull())
1734  info.pixel_ratio.num = change["value"]["num"].asInt();
1735  if (!change["value"]["den"].isNull())
1736  info.pixel_ratio.den = change["value"]["den"].asInt();
1737  }
1738  else if (root_key == "pixel_ratio" && sub_key == "num")
1739  // Set pixel_ratio.num
1740  info.pixel_ratio.num = change["value"].asInt();
1741  else if (root_key == "pixel_ratio" && sub_key == "den")
1742  // Set pixel_ratio.den
1743  info.pixel_ratio.den = change["value"].asInt();
1744 
1745  else if (root_key == "sample_rate")
1746  // Set sample rate
1747  info.sample_rate = change["value"].asInt();
1748  else if (root_key == "channels")
1749  // Set channels
1750  info.channels = change["value"].asInt();
1751  else if (root_key == "channel_layout")
1752  // Set channel layout
1753  info.channel_layout = (ChannelLayout) change["value"].asInt();
1754  else
1755  // Error parsing JSON (or missing keys)
1756  throw InvalidJSONKey("JSON change key is invalid", change.toStyledString());
1757 
1758 
1759  } else if (change["type"].asString() == "delete") {
1760 
1761  // DELETE / RESET
1762  // Reset the following properties (since we can't delete them)
1763  if (root_key == "color") {
1764  color = Color();
1765  color.red = Keyframe(0.0);
1766  color.green = Keyframe(0.0);
1767  color.blue = Keyframe(0.0);
1768  }
1769  else if (root_key == "viewport_scale")
1770  viewport_scale = Keyframe(1.0);
1771  else if (root_key == "viewport_x")
1772  viewport_x = Keyframe(0.0);
1773  else if (root_key == "viewport_y")
1774  viewport_y = Keyframe(0.0);
1775  else
1776  // Error parsing JSON (or missing keys)
1777  throw InvalidJSONKey("JSON change key is invalid", change.toStyledString());
1778 
1779  }
1780 
1781  if (cache_dirty) {
1782  // Clear entire cache
1783  ClearAllCache();
1784  }
1785 }
1786 
1787 // Clear all caches
1788 void Timeline::ClearAllCache(bool deep) {
1789  // Get lock (prevent getting frames while this happens)
1790  const std::lock_guard<std::recursive_mutex> guard(getFrameMutex);
1791 
1792  // Clear primary cache
1793  if (final_cache) {
1794  final_cache->Clear();
1795  }
1796 
1797  // Loop through all clips
1798  try {
1799  for (const auto clip : clips) {
1800  // Clear cache on clip and reader if present
1801  if (clip->Reader()) {
1802  if (auto rc = clip->Reader()->GetCache())
1803  rc->Clear();
1804 
1805  // Clear nested Reader (if deep clear requested)
1806  if (deep && clip->Reader()->Name() == "FrameMapper") {
1807  FrameMapper *nested_reader = static_cast<FrameMapper *>(clip->Reader());
1808  if (nested_reader->Reader()) {
1809  if (auto nc = nested_reader->Reader()->GetCache())
1810  nc->Clear();
1811  }
1812  }
1813  }
1814 
1815  // Clear clip cache
1816  if (auto cc = clip->GetCache())
1817  cc->Clear();
1818  }
1819  } catch (const ReaderClosed & e) {
1820  // ...
1821  }
1822 
1823  // Cache content changed: notify cache clients to rebuild their window baseline.
1824  BumpCacheEpoch();
1825 }
1826 
1827 // Set Max Image Size (used for performance optimization). Convenience function for setting
1828 // Settings::Instance()->MAX_WIDTH and Settings::Instance()->MAX_HEIGHT.
1829 void Timeline::SetMaxSize(int width, int height) {
1830  // Maintain aspect ratio regardless of what size is passed in
1831  QSize display_ratio_size = QSize(info.width, info.height);
1832  QSize proposed_size = QSize(std::min(width, info.width), std::min(height, info.height));
1833 
1834  // Scale QSize up to proposed size
1835  display_ratio_size.scale(proposed_size, Qt::KeepAspectRatio);
1836 
1837  // Update preview settings
1838  preview_width = display_ratio_size.width();
1839  preview_height = display_ratio_size.height();
1840 }
1841 
1842 // Resolve equal-power audio gains from transition placement relative to the clip edges.
1843 std::pair<float, float> Timeline::ResolveTransitionAudioGains(Clip* source_clip, int64_t timeline_frame_number, bool is_top_clip) const
1844 {
1845  constexpr double half_pi = 1.57079632679489661923;
1846 
1847  if (!source_clip)
1848  return {1.0f, 1.0f};
1849 
1850  const double fpsD = info.fps.ToDouble();
1851  Mask* active_mask = nullptr;
1852  int64_t effect_start_position = 0;
1853  int64_t effect_end_position = 0;
1854 
1855  // Find the single active transition on this layer that requested overlapping audio fades.
1856  for (auto effect : effects) {
1857  if (effect->Layer() != source_clip->Layer())
1858  continue;
1859 
1860  auto* mask = dynamic_cast<Mask*>(effect);
1861  if (!mask || !mask->fade_audio_hint)
1862  continue;
1863 
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)
1867  continue;
1868 
1869  if (active_mask)
1870  return {1.0f, 1.0f};
1871 
1872  active_mask = mask;
1873  effect_start_position = start_pos;
1874  effect_end_position = end_pos;
1875  }
1876 
1877  if (!active_mask)
1878  return {1.0f, 1.0f};
1879 
1880  struct AudibleClipInfo {
1881  Clip* clip;
1882  int64_t start_pos;
1883  int64_t end_pos;
1884  };
1885 
1886  std::vector<AudibleClipInfo> audible_clips;
1887  audible_clips.reserve(2);
1888 
1889  // Collect the audible clips covered by this transition on the current layer.
1890  for (auto clip : clips) {
1891  if (clip->Layer() != source_clip->Layer())
1892  continue;
1893  if (!clip->Reader() || !clip->Reader()->info.has_audio)
1894  continue;
1895 
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)
1899  continue;
1900 
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)
1904  continue;
1905 
1906  audible_clips.push_back({clip, clip_start_pos, clip_end_pos});
1907  if (audible_clips.size() > 2)
1908  return {1.0f, 1.0f};
1909  }
1910 
1911  if (audible_clips.empty())
1912  return {1.0f, 1.0f};
1913 
1914  // Skip clips that are not actually participating in this transition audio decision.
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;
1920  });
1921  if (source_it == audible_clips.end())
1922  return {1.0f, 1.0f};
1923 
1924  // Keep the current top/non-top clip routing intact when two clips overlap.
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);
1933  });
1934  if ((is_top_clip && source_clip != top_it->clip) || (!is_top_clip && source_clip == top_it->clip))
1935  return {1.0f, 1.0f};
1936  }
1937 
1938  // Infer fade direction from which transition edge is closer to this clip.
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;
1942 
1943  // Evaluate the current frame and previous frame so Timeline can preserve per-frame gain ramps.
1944  const auto compute_gain = [&](int64_t frame_number) -> float {
1945  if (effect_end_position <= effect_start_position)
1946  return 1.0f;
1947 
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;
1950  if (t < 0.0)
1951  t = 0.0;
1952  else if (t > 1.0)
1953  t = 1.0;
1954 
1955  return static_cast<float>(clip_fades_in ? std::sin(t * half_pi) : std::cos(t * half_pi));
1956  };
1957 
1958  return {compute_gain(timeline_frame_number - 1), compute_gain(timeline_frame_number)};
1959 }
openshot::stringToJson
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:16
openshot::CacheMemory::Clear
void Clear()
Clear the cache of all frames.
Definition: CacheMemory.cpp:224
openshot::Timeline::RemoveClip
void RemoveClip(openshot::Clip *clip)
Remove an openshot::Clip from the timeline.
Definition: Timeline.cpp:399
openshot::FrameMapper::ChangeMapping
void ChangeMapping(Fraction target_fps, PulldownType pulldown, int target_sample_rate, int target_channels, ChannelLayout target_channel_layout)
Change frame rate or audio mapping details.
Definition: FrameMapper.cpp:821
openshot::ReaderInfo::sample_rate
int sample_rate
The number of audio samples per second (44100 is a common sample rate)
Definition: ReaderBase.h:60
openshot::EffectInfo
This class returns a listing of all effects supported by libopenshot.
Definition: EffectInfo.h:28
openshot::Fraction::ToFloat
float ToFloat()
Return this fraction as a float (i.e. 1/2 = 0.5)
Definition: Fraction.cpp:35
openshot::Timeline::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t requested_frame) override
Definition: Timeline.cpp:955
openshot::EffectBase
This abstract class is the base class, used by all effects in libopenshot.
Definition: EffectBase.h:56
openshot::ReaderBase::JsonValue
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
Definition: ReaderBase.cpp:110
openshot::Timeline::~Timeline
virtual ~Timeline()
Definition: Timeline.cpp:212
openshot::CacheBase::Clear
virtual void Clear()=0
Clear the cache of all frames.
openshot::CacheBase::GetFrame
virtual std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)=0
Get a frame from the cache.
openshot::Timeline::viewport_x
openshot::Keyframe viewport_x
Curve representing the x coordinate for the viewport.
Definition: Timeline.h:333
openshot::TimelineBase::preview_width
int preview_width
Optional preview width of timeline image. If your preview window is smaller than the timeline,...
Definition: TimelineBase.h:44
openshot::CompareClipEndFrames
Definition: Timeline.h:74
openshot::Timeline::SetMaxSize
void SetMaxSize(int width, int height)
Definition: Timeline.cpp:1829
openshot::Mask
This class uses the image libraries to apply alpha (or transparency) masks to any frame....
Definition: Mask.h:36
openshot::BBox::height
float height
bounding box height
Definition: TrackedObjectBBox.h:42
openshot::CrashHandler::Instance
static CrashHandler * Instance()
Definition: CrashHandler.cpp:27
openshot::EffectInfo::CreateEffect
EffectBase * CreateEffect(std::string effect_type)
Create an instance of an effect (factory style)
Definition: EffectInfo.cpp:27
openshot::Clip::GetCache
openshot::CacheMemory * GetCache() override
Get the cache object (always return NULL for this reader)
Definition: Clip.h:217
openshot::ReaderBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ReaderBase.cpp:161
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: AnimatedCurve.h:24
openshot::TimelineBase::preview_height
int preview_height
Optional preview width of timeline image. If your preview window is smaller than the timeline,...
Definition: TimelineBase.h:45
openshot::CacheBase::Add
virtual void Add(std::shared_ptr< openshot::Frame > frame)=0
Add a Frame to the cache.
openshot::Timeline::ApplyJsonDiff
void ApplyJsonDiff(std::string value)
Apply a special formatted JSON object, which represents a change to the timeline (add,...
Definition: Timeline.cpp:1372
openshot::Clip
This class represents a clip (used to arrange readers on the timeline)
Definition: Clip.h:89
openshot::Fraction
This class represents a fraction.
Definition: Fraction.h:30
openshot::BBox::cy
float cy
y-coordinate of the bounding box center
Definition: TrackedObjectBBox.h:40
openshot::ReaderBase::info
openshot::ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:91
openshot::Settings
This class is contains settings used by libopenshot (and can be safely toggled at any point)
Definition: Settings.h:26
openshot::Timeline::GetMinFrame
int64_t GetMinFrame()
Look up the start frame number of the first element on the timeline (first frame is 1)
Definition: Timeline.cpp:492
Timeline.h
Header file for Timeline class.
openshot::Clip::ParentTimeline
void ParentTimeline(openshot::TimelineBase *new_timeline) override
Set associated Timeline pointer.
Definition: Clip.cpp:450
openshot::Timeline::ClearAllCache
void ClearAllCache(bool deep=false)
Definition: Timeline.cpp:1788
openshot::Timeline::GetTrackedObjectsIds
std::list< std::string > GetTrackedObjectsIds() const
Return the ID's of the tracked objects as a list of strings.
Definition: Timeline.cpp:264
openshot::CompareEffectEndFrames
Like CompareClipEndFrames, but for effects.
Definition: Timeline.h:80
openshot::Keyframe::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: KeyFrame.cpp:372
openshot::Clip::Effects
std::list< openshot::EffectBase * > Effects()
Return the list of effects on the timeline.
Definition: Clip.h:256
openshot::ReaderInfo::duration
float duration
Length of time (in seconds)
Definition: ReaderBase.h:43
CacheDisk.h
Header file for CacheDisk class.
openshot::Clip::channel_mapping
openshot::Keyframe channel_mapping
A number representing an audio channel to output (only works when filtering a channel)
Definition: Clip.h:363
openshot::ReaderInfo::has_video
bool has_video
Determines if this file has a video stream.
Definition: ReaderBase.h:40
openshot::ReaderInfo::width
int width
The width of the video (in pixesl)
Definition: ReaderBase.h:46
openshot::ClipBase::Position
void Position(float value)
Set the Id of this clip object
Definition: ClipBase.cpp:19
openshot::CacheBase
All cache managers in libopenshot are based on this CacheBase class.
Definition: CacheBase.h:34
openshot::Clip::SetJsonValue
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: Clip.cpp:1043
CacheBase.h
Header file for CacheBase class.
openshot::OutOfBoundsFrame
Exception for frames that are out of bounds.
Definition: Exceptions.h:306
openshot::Fraction::ToDouble
double ToDouble() const
Return this fraction as a double (i.e. 1/2 = 0.5)
Definition: Fraction.cpp:40
openshot::Timeline::apply_effects
std::shared_ptr< openshot::Frame > apply_effects(std::shared_ptr< openshot::Frame > frame, int64_t timeline_frame_number, int layer, TimelineInfoStruct *options)
Apply global/timeline effects to the source frame (if any)
Definition: Timeline.cpp:559
openshot::Keyframe::JsonValue
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: KeyFrame.cpp:339
openshot::CacheBase::Remove
virtual void Remove(int64_t frame_number)=0
Remove a specific frame.
FrameMapper.h
Header file for the FrameMapper class.
openshot::ReaderBase::clip
openshot::ClipBase * clip
Pointer to the parent clip instance (if any)
Definition: ReaderBase.h:80
openshot::CacheBase::SetMaxBytesFromInfo
void SetMaxBytesFromInfo(int64_t number_of_frames, int width, int height, int sample_rate, int channels)
Set maximum bytes to a different amount based on a ReaderInfo struct.
Definition: CacheBase.cpp:28
openshot::Color
This class represents a color (used on the timeline and clips)
Definition: Color.h:27
openshot::ClipBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ClipBase.cpp:80
openshot::ReaderInfo::video_length
int64_t video_length
The number of frames in the video stream.
Definition: ReaderBase.h:53
openshot::ReaderInfo::height
int height
The height of the video (in pixels)
Definition: ReaderBase.h:45
openshot::VOLUME_MIX_REDUCE
@ VOLUME_MIX_REDUCE
Reduce volume by about %25, and then mix (louder, but could cause pops if the sum exceeds 100%)
Definition: Enums.h:71
openshot::BBox::angle
float angle
bounding box rotation angle [degrees]
Definition: TrackedObjectBBox.h:43
openshot::Fraction::num
int num
Numerator for the fraction.
Definition: Fraction.h:32
openshot::Timeline::GetClip
openshot::Clip * GetClip(const std::string &id)
Look up a single clip by ID.
Definition: Timeline.cpp:418
openshot::Fraction::den
int den
Denominator for the fraction.
Definition: Fraction.h:33
OPEN_MP_NUM_PROCESSORS
#define OPEN_MP_NUM_PROCESSORS
Definition: OpenMPUtilities.h:23
openshot::Keyframe
A Keyframe is a collection of Point instances, which is used to vary a number or property over time.
Definition: KeyFrame.h:53
CrashHandler.h
Header file for CrashHandler class.
openshot::Fraction::Reduce
void Reduce()
Reduce this fraction (i.e. 640/480 = 4/3)
Definition: Fraction.cpp:65
openshot::Color::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: Color.cpp:117
openshot::Timeline::Open
void Open() override
Open the reader (and start consuming resources)
Definition: Timeline.cpp:943
openshot::Timeline::SetJson
void SetJson(const std::string value) override
Load JSON string into this object.
Definition: Timeline.cpp:1250
openshot::TimelineInfoStruct::is_before_clip_keyframes
bool is_before_clip_keyframes
Is this before clip keyframes are applied.
Definition: TimelineBase.h:35
openshot::Fraction::Reciprocal
Fraction Reciprocal() const
Return the reciprocal as a Fraction.
Definition: Fraction.cpp:78
openshot::ReaderInfo::has_audio
bool has_audio
Determines if this file has an audio stream.
Definition: ReaderBase.h:41
openshot::Timeline::GetTrackedObjectValues
std::string GetTrackedObjectValues(std::string id, int64_t frame_number) const
Return the trackedObject's properties as a JSON string.
Definition: Timeline.cpp:280
openshot::CacheMemory
This class is a memory-based cache manager for Frame objects.
Definition: CacheMemory.h:29
openshot::FrameMapper::Close
void Close() override
Close the openshot::FrameMapper and internal reader.
Definition: FrameMapper.cpp:738
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:223
openshot::Timeline::GetMaxTime
double GetMaxTime()
Look up the end time of the latest timeline element.
Definition: Timeline.cpp:473
openshot::BBox::width
float width
bounding box width
Definition: TrackedObjectBBox.h:41
openshot::Timeline
This class represents a timeline.
Definition: Timeline.h:153
openshot::Timeline::ClipEffects
std::list< openshot::EffectBase * > ClipEffects() const
Return the list of effects on all clips.
Definition: Timeline.cpp:454
CacheMemory.h
Header file for CacheMemory class.
openshot::Color::green
openshot::Keyframe green
Curve representing the green value (0 - 255)
Definition: Color.h:31
openshot::ReaderInfo
This struct contains info about a media file, such as height, width, frames per second,...
Definition: ReaderBase.h:38
openshot::CompareEffects
Definition: Timeline.h:64
openshot::ReaderInfo::video_timebase
openshot::Fraction video_timebase
The video timebase determines how long each frame stays on the screen.
Definition: ReaderBase.h:55
openshot::Settings::Instance
static Settings * Instance()
Create or get an instance of this logger singleton (invoke the class with this method)
Definition: Settings.cpp:43
openshot::TimelineInfoStruct
This struct contains info about the current Timeline clip instance.
Definition: TimelineBase.h:32
openshot::Timeline::Clear
void Clear()
Clear all clips, effects, and frame mappers from timeline (and free memory)
Definition: Timeline.cpp:875
openshot::Timeline::RemoveEffect
void RemoveEffect(openshot::EffectBase *effect)
Remove an effect from the timeline.
Definition: Timeline.cpp:380
openshot::ClipBase::Start
void Start(float value)
Set start position (in seconds) of clip (trim start of video)
Definition: ClipBase.cpp:42
path
path
Definition: FFmpegWriter.cpp:1481
openshot::Settings::PATH_OPENSHOT_INSTALL
std::string PATH_OPENSHOT_INSTALL
Definition: Settings.h:123
openshot::FrameMapper
This class creates a mapping between 2 different frame rates, applying a specific pull-down technique...
Definition: FrameMapper.h:193
openshot::Timeline::Close
void Close() override
Close the timeline reader (and any resources it was consuming)
Definition: Timeline.cpp:921
openshot::Frame::GetSamplesPerFrame
int GetSamplesPerFrame(openshot::Fraction fps, int sample_rate, int channels)
Calculate the # of samples per video frame (for the current frame number)
Definition: Frame.cpp:484
openshot::Timeline::AddClip
void AddClip(openshot::Clip *clip)
Add an openshot::Clip to the timeline.
Definition: Timeline.cpp:338
openshot::InvalidFile
Exception for files that can not be found or opened.
Definition: Exceptions.h:193
openshot::ZmqLogger::Instance
static ZmqLogger * Instance()
Create or get an instance of this logger singleton (invoke the class with this method)
Definition: ZmqLogger.cpp:35
Mask.h
Header file for Mask class.
openshot::ZmqLogger::AppendDebugMethod
void AppendDebugMethod(std::string method_name, std::string arg1_name="", float arg1_value=-1.0, std::string arg2_name="", float arg2_value=-1.0, std::string arg3_name="", float arg3_value=-1.0, std::string arg4_name="", float arg4_value=-1.0, std::string arg5_name="", float arg5_value=-1.0, std::string arg6_name="", float arg6_value=-1.0)
Append debug information.
Definition: ZmqLogger.cpp:178
openshot::Clip::volume
openshot::Keyframe volume
Curve representing the volume (0 to 1)
Definition: Clip.h:346
openshot::ReaderInfo::vcodec
std::string vcodec
The name of the video codec used to encode / decode the video stream.
Definition: ReaderBase.h:52
openshot::Timeline::AddTrackedObject
void AddTrackedObject(std::shared_ptr< openshot::TrackedObjectBase > trackedObject)
Add to the tracked_objects map a pointer to a tracked object (TrackedObjectBBox)
Definition: Timeline.cpp:229
openshot::Color::JsonValue
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition: Color.cpp:86
openshot::Keyframe::GetInt
int GetInt(int64_t index) const
Get the rounded INT value at a specific index.
Definition: KeyFrame.cpp:282
openshot::BBox
This struct holds the information of a bounding-box.
Definition: TrackedObjectBBox.h:37
openshot::Timeline::color
openshot::Color color
Background color of timeline canvas.
Definition: Timeline.h:337
openshot::ReaderClosed
Exception when a reader is closed, and a frame is requested.
Definition: Exceptions.h:369
openshot::Timeline::GetEffect
openshot::EffectBase * GetEffect(const std::string &id)
Look up a timeline effect by ID.
Definition: Timeline.cpp:430
openshot::ReaderInfo::channel_layout
openshot::ChannelLayout channel_layout
The channel layout (mono, stereo, 5 point surround, etc...)
Definition: ReaderBase.h:62
openshot::CompareClips
Definition: Timeline.h:48
openshot::Clip::channel_filter
openshot::Keyframe channel_filter
A number representing an audio channel to filter (clears all other channels)
Definition: Clip.h:362
openshot::ClipBase::Id
void Id(std::string value)
Definition: ClipBase.h:94
openshot::Keyframe::GetCount
int64_t GetCount() const
Get the number of points (i.e. # of points)
Definition: KeyFrame.cpp:424
openshot::Timeline::Timeline
Timeline(int width, int height, openshot::Fraction fps, int sample_rate, int channels, openshot::ChannelLayout channel_layout)
Constructor for the timeline (which configures the default frame properties)
Definition: Timeline.cpp:34
openshot::ReaderInfo::fps
openshot::Fraction fps
Frames per second, as a fraction (i.e. 24/1 = 24 fps)
Definition: ReaderBase.h:48
openshot::ReaderBase
This abstract class is the base class, used by all readers in libopenshot.
Definition: ReaderBase.h:75
openshot::Timeline::Json
std::string Json() const override
Generate JSON string of this object.
Definition: Timeline.cpp:1209
openshot::Timeline::GetMaxFrame
int64_t GetMaxFrame()
Look up the end frame number of the latest element on the timeline.
Definition: Timeline.cpp:479
openshot::ClipBase::GetFrame
virtual std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)=0
This method is required for all derived classes of ClipBase, and returns a new openshot::Frame object...
openshot::Timeline::SetJsonValue
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: Timeline.cpp:1270
openshot::VOLUME_MIX_AVERAGE
@ VOLUME_MIX_AVERAGE
Evenly divide the overlapping clips volume keyframes, so that the sum does not exceed 100%.
Definition: Enums.h:70
openshot::Timeline::ApplyMapperToClips
void ApplyMapperToClips()
Apply the timeline's framerate and samplerate to all clips.
Definition: Timeline.cpp:535
openshot::Timeline::viewport_y
openshot::Keyframe viewport_y
Curve representing the y coordinate for the viewport.
Definition: Timeline.h:334
openshot::Clip::has_audio
openshot::Keyframe has_audio
An optional override to determine if this clip has audio (-1=undefined, 0=no, 1=yes)
Definition: Clip.h:366
openshot::ChannelLayout
ChannelLayout
This enumeration determines the audio channel layout (such as stereo, mono, 5 point surround,...
Definition: ChannelLayouts.h:28
openshot::ReaderInfo::pixel_ratio
openshot::Fraction pixel_ratio
The pixel ratio of the video stream as a fraction (i.e. some pixels are not square)
Definition: ReaderBase.h:50
openshot::BBox::cx
float cx
x-coordinate of the bounding box center
Definition: TrackedObjectBBox.h:39
openshot::Clip::Reader
void Reader(openshot::ReaderBase *new_reader)
Set the current reader.
Definition: Clip.cpp:340
openshot::Timeline::GetClipEffect
openshot::EffectBase * GetClipEffect(const std::string &id)
Look up a clip effect by ID.
Definition: Timeline.cpp:441
openshot::Color::red
openshot::Keyframe red
Curve representing the red value (0 - 255)
Definition: Color.h:30
openshot::FrameMapper::Reader
ReaderBase * Reader()
Get the current reader.
Definition: FrameMapper.cpp:67
openshot::ReaderInfo::acodec
std::string acodec
The name of the audio codec used to encode / decode the video stream.
Definition: ReaderBase.h:58
openshot::PULLDOWN_NONE
@ PULLDOWN_NONE
Do not apply pull-down techniques, just repeat or skip entire frames.
Definition: FrameMapper.h:46
openshot::ReaderInfo::display_ratio
openshot::Fraction display_ratio
The ratio of width to height of the video stream (i.e. 640x480 has a ratio of 4/3)
Definition: ReaderBase.h:51
openshot::TimelineInfoStruct::is_top_clip
bool is_top_clip
Is clip on top (if overlapping another clip)
Definition: TimelineBase.h:34
openshot::InvalidJSONKey
Exception for missing JSON Change key.
Definition: Exceptions.h:268
openshot::ClipBase::Layer
void Layer(int value)
Set layer of clip on timeline (lower number is covered by higher numbers)
Definition: ClipBase.cpp:31
openshot::Color::GetColorHex
std::string GetColorHex(int64_t frame_number)
Get the HEX value of a color at a specific frame.
Definition: Color.cpp:47
openshot::ReaderInfo::channels
int channels
The number of audio channels used in the audio stream.
Definition: ReaderBase.h:61
openshot::Timeline::viewport_scale
openshot::Keyframe viewport_scale
Curve representing the scale of the viewport (0 to 100)
Definition: Timeline.h:332
openshot::Timeline::AddEffect
void AddEffect(openshot::EffectBase *effect)
Add an effect to the timeline.
Definition: Timeline.cpp:364
openshot::Timeline::JsonValue
Json::Value JsonValue() const override
Generate Json::Value for this object.
Definition: Timeline.cpp:1216
openshot::ReaderBase::GetCache
virtual openshot::CacheBase * GetCache()=0
Get the cache object used by this reader (note: not all readers use cache)
openshot::Color::blue
openshot::Keyframe blue
Curve representing the red value (0 - 255)
Definition: Color.h:32
openshot::Timeline::GetTrackedObject
std::shared_ptr< openshot::TrackedObjectBase > GetTrackedObject(std::string id) const
Return tracked object pointer by it's id.
Definition: Timeline.cpp:247
Exceptions.h
Header file for all Exception classes.
openshot::Clip::mixing
openshot::VolumeMixType mixing
What strategy should be followed when mixing audio with other clips.
Definition: Clip.h:189
openshot::Timeline::GetMinTime
double GetMinTime()
Look up the position/start time of the first timeline element.
Definition: Timeline.cpp:500
openshot::EffectBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: EffectBase.cpp:139
openshot::Keyframe::GetValue
double GetValue(int64_t index) const
Get the value at a specific index.
Definition: KeyFrame.cpp:258
openshot::Timeline::SetCache
void SetCache(openshot::CacheBase *new_cache)
Definition: Timeline.cpp:1193
openshot::ReaderBase::getFrameMutex
std::recursive_mutex getFrameMutex
Mutex for multiple threads.
Definition: ReaderBase.h:79