bb675adc016d116b366b53868c341a4d4f2bb220
[platform/upstream/gst-editing-services.git] / ges / ges-timeline.c
1 /* GStreamer Editing Services
2  * Copyright (C) 2009 Edward Hervey <edward.hervey@collabora.co.uk>
3  *               2009 Nokia Corporation
4  *               2012 Thibault Saunier <tsaunier@gnome.org>
5  *               2012 Collabora Ltd.
6  *                 Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
7  *               2019 Igalia S.L
8  *                 Author: Thibault Saunier <tsaunier@igalia.com>
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 /**
27  * SECTION:gestimeline
28  * @title: GESTimeline
29  * @short_description: Multimedia timeline
30  *
31  * #GESTimeline is the central object for any multimedia timeline.
32  *
33  * A timeline is composed of a set of #GESTrack-s and a set of
34  * #GESLayer-s, which are added to the timeline using
35  * ges_timeline_add_track() and ges_timeline_append_layer(), respectively.
36  *
37  * The contained tracks define the supported types of the timeline
38  * and provide the media output. Essentially, each track provides an
39  * additional source #GstPad.
40  *
41  * Most usage of a timeline will likely only need a single #GESAudioTrack
42  * and/or a single #GESVideoTrack. You can create such a timeline with
43  * ges_timeline_new_audio_video(). After this, you are unlikely to need to
44  * work with the tracks directly.
45  *
46  * A timeline's layers contain #GESClip-s, which in turn control the
47  * creation of #GESTrackElement-s, which are added to the timeline's
48  * tracks. See #GESTimeline::select-tracks-for-object if you wish to have
49  * more control over which track a clip's elements are added to.
50  *
51  * The layers are ordered, with higher priority layers having their
52  * content prioritised in the tracks. This ordering can be changed using
53  * ges_timeline_move_layer().
54  *
55  * ## Editing
56  *
57  * See #GESTimelineElement for the various ways the elements of a timeline
58  * can be edited.
59  *
60  * If you change the timing or ordering of a timeline's
61  * #GESTimelineElement-s, then these changes will not actually be taken
62  * into account in the output of the timeline's tracks until the
63  * ges_timeline_commit() method is called. This allows you to move its
64  * elements around, say, in response to an end user's mouse dragging, with
65  * little expense before finalising their effect on the produced data.
66  *
67  * ## Overlaps and Auto-Transitions
68  *
69  * There are certain restrictions placed on how #GESSource-s may overlap
70  * in a #GESTrack that belongs to a timeline. These will be enforced by
71  * GES, so the user will not need to keep track of them, but they should
72  * be aware that certain edits will be refused as a result if the overlap
73  * rules would be broken.
74  *
75  * Consider two #GESSource-s, `A` and `B`, with start times `startA` and
76  * `startB`, and end times `endA` and `endB`, respectively. The start
77  * time refers to their #GESTimelineElement:start, and the end time is
78  * their #GESTimelineElement:start + #GESTimelineElement:duration. These
79  * two sources *overlap* if:
80  *
81  * + they share the same #GESTrackElement:track (non %NULL), which belongs
82  *   to the timeline;
83  * + they share the same #GES_TIMELINE_ELEMENT_LAYER_PRIORITY; and
84  * + `startA < endB` and `startB < endA `.
85  *
86  * Note that when `startA = endB` or `startB = endA` then the two sources
87  * will *touch* at their edges, but are not considered overlapping.
88  *
89  * If, in addition, `startA < startB < endA`, then we can say that the
90  * end of `A` overlaps the start of `B`.
91  *
92  * If, instead, `startA <= startB` and `endA >= endB`, then we can say
93  * that `A` fully overlaps `B`.
94  *
95  * The overlap rules for a timeline are that:
96  *
97  * 1. One source cannot fully overlap another source.
98  * 2. A source can only overlap the end of up to one other source at its
99  *    start.
100  * 3. A source can only overlap the start of up to one other source at its
101  *    end.
102  *
103  * The last two rules combined essentially mean that at any given timeline
104  * position, only up to two #GESSource-s may overlap at that position. So
105  * triple or more overlaps are not allowed.
106  *
107  * If you switch on #GESTimeline:auto-transition, then at any moment when
108  * the end of one source (the first source) overlaps the start of another
109  * (the second source), a #GESTransitionClip will be automatically created
110  * for the pair in the same layer and it will cover their overlap. If the
111  * two elements are edited in a way such that the end of the first source
112  * no longer overlaps the start of the second, the transition will be
113  * automatically removed from the timeline. However, if the two sources
114  * still overlap at the same edges after the edit, then the same
115  * transition object will be kept, but with its timing and layer adjusted
116  * accordingly.
117  *
118  * ## Saving
119  *
120  * To save/load a timeline, you can use the ges_timeline_load_from_uri()
121  * and ges_timeline_save_to_uri() methods that use the default format.
122  *
123  * ## Playing
124  *
125  * A timeline is a #GstBin with a source #GstPad for each of its
126  * tracks, which you can fetch with ges_timeline_get_pad_for_track(). You
127  * will likely want to link these to some compatible sink #GstElement-s to
128  * be able to play or capture the content of the timeline.
129  *
130  * You can use a #GESPipeline to easily preview/play the timeline's
131  * content, or render it to a file.
132  */
133 #ifdef HAVE_CONFIG_H
134 #include "config.h"
135 #endif
136
137 #include "ges-internal.h"
138 #include "ges-project.h"
139 #include "ges-container.h"
140 #include "ges-timeline.h"
141 #include "ges-timeline-tree.h"
142 #include "ges-track.h"
143 #include "ges-layer.h"
144 #include "ges-auto-transition.h"
145 #include "ges.h"
146
147
148 static GPtrArray *select_tracks_for_object_default (GESTimeline * timeline,
149     GESClip * clip, GESTrackElement * tr_obj, gpointer user_data);
150 static void ges_extractable_interface_init (GESExtractableInterface * iface);
151 static void ges_meta_container_interface_init
152     (GESMetaContainerInterface * iface);
153
154 GST_DEBUG_CATEGORY_STATIC (ges_timeline_debug);
155 #undef GST_CAT_DEFAULT
156 #define GST_CAT_DEFAULT ges_timeline_debug
157
158 /* lock to protect dynamic callbacks, like pad-added */
159 #define DYN_LOCK(timeline) (&GES_TIMELINE (timeline)->priv->dyn_mutex)
160 #define LOCK_DYN(timeline) G_STMT_START {                       \
161     GST_LOG_OBJECT (timeline, "Getting dynamic lock from %p", \
162         g_thread_self());                                       \
163     g_rec_mutex_lock (DYN_LOCK (timeline));                     \
164     GST_LOG_OBJECT (timeline, "Got Dynamic lock from %p",     \
165         g_thread_self());         \
166   } G_STMT_END
167
168 #define UNLOCK_DYN(timeline) G_STMT_START {                         \
169     GST_LOG_OBJECT (timeline, "Unlocking dynamic lock from %p", \
170         g_thread_self());                                         \
171     g_rec_mutex_unlock (DYN_LOCK (timeline));                     \
172     GST_LOG_OBJECT (timeline, "Unlocked Dynamic lock from %p",  \
173         g_thread_self());         \
174   } G_STMT_END
175
176 #define CHECK_THREAD(timeline) g_assert(timeline->priv->valid_thread == g_thread_self())
177
178 struct _GESTimelinePrivate
179 {
180   GNode *tree;
181
182   /* The duration of the timeline */
183   gint64 duration;
184
185   /* The auto-transition of the timeline */
186   gboolean auto_transition;
187
188   /* Timeline edition modes and snapping management */
189   guint64 snapping_distance;
190
191   GRecMutex dyn_mutex;
192   GList *priv_tracks;
193
194   /* Avoid sorting layers when we are actually resyncing them ourself */
195   gboolean resyncing_layers;
196   GList *auto_transitions;
197
198   /* Last snapping  properties */
199   GstClockTime last_snap_ts;
200   GESTrackElement *last_snaped1;
201   GESTrackElement *last_snaped2;
202
203   GESTrack *auto_transition_track;
204   GESTrack *new_track;
205
206   /* While we are creating and adding the TrackElements for a clip, we need to
207    * ignore the child-added signal */
208   gboolean track_elements_moving;
209   /* whether any error occurred during track selection, including
210    * programming or usage errors */
211   gboolean has_any_track_selection_error;
212   /* error set for non-programming/usage errors */
213   GError *track_selection_error;
214   GList *groups;
215
216   guint stream_start_group_id;
217
218   GHashTable *all_elements;
219
220   /* With GST_OBJECT_LOCK */
221   guint expected_async_done;
222   /* With GST_OBJECT_LOCK */
223   guint expected_commited;
224
225   /* For ges_timeline_commit_sync */
226   GMutex commited_lock;
227   GCond commited_cond;
228
229   GThread *valid_thread;
230   gboolean disposed;
231
232   GstStreamCollection *stream_collection;
233
234   gboolean rendering_smartly;
235 };
236
237 /* private structure to contain our track-related information */
238
239 typedef struct
240 {
241   GESTimeline *timeline;
242   GESTrack *track;
243   GstPad *pad;                  /* Pad from the track */
244   GstPad *ghostpad;
245   gulong track_element_added_sigid;
246
247   gulong probe_id;
248   GstStream *stream;
249 } TrackPrivate;
250
251 enum
252 {
253   PROP_0,
254   PROP_DURATION,
255   PROP_AUTO_TRANSITION,
256   PROP_SNAPPING_DISTANCE,
257   PROP_UPDATE,
258   PROP_LAST
259 };
260
261 static GParamSpec *properties[PROP_LAST];
262
263 enum
264 {
265   TRACK_ADDED,
266   TRACK_REMOVED,
267   LAYER_ADDED,
268   LAYER_REMOVED,
269   GROUP_ADDED,
270   GROUP_REMOVED,
271   SNAPING_STARTED,
272   SNAPING_ENDED,
273   SELECT_TRACKS_FOR_OBJECT,
274   COMMITED,
275   SELECT_ELEMENT_TRACK,
276   LAST_SIGNAL
277 };
278
279 G_DEFINE_TYPE_WITH_CODE (GESTimeline, ges_timeline, GST_TYPE_BIN,
280     G_ADD_PRIVATE (GESTimeline)
281     G_IMPLEMENT_INTERFACE (GES_TYPE_EXTRACTABLE, ges_extractable_interface_init)
282     G_IMPLEMENT_INTERFACE (GES_TYPE_META_CONTAINER,
283         ges_meta_container_interface_init));
284
285 static GstBinClass *parent_class;
286
287 static guint ges_timeline_signals[LAST_SIGNAL] = { 0 };
288
289 static gint custom_find_track (TrackPrivate * tr_priv, GESTrack * track);
290
291 static guint nb_assets = 0;
292
293 /* GESExtractable implementation */
294 static gchar *
295 extractable_check_id (GType type, const gchar * id)
296 {
297   gchar *res;
298
299   if (id == NULL)
300     res = g_strdup_printf ("%s-%i", "project", nb_assets);
301   else
302     res = g_strdup (id);
303
304   nb_assets++;
305
306   return res;
307 }
308
309 static gchar *
310 extractable_get_id (GESExtractable * self)
311 {
312   GESAsset *asset;
313
314   if (!(asset = ges_extractable_get_asset (self)))
315     return NULL;
316
317   return g_strdup (ges_asset_get_id (asset));
318 }
319
320 static void
321 ges_extractable_interface_init (GESExtractableInterface * iface)
322 {
323   iface->asset_type = GES_TYPE_PROJECT;
324   iface->check_id = (GESExtractableCheckId) extractable_check_id;
325   iface->get_id = extractable_get_id;
326 }
327
328 static void
329 ges_meta_container_interface_init (GESMetaContainerInterface * iface)
330 {
331 }
332
333 /* GObject Standard vmethods*/
334 static void
335 ges_timeline_get_property (GObject * object, guint property_id,
336     GValue * value, GParamSpec * pspec)
337 {
338   GESTimeline *timeline = GES_TIMELINE (object);
339
340   switch (property_id) {
341     case PROP_DURATION:
342       g_value_set_uint64 (value, timeline->priv->duration);
343       break;
344     case PROP_AUTO_TRANSITION:
345       g_value_set_boolean (value, timeline->priv->auto_transition);
346       break;
347     case PROP_SNAPPING_DISTANCE:
348       g_value_set_uint64 (value, timeline->priv->snapping_distance);
349       break;
350     default:
351       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
352   }
353 }
354
355 static void
356 ges_timeline_set_property (GObject * object, guint property_id,
357     const GValue * value, GParamSpec * pspec)
358 {
359   GESTimeline *timeline = GES_TIMELINE (object);
360
361   switch (property_id) {
362     case PROP_AUTO_TRANSITION:
363       ges_timeline_set_auto_transition (timeline, g_value_get_boolean (value));
364       break;
365     case PROP_SNAPPING_DISTANCE:
366       timeline->priv->snapping_distance = g_value_get_uint64 (value);
367       break;
368     default:
369       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
370   }
371 }
372
373 gboolean
374 ges_timeline_is_disposed (GESTimeline * timeline)
375 {
376   return timeline->priv->disposed;
377 }
378
379 static void
380 ges_timeline_dispose (GObject * object)
381 {
382   GESTimeline *tl = GES_TIMELINE (object);
383   GESTimelinePrivate *priv = tl->priv;
384   GList *tmp, *groups;
385
386   priv->disposed = TRUE;
387   while (tl->layers) {
388     GESLayer *layer = (GESLayer *) tl->layers->data;
389     ges_timeline_remove_layer (GES_TIMELINE (object), layer);
390   }
391
392   /* FIXME: it should be possible to remove tracks before removing
393    * layers, but at the moment this creates a problem because the track
394    * objects aren't notified that their nleobjects have been destroyed.
395    */
396
397   LOCK_DYN (tl);
398   while (tl->tracks)
399     ges_timeline_remove_track (GES_TIMELINE (object), tl->tracks->data);
400   UNLOCK_DYN (tl);
401
402   /* NOTE: the timeline should not contain empty groups */
403   groups = g_list_copy_deep (priv->groups, (GCopyFunc) gst_object_ref, NULL);
404   for (tmp = groups; tmp; tmp = tmp->next) {
405     GList *elems = ges_container_ungroup (tmp->data, FALSE);
406
407     g_list_free_full (elems, gst_object_unref);
408   }
409   g_list_free_full (groups, gst_object_unref);
410   g_list_free_full (priv->groups, gst_object_unref);
411
412   g_list_free_full (priv->auto_transitions, gst_object_unref);
413
414   g_hash_table_unref (priv->all_elements);
415   gst_object_unref (priv->stream_collection);
416
417   gst_clear_object (&priv->auto_transition_track);
418   gst_clear_object (&priv->new_track);
419   g_clear_error (&priv->track_selection_error);
420   priv->track_selection_error = NULL;
421
422   G_OBJECT_CLASS (ges_timeline_parent_class)->dispose (object);
423 }
424
425 static void
426 ges_timeline_finalize (GObject * object)
427 {
428   GESTimeline *tl = GES_TIMELINE (object);
429
430   g_rec_mutex_clear (&tl->priv->dyn_mutex);
431   g_node_destroy (tl->priv->tree);
432
433   G_OBJECT_CLASS (ges_timeline_parent_class)->finalize (object);
434 }
435
436 static void
437 ges_timeline_handle_message (GstBin * bin, GstMessage * message)
438 {
439   GESTimeline *timeline = GES_TIMELINE (bin);
440
441   if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_ASYNC_START) {
442     GST_INFO_OBJECT (timeline, "Dropping %" GST_PTR_FORMAT, message);
443     return;
444   }
445
446   if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_ASYNC_DONE) {
447     GST_INFO_OBJECT (timeline, "Dropping %" GST_PTR_FORMAT, message);
448
449     return;
450   }
451
452   if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_ELEMENT) {
453     GstMessage *amessage = NULL;
454     const GstStructure *mstructure = gst_message_get_structure (message);
455
456     if (gst_structure_has_name (mstructure, "NleCompositionStartUpdate")) {
457       if (g_strcmp0 (gst_structure_get_string (mstructure, "reason"), "Seek")) {
458         GST_INFO_OBJECT (timeline,
459             "A composition is starting an update because of %s"
460             " not considering async", gst_structure_get_string (mstructure,
461                 "reason"));
462
463         goto forward;
464       }
465
466       GST_OBJECT_LOCK (timeline);
467       if (timeline->priv->expected_async_done == 0) {
468         amessage = gst_message_new_async_start (GST_OBJECT_CAST (bin));
469         LOCK_DYN (timeline);
470         timeline->priv->expected_async_done = g_list_length (timeline->tracks);
471         UNLOCK_DYN (timeline);
472         GST_INFO_OBJECT (timeline, "Posting ASYNC_START %s",
473             gst_structure_get_string (mstructure, "reason"));
474       }
475       GST_OBJECT_UNLOCK (timeline);
476
477     } else if (gst_structure_has_name (mstructure, "NleCompositionUpdateDone")) {
478       if (g_strcmp0 (gst_structure_get_string (mstructure, "reason"), "Seek")) {
479         GST_INFO_OBJECT (timeline,
480             "A composition is done updating because of %s"
481             " not considering async", gst_structure_get_string (mstructure,
482                 "reason"));
483
484         goto forward;
485       }
486
487       GST_OBJECT_LOCK (timeline);
488       timeline->priv->expected_async_done -= 1;
489       if (timeline->priv->expected_async_done == 0) {
490         amessage = gst_message_new_async_done (GST_OBJECT_CAST (bin),
491             GST_CLOCK_TIME_NONE);
492         GST_INFO_OBJECT (timeline, "Posting ASYNC_DONE %s",
493             gst_structure_get_string (mstructure, "reason"));
494       }
495       GST_OBJECT_UNLOCK (timeline);
496     }
497
498     if (amessage) {
499       gst_message_unref (message);
500       gst_element_post_message (GST_ELEMENT_CAST (bin), amessage);
501       return;
502     }
503   }
504
505 forward:
506   gst_element_post_message (GST_ELEMENT_CAST (bin), message);
507 }
508
509 static GstStateChangeReturn
510 ges_timeline_change_state (GstElement * element, GstStateChange transition)
511 {
512   GstStateChangeReturn res;
513   GESTimeline *timeline = GES_TIMELINE (element);
514
515   res = GST_ELEMENT_CLASS (ges_timeline_parent_class)->change_state (element,
516       transition);
517
518   if (transition == GST_STATE_CHANGE_READY_TO_PAUSED)
519     gst_element_post_message ((GstElement *) timeline,
520         gst_message_new_stream_collection ((GstObject *) timeline,
521             timeline->priv->stream_collection));
522   return res;
523 }
524
525 static gboolean
526 ges_timeline_send_event (GstElement * element, GstEvent * event)
527 {
528   GESTimeline *timeline = GES_TIMELINE (element);
529
530   if (GST_EVENT_TYPE (event) == GST_EVENT_SELECT_STREAMS) {
531     GList *stream_ids = NULL, *tmp, *to_remove =
532         ges_timeline_get_tracks (timeline);
533
534     gst_event_parse_select_streams (event, &stream_ids);
535     for (tmp = stream_ids; tmp; tmp = tmp->next) {
536       GList *trackit;
537       gchar *stream_id = tmp->data;
538
539       LOCK_DYN (timeline);
540       for (trackit = timeline->priv->priv_tracks; trackit;
541           trackit = trackit->next) {
542         TrackPrivate *tr_priv = trackit->data;
543
544         if (!g_strcmp0 (gst_stream_get_stream_id (tr_priv->stream), stream_id)) {
545           to_remove = g_list_remove (to_remove, tr_priv->track);
546         }
547       }
548       UNLOCK_DYN (timeline);
549     }
550     for (tmp = to_remove; tmp; tmp = tmp->next) {
551       GST_INFO_OBJECT (timeline, "Removed unselected track: %" GST_PTR_FORMAT,
552           tmp->data);
553       ges_timeline_remove_track (timeline, tmp->data);
554     }
555
556     g_list_free_full (stream_ids, g_free);
557     g_list_free (to_remove);
558
559     return TRUE;
560   }
561
562   return GST_ELEMENT_CLASS (ges_timeline_parent_class)->send_event (element,
563       event);
564 }
565
566 /* we collect the first result */
567 static gboolean
568 _gst_array_accumulator (GSignalInvocationHint * ihint,
569     GValue * return_accu, const GValue * handler_return, gpointer dummy)
570 {
571   gpointer array;
572
573   array = g_value_get_boxed (handler_return);
574   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
575     g_value_set_boxed (return_accu, array);
576
577   return FALSE;
578 }
579
580 static void
581 ges_timeline_class_init (GESTimelineClass * klass)
582 {
583   GObjectClass *object_class = G_OBJECT_CLASS (klass);
584   GstElementClass *element_class = (GstElementClass *) klass;
585   GstBinClass *bin_class = GST_BIN_CLASS (klass);
586
587   GST_DEBUG_CATEGORY_INIT (ges_timeline_debug, "gestimeline",
588       GST_DEBUG_FG_YELLOW, "ges timeline");
589   timeline_tree_init_debug ();
590
591   parent_class = g_type_class_peek_parent (klass);
592
593   object_class->get_property = ges_timeline_get_property;
594   object_class->set_property = ges_timeline_set_property;
595   object_class->dispose = ges_timeline_dispose;
596   object_class->finalize = ges_timeline_finalize;
597
598   element_class->change_state = GST_DEBUG_FUNCPTR (ges_timeline_change_state);
599   element_class->send_event = GST_DEBUG_FUNCPTR (ges_timeline_send_event);
600
601   bin_class->handle_message = GST_DEBUG_FUNCPTR (ges_timeline_handle_message);
602
603   /**
604    * GESTimeline:duration:
605    *
606    * The current duration (in nanoseconds) of the timeline. A timeline
607    * 'starts' at time 0, so this is the maximum end time of all of its
608    * #GESTimelineElement-s.
609    */
610   properties[PROP_DURATION] =
611       g_param_spec_uint64 ("duration", "Duration",
612       "The duration of the timeline", 0, G_MAXUINT64,
613       GST_CLOCK_TIME_NONE, G_PARAM_READABLE);
614   g_object_class_install_property (object_class, PROP_DURATION,
615       properties[PROP_DURATION]);
616
617   /**
618    * GESTimeline:auto-transition:
619    *
620    * Whether to automatically create a transition whenever two
621    * #GESSource-s overlap in a track of the timeline. See
622    * #GESLayer:auto-transition if you want this to only happen in some
623    * layers.
624    */
625   g_object_class_install_property (object_class, PROP_AUTO_TRANSITION,
626       g_param_spec_boolean ("auto-transition", "Auto-Transition",
627           "whether the transitions are added", FALSE, G_PARAM_READWRITE));
628
629   /**
630    * GESTimeline:snapping-distance:
631    *
632    * The distance (in nanoseconds) at which a #GESTimelineElement being
633    * moved within the timeline should snap one of its #GESSource-s with
634    * another #GESSource-s edge. See #GESEditMode for which edges can
635    * snap during an edit. 0 means no snapping.
636    */
637   properties[PROP_SNAPPING_DISTANCE] =
638       g_param_spec_uint64 ("snapping-distance", "Snapping distance",
639       "Distance from which moving an object will snap with neighbours", 0,
640       G_MAXUINT64, 0, G_PARAM_READWRITE);
641   g_object_class_install_property (object_class, PROP_SNAPPING_DISTANCE,
642       properties[PROP_SNAPPING_DISTANCE]);
643
644   /**
645    * GESTimeline::track-added:
646    * @timeline: The #GESTimeline
647    * @track: The track that was added to @timeline
648    *
649    * Will be emitted after the track is added to the timeline.
650    *
651    * Note that this should not be emitted whilst a timeline is being
652    * loaded from its #GESProject asset. You should connect to the
653    * project's #GESProject::loaded signal if you want to know which
654    * tracks were created for the timeline.
655    */
656   ges_timeline_signals[TRACK_ADDED] =
657       g_signal_new ("track-added", G_TYPE_FROM_CLASS (klass),
658       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, track_added), NULL,
659       NULL, NULL, G_TYPE_NONE, 1, GES_TYPE_TRACK);
660
661   /**
662    * GESTimeline::track-removed:
663    * @timeline: The #GESTimeline
664    * @track: The track that was removed from @timeline
665    *
666    * Will be emitted after the track is removed from the timeline.
667    */
668   ges_timeline_signals[TRACK_REMOVED] =
669       g_signal_new ("track-removed", G_TYPE_FROM_CLASS (klass),
670       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, track_removed),
671       NULL, NULL, NULL, G_TYPE_NONE, 1, GES_TYPE_TRACK);
672
673   /**
674    * GESTimeline::layer-added:
675    * @timeline: The #GESTimeline
676    * @layer: The layer that was added to @timeline
677    *
678    * Will be emitted after the layer is added to the timeline.
679    *
680    * Note that this should not be emitted whilst a timeline is being
681    * loaded from its #GESProject asset. You should connect to the
682    * project's #GESProject::loaded signal if you want to know which
683    * layers were created for the timeline.
684    */
685   ges_timeline_signals[LAYER_ADDED] =
686       g_signal_new ("layer-added", G_TYPE_FROM_CLASS (klass),
687       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, layer_added), NULL,
688       NULL, NULL, G_TYPE_NONE, 1, GES_TYPE_LAYER);
689
690   /**
691    * GESTimeline::layer-removed:
692    * @timeline: The #GESTimeline
693    * @layer: The layer that was removed from @timeline
694    *
695    * Will be emitted after the layer is removed from the timeline.
696    */
697   ges_timeline_signals[LAYER_REMOVED] =
698       g_signal_new ("layer-removed", G_TYPE_FROM_CLASS (klass),
699       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, layer_removed),
700       NULL, NULL, NULL, G_TYPE_NONE, 1, GES_TYPE_LAYER);
701
702   /**
703    * GESTimeline::group-added
704    * @timeline: The #GESTimeline
705    * @group: The group that was added to @timeline
706    *
707    * Will be emitted after the group is added to to the timeline. This can
708    * happen when grouping with `ges_container_group`, or by adding
709    * containers to a newly created group.
710    *
711    * Note that this should not be emitted whilst a timeline is being
712    * loaded from its #GESProject asset. You should connect to the
713    * project's #GESProject::loaded signal if you want to know which groups
714    * were created for the timeline.
715    */
716   ges_timeline_signals[GROUP_ADDED] =
717       g_signal_new ("group-added", G_TYPE_FROM_CLASS (klass),
718       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, group_added), NULL,
719       NULL, NULL, G_TYPE_NONE, 1, GES_TYPE_GROUP);
720
721   /**
722    * GESTimeline::group-removed
723    * @timeline: The #GESTimeline
724    * @group: The group that was removed from @timeline
725    * @children: (element-type GESContainer) (transfer none): A list
726    * of #GESContainer-s that _were_ the children of the removed @group
727    *
728    * Will be emitted after the group is removed from the timeline through
729    * `ges_container_ungroup`. Note that @group will no longer contain its
730    * former children, these are held in @children.
731    *
732    * Note that if a group is emptied, then it will no longer belong to the
733    * timeline, but this signal will **not** be emitted in such a case.
734    */
735   ges_timeline_signals[GROUP_REMOVED] =
736       g_signal_new ("group-removed", G_TYPE_FROM_CLASS (klass),
737       G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GESTimelineClass, group_removed),
738       NULL, NULL, NULL, G_TYPE_NONE, 2, GES_TYPE_GROUP, G_TYPE_PTR_ARRAY);
739
740   /**
741    * GESTimeline::snapping-started:
742    * @timeline: The #GESTimeline
743    * @obj1: The first element that is snapping
744    * @obj2: The second element that is snapping
745    * @position: The position where the two objects will snap to
746    *
747    * Will be emitted whenever an element's movement invokes a snapping
748    * event during an edit (usually of one of its ancestors) because its
749    * start or end point lies within the #GESTimeline:snapping-distance of
750    * another element's start or end point.
751    *
752    * See #GESEditMode to see what can snap during an edit.
753    *
754    * Note that only up to one snapping-started signal will be emitted per
755    * element edit within a timeline.
756    */
757   ges_timeline_signals[SNAPING_STARTED] =
758       g_signal_new ("snapping-started", G_TYPE_FROM_CLASS (klass),
759       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
760       G_TYPE_NONE, 3, GES_TYPE_TRACK_ELEMENT, GES_TYPE_TRACK_ELEMENT,
761       G_TYPE_UINT64);
762
763   /**
764    * GESTimeline::snapping-ended:
765    * @timeline: The #GESTimeline
766    * @obj1: The first element that was snapping
767    * @obj2: The second element that was snapping
768    * @position: The position where the two objects were to be snapped to
769    *
770    * Will be emitted whenever a snapping event ends. After a snap event
771    * has started (see #GESTimeline::snapping-started), it can later end
772    * because either another timeline edit has occurred (which may or may
773    * not have created a new snapping event), or because the timeline has
774    * been committed.
775    */
776   ges_timeline_signals[SNAPING_ENDED] =
777       g_signal_new ("snapping-ended", G_TYPE_FROM_CLASS (klass),
778       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
779       G_TYPE_NONE, 3, GES_TYPE_TRACK_ELEMENT, GES_TYPE_TRACK_ELEMENT,
780       G_TYPE_UINT64);
781
782   /**
783    * GESTimeline::select-tracks-for-object:
784    * @timeline: The #GESTimeline
785    * @clip: The clip that @track_element is being added to
786    * @track_element: The element being added
787    *
788    * This will be emitted whenever the timeline needs to determine which
789    * tracks a clip's children should be added to. The track element will
790    * be added to each of the tracks given in the return. If a track
791    * element is selected to go into multiple tracks, it will be copied
792    * into the additional tracks, under the same clip. Note that the copy
793    * will *not* keep its properties or state in sync with the original.
794    *
795    * Connect to this signal once if you wish to control which element
796    * should be added to which track. Doing so will overwrite the default
797    * behaviour, which adds @track_element to all tracks whose
798    * #GESTrack:track-type includes the @track_element's
799    * #GESTrackElement:track-type.
800    *
801    * Note that under the default track selection, if a clip would produce
802    * multiple core children of the same #GESTrackType, it will choose
803    * one of the core children arbitrarily to place in the corresponding
804    * tracks, with a warning for the other core children that are not
805    * placed in the track. For example, this would happen for a #GESUriClip
806    * that points to a file that contains multiple audio streams. If you
807    * wish to choose the stream, you could connect to this signal, and use,
808    * say, ges_uri_source_asset_get_stream_info() to choose which core
809    * source to add.
810    *
811    * When a clip is first added to a timeline, its core elements will
812    * be created for the current tracks in the timeline if they have not
813    * already been created. Then this will be emitted for each of these
814    * core children to select which tracks, if any, they should be added
815    * to. It will then be called for any non-core children in the clip.
816    *
817    * In addition, if a new track element is ever added to a clip in a
818    * timeline (and it is not already part of a track) this will be emitted
819    * to select which tracks the element should be added to.
820    *
821    * Finally, as a special case, if a track is added to the timeline
822    * *after* it already contains clips, then it will request the creation
823    * of the clips' core elements of the corresponding type, if they have
824    * not already been created, and this signal will be emitted for each of
825    * these newly created elements. In addition, this will also be released
826    * for all other track elements in the timeline's clips that have not
827    * yet been assigned a track. However, in this final case, the timeline
828    * will only check whether the newly added track appears in the track
829    * list. If it does appear, the track element will be added to the newly
830    * added track. All other tracks in the returned track list are ignored.
831    *
832    * In this latter case, track elements that are already part of a track
833    * will not be asked if they want to be copied into the new track. If
834    * you wish to do this, you can use ges_clip_add_child_to_track().
835    *
836    * Note that the returned #GPtrArray should own a new reference to each
837    * of its contained #GESTrack. The timeline will set the #GDestroyNotify
838    * free function on the #GPtrArray to dereference the elements.
839    *
840    * Returns: (transfer full) (element-type GESTrack): An array of
841    * #GESTrack-s that @track_element should be added to, or %NULL to
842    * not add the element to any track.
843    */
844   ges_timeline_signals[SELECT_TRACKS_FOR_OBJECT] =
845       g_signal_new ("select-tracks-for-object", G_TYPE_FROM_CLASS (klass),
846       G_SIGNAL_RUN_LAST, 0, _gst_array_accumulator, NULL, NULL,
847       G_TYPE_PTR_ARRAY, 2, GES_TYPE_CLIP, GES_TYPE_TRACK_ELEMENT);
848
849   /**
850    * GESTimeline::select-element-track:
851    * @timeline: The #GESTimeline
852    * @clip: The clip that @track_element is being added to
853    * @track_element: The element being added
854    *
855    * Simplified version of #GESTimeline::select-tracks-for-object which only
856    * allows @track_element to be added to a single #GESTrack.
857    *
858    * Returns: (transfer full): A track to put @track_element into, or %NULL if
859    * it should be discarded.
860    *
861    * Since: 1.18
862    */
863   ges_timeline_signals[SELECT_ELEMENT_TRACK] =
864       g_signal_new ("select-element-track", G_TYPE_FROM_CLASS (klass),
865       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
866       GES_TYPE_TRACK, 2, GES_TYPE_CLIP, GES_TYPE_TRACK_ELEMENT);
867
868   /**
869    * GESTimeline::commited:
870    * @timeline: The #GESTimeline
871    *
872    * This signal will be emitted once the changes initiated by
873    * ges_timeline_commit() have been executed in the backend. Use
874    * ges_timeline_commit_sync() if you do not want to have to connect
875    * to this signal.
876    */
877   ges_timeline_signals[COMMITED] =
878       g_signal_new ("commited", G_TYPE_FROM_CLASS (klass),
879       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0);
880 }
881
882 static void
883 ges_timeline_init (GESTimeline * self)
884 {
885   GESTimelinePrivate *priv = self->priv;
886
887   self->priv = ges_timeline_get_instance_private (self);
888   self->priv->tree = g_node_new (self);
889
890   priv = self->priv;
891   self->layers = NULL;
892   self->tracks = NULL;
893   self->priv->duration = 0;
894   self->priv->auto_transition = FALSE;
895   priv->snapping_distance = 0;
896   priv->expected_async_done = 0;
897   priv->expected_commited = 0;
898
899   self->priv->last_snap_ts = GST_CLOCK_TIME_NONE;
900
901   priv->priv_tracks = NULL;
902
903   priv->all_elements =
904       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, gst_object_unref);
905
906   priv->stream_start_group_id = -1;
907   priv->stream_collection = gst_stream_collection_new (NULL);
908
909   g_signal_connect_after (self, "select-tracks-for-object",
910       G_CALLBACK (select_tracks_for_object_default), NULL);
911
912   g_rec_mutex_init (&priv->dyn_mutex);
913   g_mutex_init (&priv->commited_lock);
914   priv->valid_thread = g_thread_self ();
915 }
916
917 /* Private methods */
918
919 /* Sorting utils*/
920 static gint
921 sort_layers (gpointer a, gpointer b)
922 {
923   GESLayer *layer_a, *layer_b;
924   guint prio_a, prio_b;
925
926   layer_a = GES_LAYER (a);
927   layer_b = GES_LAYER (b);
928
929   prio_a = ges_layer_get_priority (layer_a);
930   prio_b = ges_layer_get_priority (layer_b);
931
932   if (prio_a > prio_b)
933     return 1;
934   if (prio_a < prio_b)
935     return -1;
936
937   return 0;
938 }
939
940 static void
941 _resync_layers (GESTimeline * timeline)
942 {
943   GList *tmp;
944   gint i = 0;
945
946   timeline->priv->resyncing_layers = TRUE;
947   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
948     layer_set_priority (tmp->data, i, TRUE);
949     i++;
950   }
951   timeline->priv->resyncing_layers = FALSE;
952 }
953
954 void
955 timeline_update_duration (GESTimeline * timeline)
956 {
957   GstClockTime duration = timeline_tree_get_duration (timeline->priv->tree);
958
959   if (timeline->priv->duration != duration) {
960     GST_DEBUG ("track duration : %" GST_TIME_FORMAT " current : %"
961         GST_TIME_FORMAT, GST_TIME_ARGS (duration),
962         GST_TIME_ARGS (timeline->priv->duration));
963
964     timeline->priv->duration = duration;
965
966     g_object_notify_by_pspec (G_OBJECT (timeline), properties[PROP_DURATION]);
967   }
968 }
969
970 static gint
971 custom_find_track (TrackPrivate * tr_priv, GESTrack * track)
972 {
973   if (tr_priv->track == track)
974     return 0;
975   return -1;
976 }
977
978 static void
979 _destroy_auto_transition_cb (GESAutoTransition * auto_transition,
980     GESTimeline * timeline)
981 {
982   GESTimelinePrivate *priv = timeline->priv;
983   GESClip *transition = auto_transition->transition_clip;
984   GESLayer *layer = ges_clip_get_layer (transition);
985
986   ges_layer_remove_clip (layer, transition);
987   g_signal_handlers_disconnect_by_func (auto_transition,
988       _destroy_auto_transition_cb, timeline);
989
990   priv->auto_transitions =
991       g_list_remove (priv->auto_transitions, auto_transition);
992   gst_object_unref (auto_transition);
993 }
994
995 GESAutoTransition *
996 ges_timeline_create_transition (GESTimeline * timeline,
997     GESTrackElement * previous, GESTrackElement * next, GESClip * transition,
998     GESLayer * layer, guint64 start, guint64 duration)
999 {
1000   GESAutoTransition *auto_transition;
1001   GESTrackElement *child;
1002   /* track should not be NULL */
1003   GESTrack *track = ges_track_element_get_track (next);
1004
1005   if (transition == NULL) {
1006     GESAsset *asset;
1007
1008     LOCK_DYN (timeline);
1009     timeline->priv->auto_transition_track = gst_object_ref (track);
1010     UNLOCK_DYN (timeline);
1011
1012     asset = ges_asset_request (GES_TYPE_TRANSITION_CLIP, "crossfade", NULL);
1013     transition = ges_layer_add_asset (layer, asset, start, 0, duration,
1014         ges_track_element_get_track_type (next));
1015     gst_object_unref (asset);
1016
1017     LOCK_DYN (timeline);
1018     /* should have been set to NULL, but clear just in case */
1019     gst_clear_object (&timeline->priv->auto_transition_track);
1020     UNLOCK_DYN (timeline);
1021   } else {
1022     GST_DEBUG_OBJECT (timeline,
1023         "Reusing already existing transition: %" GST_PTR_FORMAT, transition);
1024   }
1025
1026   g_return_val_if_fail (transition, NULL);
1027   g_return_val_if_fail (g_list_length (GES_CONTAINER_CHILDREN (transition)) ==
1028       1, NULL);
1029   child = GES_CONTAINER_CHILDREN (transition)->data;
1030   if (ges_track_element_get_track (child) != track) {
1031     GST_ERROR_OBJECT (timeline, "The auto transition element %"
1032         GES_FORMAT " for elements %" GES_FORMAT " and %" GES_FORMAT
1033         " is not in the same track %" GST_PTR_FORMAT,
1034         GES_ARGS (child), GES_ARGS (previous), GES_ARGS (next), track);
1035     return NULL;
1036   }
1037
1038   /* We know there is only 1 TrackElement */
1039   auto_transition = ges_auto_transition_new (child, previous, next);
1040
1041   g_signal_connect (auto_transition, "destroy-me",
1042       G_CALLBACK (_destroy_auto_transition_cb), timeline);
1043
1044   timeline->priv->auto_transitions =
1045       g_list_prepend (timeline->priv->auto_transitions, auto_transition);
1046
1047   return auto_transition;
1048 }
1049
1050 GESAutoTransition *
1051 ges_timeline_find_auto_transition (GESTimeline * timeline,
1052     GESTrackElement * prev, GESTrackElement * next,
1053     GstClockTime transition_duration)
1054 {
1055   GList *tmp;
1056
1057   for (tmp = timeline->priv->auto_transitions; tmp; tmp = tmp->next) {
1058     GESAutoTransition *auto_trans = (GESAutoTransition *) tmp->data;
1059
1060     /* We already have a transition linked to one of the elements we want to
1061      * find a transition for */
1062     if (auto_trans->previous_source == prev || auto_trans->next_source == next) {
1063       if (auto_trans->previous_source != prev
1064           || auto_trans->next_source != next) {
1065         GST_ERROR_OBJECT (timeline, "Failed creating auto transition, "
1066             " trying to have 3 clips overlapping, rolling back");
1067       }
1068
1069       return auto_trans;
1070     }
1071   }
1072
1073   return NULL;
1074 }
1075
1076 GESAutoTransition *
1077 ges_timeline_get_auto_transition_at_edge (GESTimeline * timeline,
1078     GESTrackElement * source, GESEdge edge)
1079 {
1080   GList *tmp, *auto_transitions;
1081   GESAutoTransition *ret = NULL;
1082
1083   LOCK_DYN (timeline);
1084   auto_transitions = g_list_copy_deep (timeline->priv->auto_transitions,
1085       (GCopyFunc) gst_object_ref, NULL);
1086   UNLOCK_DYN (timeline);
1087
1088   for (tmp = auto_transitions; tmp; tmp = tmp->next) {
1089     GESAutoTransition *auto_trans = (GESAutoTransition *) tmp->data;
1090
1091     /* We already have a transition linked to one of the elements we want to
1092      * find a transition for */
1093     if (edge == GES_EDGE_END && auto_trans->previous_source == source) {
1094       ret = gst_object_ref (auto_trans);
1095       break;
1096     } else if (edge == GES_EDGE_START && auto_trans->next_source == source) {
1097       ret = gst_object_ref (auto_trans);
1098       break;
1099     }
1100   }
1101
1102   g_list_free_full (auto_transitions, gst_object_unref);
1103
1104   return ret;
1105 }
1106
1107 static GESAutoTransition *
1108 _create_auto_transition_from_transitions (GESTimeline * timeline,
1109     GESTrackElement * prev, GESTrackElement * next,
1110     GstClockTime transition_duration)
1111 {
1112   GList *tmp, *elements;
1113   GESLayer *layer;
1114   guint32 layer_prio = GES_TIMELINE_ELEMENT_LAYER_PRIORITY (prev);
1115   GESTrack *track;
1116   GESAutoTransition *auto_transition =
1117       ges_timeline_find_auto_transition (timeline, prev, next,
1118       transition_duration);
1119
1120   if (auto_transition)
1121     return auto_transition;
1122
1123   layer = ges_timeline_get_layer (timeline, layer_prio);
1124   track = ges_track_element_get_track (prev);
1125   elements = ges_track_get_elements (track);
1126   for (tmp = elements; tmp; tmp = tmp->next) {
1127     GESTrackElement *maybe_transition = tmp->data;
1128
1129     if (ges_timeline_element_get_layer_priority (tmp->data) != layer_prio)
1130       continue;
1131
1132     if (_START (maybe_transition) > _START (next))
1133       break;
1134     else if (_START (maybe_transition) != _START (next) ||
1135         _DURATION (maybe_transition) != transition_duration)
1136       continue;
1137     else if (GES_IS_TRANSITION (maybe_transition)) {
1138       /* Use that transition */
1139       /* TODO We should make sure that the transition contains only
1140        * TrackElement-s in @track and if it is not the case properly unlink the
1141        * object to use it */
1142       auto_transition = ges_timeline_create_transition (timeline, prev, next,
1143           GES_CLIP (GES_TIMELINE_ELEMENT_PARENT (maybe_transition)), layer,
1144           _START (next), transition_duration);
1145
1146       break;
1147     }
1148   }
1149   gst_object_unref (layer);
1150   g_list_free_full (elements, gst_object_unref);
1151
1152   return auto_transition;
1153 }
1154
1155 void
1156 ges_timeline_emit_snapping (GESTimeline * timeline, GESTrackElement * elem1,
1157     GESTrackElement * elem2, GstClockTime snap_time)
1158 {
1159   GESTimelinePrivate *priv = timeline->priv;
1160   GstClockTime last_snap_ts = timeline->priv->last_snap_ts;
1161
1162   if (!GST_CLOCK_TIME_IS_VALID (snap_time)) {
1163     if (priv->last_snaped1 != NULL && priv->last_snaped2 != NULL) {
1164       g_signal_emit (timeline, ges_timeline_signals[SNAPING_ENDED], 0,
1165           priv->last_snaped1, priv->last_snaped2, last_snap_ts);
1166       priv->last_snaped1 = NULL;
1167       priv->last_snaped2 = NULL;
1168       priv->last_snap_ts = GST_CLOCK_TIME_NONE;
1169     }
1170
1171     return;
1172   }
1173
1174   g_assert (elem1 != elem2);
1175
1176   if (GST_CLOCK_TIME_IS_VALID (last_snap_ts))
1177     g_signal_emit (timeline, ges_timeline_signals[SNAPING_ENDED], 0,
1178         priv->last_snaped1, priv->last_snaped2, (last_snap_ts));
1179
1180   priv->last_snaped1 = elem1;
1181   priv->last_snaped2 = elem2;
1182   timeline->priv->last_snap_ts = snap_time;
1183   g_signal_emit (timeline, ges_timeline_signals[SNAPING_STARTED], 0,
1184       elem1, elem2, snap_time);
1185 }
1186
1187 /* Accept @self == NULL, making it use default framerate */
1188 void
1189 timeline_get_framerate (GESTimeline * self, gint * fps_n, gint * fps_d)
1190 {
1191   GList *tmp;
1192
1193   *fps_n = *fps_d = -1;
1194   if (!self)
1195     goto done;
1196
1197   LOCK_DYN (self);
1198   for (tmp = self->tracks; tmp; tmp = tmp->next) {
1199     if (GES_IS_VIDEO_TRACK (tmp->data)) {
1200       GstCaps *restriction = ges_track_get_restriction_caps (tmp->data);
1201       gint i;
1202
1203       if (!restriction)
1204         continue;
1205
1206       for (i = 0; i < gst_caps_get_size (restriction); i++) {
1207         gint n, d;
1208
1209         if (!gst_structure_get_fraction (gst_caps_get_structure (restriction,
1210                     i), "framerate", &n, &d))
1211           continue;
1212
1213         if (*fps_n != -1 && *fps_d != -1 && !(n == *fps_n && d == *fps_d)) {
1214           GST_WARNING_OBJECT (self,
1215               "Various framerates specified, this is not supported"
1216               " First one will be used.");
1217           continue;
1218         }
1219
1220         *fps_n = n;
1221         *fps_d = d;
1222       }
1223       gst_caps_unref (restriction);
1224     }
1225   }
1226   UNLOCK_DYN (self);
1227
1228 done:
1229   if (*fps_n == -1 && *fps_d == -1) {
1230     GST_INFO_OBJECT (self,
1231         "No framerate found, using default " G_STRINGIFY (FRAMERATE_N) "/ "
1232         G_STRINGIFY (FRAMERATE_D));
1233     *fps_n = DEFAULT_FRAMERATE_N;
1234     *fps_d = DEFAULT_FRAMERATE_D;
1235   }
1236 }
1237
1238 void
1239 ges_timeline_freeze_auto_transitions (GESTimeline * timeline, gboolean freeze)
1240 {
1241   GList *tmp, *trans = g_list_copy (timeline->priv->auto_transitions);
1242   for (tmp = trans; tmp; tmp = tmp->next) {
1243     GESAutoTransition *auto_transition = tmp->data;
1244     auto_transition->frozen = freeze;
1245     if (freeze == FALSE) {
1246       GST_LOG_OBJECT (timeline, "Un-Freezing %" GES_FORMAT,
1247           GES_ARGS (auto_transition->transition_clip));
1248       ges_auto_transition_update (auto_transition);
1249     } else {
1250       GST_LOG_OBJECT (timeline, "Freezing %" GES_FORMAT,
1251           GES_ARGS (auto_transition->transition_clip));
1252     }
1253   }
1254   g_list_free (trans);
1255 }
1256
1257 static gint
1258 _edit_auto_transition (GESTimeline * timeline, GESTimelineElement * element,
1259     gint64 new_layer_priority, GESEditMode mode, GESEdge edge,
1260     GstClockTime position, GError ** error)
1261 {
1262   GList *tmp;
1263   guint32 layer_prio = ges_timeline_element_get_layer_priority (element);
1264   GESLayer *layer = ges_timeline_get_layer (timeline, layer_prio);
1265
1266   if (!ges_layer_get_auto_transition (layer)) {
1267     gst_object_unref (layer);
1268     return -1;
1269   }
1270
1271   gst_object_unref (layer);
1272   for (tmp = timeline->priv->auto_transitions; tmp; tmp = tmp->next) {
1273     GESTimelineElement *replace;
1274     GESAutoTransition *auto_transition = tmp->data;
1275
1276     if (GES_TIMELINE_ELEMENT (auto_transition->transition) == element ||
1277         GES_TIMELINE_ELEMENT (auto_transition->transition_clip) == element) {
1278       if (auto_transition->positioning) {
1279         GST_ERROR_OBJECT (element, "Trying to edit an auto-transition "
1280             "whilst it is being positioned");
1281         return FALSE;
1282       }
1283       if (new_layer_priority != layer_prio) {
1284         GST_WARNING_OBJECT (element, "Cannot edit an auto-transition to a "
1285             "new layer");
1286         return FALSE;
1287       }
1288       if (mode != GES_EDIT_MODE_TRIM) {
1289         GST_WARNING_OBJECT (element, "Cannot edit an auto-transition "
1290             "under the edit mode %i", mode);
1291         return FALSE;
1292       }
1293
1294       if (edge == GES_EDGE_END)
1295         replace = GES_TIMELINE_ELEMENT (auto_transition->previous_source);
1296       else
1297         replace = GES_TIMELINE_ELEMENT (auto_transition->next_source);
1298
1299       GST_INFO_OBJECT (element, "Trimming %" GES_FORMAT " in place  of "
1300           "trimming the corresponding auto-transition", GES_ARGS (replace));
1301       return ges_timeline_element_edit_full (replace, -1, mode, edge,
1302           position, error);
1303     }
1304   }
1305
1306   return -1;
1307 }
1308
1309 gboolean
1310 ges_timeline_edit (GESTimeline * timeline, GESTimelineElement * element,
1311     gint64 new_layer_priority, GESEditMode mode, GESEdge edge,
1312     guint64 position, GError ** error)
1313 {
1314   GstClockTimeDiff edge_diff = (edge == GES_EDGE_END ?
1315       GST_CLOCK_DIFF (position, element->start + element->duration) :
1316       GST_CLOCK_DIFF (position, element->start));
1317   gint64 prio_diff = (gint64) ges_timeline_element_get_layer_priority (element)
1318       - new_layer_priority;
1319   gint res = -1;
1320
1321   if ((GES_IS_TRANSITION (element) || GES_IS_TRANSITION_CLIP (element)))
1322     res = _edit_auto_transition (timeline, element, new_layer_priority, mode,
1323         edge, position, error);
1324
1325   if (res != -1)
1326     return res;
1327
1328   switch (mode) {
1329     case GES_EDIT_MODE_RIPPLE:
1330       return timeline_tree_ripple (timeline->priv->tree, element, prio_diff,
1331           edge_diff, edge, timeline->priv->snapping_distance, error);
1332     case GES_EDIT_MODE_TRIM:
1333       return timeline_tree_trim (timeline->priv->tree, element, prio_diff,
1334           edge_diff, edge, timeline->priv->snapping_distance, error);
1335     case GES_EDIT_MODE_NORMAL:
1336       return timeline_tree_move (timeline->priv->tree, element, prio_diff,
1337           edge_diff, edge, timeline->priv->snapping_distance, error);
1338     case GES_EDIT_MODE_ROLL:
1339       if (prio_diff != 0) {
1340         GST_WARNING_OBJECT (element, "Cannot roll an element to a new layer");
1341         return FALSE;
1342       }
1343       return timeline_tree_roll (timeline->priv->tree, element,
1344           edge_diff, edge, timeline->priv->snapping_distance, error);
1345     case GES_EDIT_MODE_SLIDE:
1346       GST_ERROR_OBJECT (element, "Sliding not implemented.");
1347       return FALSE;
1348   }
1349   return FALSE;
1350 }
1351
1352 void
1353 timeline_add_group (GESTimeline * timeline, GESGroup * group)
1354 {
1355   GST_DEBUG_OBJECT (timeline, "Adding group %" GST_PTR_FORMAT, group);
1356
1357   timeline->priv->groups = g_list_prepend (timeline->priv->groups,
1358       gst_object_ref_sink (group));
1359
1360   ges_timeline_element_set_timeline (GES_TIMELINE_ELEMENT (group), timeline);
1361 }
1362
1363 /**
1364  * timeline_emit_group_added:
1365  * @timeline: The #GESTimeline
1366  * @group: group that was added
1367  *
1368  * Emit group-added signal.
1369  */
1370 void
1371 timeline_emit_group_added (GESTimeline * timeline, GESGroup * group)
1372 {
1373   g_signal_emit (timeline, ges_timeline_signals[GROUP_ADDED], 0, group);
1374 }
1375
1376 /**
1377  * timeline_emit_group_removed:
1378  * @timeline: The #GESTimeline
1379  * @group: group that was removed
1380  *
1381  * Emit group-removed signal.
1382  */
1383 void
1384 timeline_emit_group_removed (GESTimeline * timeline, GESGroup * group,
1385     GPtrArray * array)
1386 {
1387   g_signal_emit (timeline, ges_timeline_signals[GROUP_REMOVED], 0, group,
1388       array);
1389 }
1390
1391 void
1392 timeline_remove_group (GESTimeline * timeline, GESGroup * group)
1393 {
1394   GST_DEBUG_OBJECT (timeline, "Removing group %" GST_PTR_FORMAT, group);
1395
1396   timeline->priv->groups = g_list_remove (timeline->priv->groups, group);
1397
1398   ges_timeline_element_set_timeline (GES_TIMELINE_ELEMENT (group), NULL);
1399   gst_object_unref (group);
1400 }
1401
1402 static GESTrackElement *
1403 _core_in_track (GESTrack * track, GESClip * clip)
1404 {
1405   GList *tmp;
1406   for (tmp = GES_CONTAINER_CHILDREN (clip); tmp; tmp = tmp->next) {
1407     GESTrackElement *el = tmp->data;
1408     if (ges_track_element_is_core (el)
1409         && ges_track_element_get_track (el) == track) {
1410       return tmp->data;
1411     }
1412   }
1413   return NULL;
1414 }
1415
1416 static GPtrArray *
1417 select_tracks_for_object_default (GESTimeline * timeline,
1418     GESClip * clip, GESTrackElement * tr_object, gpointer user_data)
1419 {
1420   GPtrArray *result;
1421   GList *tmp;
1422   GESTrackElement *core;
1423
1424   result = g_ptr_array_new ();
1425
1426   LOCK_DYN (timeline);
1427   for (tmp = timeline->tracks; tmp; tmp = tmp->next) {
1428     GESTrack *track = GES_TRACK (tmp->data);
1429
1430     if ((track->type & ges_track_element_get_track_type (tr_object))) {
1431       if (ges_track_element_is_core (tr_object)) {
1432         core = _core_in_track (track, clip);
1433         if (core) {
1434           GST_WARNING_OBJECT (timeline, "The clip '%s' contains multiple "
1435               "core elements of the same %s track type. The core child "
1436               "'%s' has already been chosen arbitrarily for the track %"
1437               GST_PTR_FORMAT ", which means that the other core child "
1438               "'%s' of the same type can not be added to the track. "
1439               "Consider connecting to "
1440               "GESTimeline::select-tracks-for-objects to be able to "
1441               "specify which core element should land in the track",
1442               GES_TIMELINE_ELEMENT_NAME (clip),
1443               ges_track_type_name (track->type),
1444               GES_TIMELINE_ELEMENT_NAME (core), track,
1445               GES_TIMELINE_ELEMENT_NAME (tr_object));
1446           continue;
1447         }
1448       }
1449       gst_object_ref (track);
1450       g_ptr_array_add (result, track);
1451     }
1452   }
1453   UNLOCK_DYN (timeline);
1454
1455   return result;
1456 }
1457
1458 static GPtrArray *
1459 _get_selected_tracks (GESTimeline * timeline, GESClip * clip,
1460     GESTrackElement * track_element)
1461 {
1462   guint i, j;
1463   GPtrArray *tracks = NULL;
1464   GESTrack *track = NULL;
1465
1466   g_signal_emit (G_OBJECT (timeline),
1467       ges_timeline_signals[SELECT_ELEMENT_TRACK], 0, clip, track_element,
1468       &track);
1469
1470   if (track) {
1471     tracks = g_ptr_array_new ();
1472
1473     g_ptr_array_add (tracks, track);
1474   } else {
1475     g_signal_emit (G_OBJECT (timeline),
1476         ges_timeline_signals[SELECT_TRACKS_FOR_OBJECT], 0, clip, track_element,
1477         &tracks);
1478   }
1479
1480   if (tracks == NULL)
1481     tracks = g_ptr_array_new ();
1482
1483   g_ptr_array_set_free_func (tracks, gst_object_unref);
1484
1485   /* make sure unique */
1486   for (i = 0; i < tracks->len;) {
1487     GESTrack *track = GES_TRACK (g_ptr_array_index (tracks, i));
1488
1489     for (j = i + 1; j < tracks->len;) {
1490       if (track == g_ptr_array_index (tracks, j)) {
1491         GST_WARNING_OBJECT (timeline, "Found the track %" GST_PTR_FORMAT
1492             " more than once in the return for select-tracks-for-object "
1493             "signal for track element %" GES_FORMAT " in clip %"
1494             GES_FORMAT ". Ignoring the extra track", track,
1495             GES_ARGS (track_element), GES_ARGS (clip));
1496         g_ptr_array_remove_index (tracks, j);
1497         /* don't increase index since the next track is in its place */
1498         continue;
1499       }
1500       j++;
1501     }
1502
1503     if (ges_track_get_timeline (track) != timeline) {
1504       GST_WARNING_OBJECT (timeline, "The track %" GST_PTR_FORMAT
1505           " found in the return for select-tracks-for-object belongs "
1506           "to a different timeline %" GST_PTR_FORMAT ". Ignoring this "
1507           "track", track, ges_track_get_timeline (track));
1508       g_ptr_array_remove_index (tracks, i);
1509       /* don't increase index since the next track is in its place */
1510       continue;
1511     }
1512     i++;
1513   }
1514
1515   return tracks;
1516 }
1517
1518 /* returns TRUE if track element was successfully added to all the
1519  * selected tracks */
1520 static gboolean
1521 _add_track_element_to_tracks (GESTimeline * timeline, GESClip * clip,
1522     GESTrackElement * track_element, GError ** error)
1523 {
1524   guint i;
1525   gboolean ret = TRUE;
1526   GPtrArray *tracks = _get_selected_tracks (timeline, clip, track_element);
1527
1528   for (i = 0; i < tracks->len; i++) {
1529     GESTrack *track = GES_TRACK (g_ptr_array_index (tracks, i));
1530     if (!ges_clip_add_child_to_track (clip, track_element, track, error)) {
1531       ret = FALSE;
1532       if (error)
1533         break;
1534     }
1535   }
1536
1537   g_ptr_array_unref (tracks);
1538
1539   return ret;
1540 }
1541
1542 static gboolean
1543 _try_add_track_element_to_track (GESTimeline * timeline, GESClip * clip,
1544     GESTrackElement * track_element, GESTrack * track, GError ** error)
1545 {
1546   gboolean no_error = TRUE;
1547   GPtrArray *tracks = _get_selected_tracks (timeline, clip, track_element);
1548
1549   /* if we are trying to add the element to a newly added track, then
1550    * we only check whether the track list contains the newly added track,
1551    * if it does we add the track element to the track, or add a copy if
1552    * the track element is already in a track */
1553   if (g_ptr_array_find (tracks, track, NULL)) {
1554     if (!ges_clip_add_child_to_track (clip, track_element, track, error))
1555       no_error = FALSE;
1556   }
1557
1558   g_ptr_array_unref (tracks);
1559   return no_error;
1560 }
1561
1562 /* accepts NULL */
1563 void
1564 ges_timeline_set_moving_track_elements (GESTimeline * timeline, gboolean moving)
1565 {
1566   if (timeline) {
1567     LOCK_DYN (timeline);
1568     timeline->priv->track_elements_moving = moving;
1569     UNLOCK_DYN (timeline);
1570   }
1571 }
1572
1573 void
1574 ges_timeline_set_track_selection_error (GESTimeline * timeline,
1575     gboolean was_error, GError * error)
1576 {
1577   GESTimelinePrivate *priv;
1578
1579   LOCK_DYN (timeline);
1580
1581   priv = timeline->priv;
1582   g_clear_error (&priv->track_selection_error);
1583   priv->track_selection_error = error;
1584   priv->has_any_track_selection_error = was_error;
1585
1586   UNLOCK_DYN (timeline);
1587 }
1588
1589 gboolean
1590 ges_timeline_take_track_selection_error (GESTimeline * timeline,
1591     GError ** error)
1592 {
1593   gboolean ret;
1594   GESTimelinePrivate *priv;
1595
1596   LOCK_DYN (timeline);
1597
1598   priv = timeline->priv;
1599   if (error) {
1600     if (*error) {
1601       GST_ERROR_OBJECT (timeline, "Error not handled %s", (*error)->message);
1602       g_error_free (*error);
1603     }
1604     *error = priv->track_selection_error;
1605   } else if (priv->track_selection_error) {
1606     GST_WARNING_OBJECT (timeline, "Got track selection error: %s",
1607         priv->track_selection_error->message);
1608     g_error_free (priv->track_selection_error);
1609   }
1610   priv->track_selection_error = NULL;
1611   ret = priv->has_any_track_selection_error;
1612   priv->has_any_track_selection_error = FALSE;
1613
1614   UNLOCK_DYN (timeline);
1615
1616   return ret;
1617 }
1618
1619 static void
1620 clip_track_element_added_cb (GESClip * clip,
1621     GESTrackElement * track_element, GESTimeline * timeline)
1622 {
1623   GESTrack *auto_trans_track, *new_track;
1624   GError *error = NULL;
1625   gboolean success = FALSE;
1626
1627   if (timeline->priv->track_elements_moving) {
1628     GST_DEBUG_OBJECT (timeline, "Ignoring element added: %" GES_FORMAT
1629         " in %" GES_FORMAT, GES_ARGS (track_element), GES_ARGS (clip));
1630     return;
1631   }
1632
1633   if (ges_track_element_get_track (track_element) != NULL) {
1634     GST_DEBUG_OBJECT (timeline, "Not selecting tracks for %" GES_FORMAT
1635         " in %" GES_FORMAT " because it already part of the track %"
1636         GST_PTR_FORMAT, GES_ARGS (track_element), GES_ARGS (clip),
1637         ges_track_element_get_track (track_element));
1638     return;
1639   }
1640
1641   LOCK_DYN (timeline);
1642   /* take ownership of auto_transition_track. For auto-transitions, this
1643    * should be used exactly once! */
1644   auto_trans_track = timeline->priv->auto_transition_track;
1645   timeline->priv->auto_transition_track = NULL;
1646   /* don't take ownership of new_track */
1647   new_track = timeline->priv->new_track;
1648   UNLOCK_DYN (timeline);
1649
1650   if (auto_trans_track) {
1651     /* don't use track-selection */
1652     success = ! !ges_clip_add_child_to_track (clip, track_element,
1653         auto_trans_track, &error);
1654     gst_object_unref (auto_trans_track);
1655   } else {
1656     if (new_track)
1657       success = _try_add_track_element_to_track (timeline, clip, track_element,
1658           new_track, &error);
1659     else
1660       success = _add_track_element_to_tracks (timeline, clip, track_element,
1661           &error);
1662   }
1663
1664   if (error || !success) {
1665     if (!error)
1666       GST_WARNING_OBJECT (timeline, "Track selection failed for %" GES_FORMAT,
1667           GES_ARGS (track_element));
1668     ges_timeline_set_track_selection_error (timeline, TRUE, error);
1669   }
1670 }
1671
1672 static void
1673 clip_track_element_removed_cb (GESClip * clip,
1674     GESTrackElement * track_element, GESTimeline * timeline)
1675 {
1676   GESTrack *track = ges_track_element_get_track (track_element);
1677
1678   if (timeline->priv->track_elements_moving) {
1679     GST_DEBUG_OBJECT (timeline, "Ignoring element removed (%" GST_PTR_FORMAT
1680         " in %" GST_PTR_FORMAT, track_element, clip);
1681
1682     return;
1683   }
1684
1685   if (track) {
1686     /* if we have non-core elements in the same track, they should be
1687      * removed from them to preserve the rule that a non-core can only be
1688      * in the same track as a core element from the same clip */
1689     if (ges_track_element_is_core (track_element))
1690       ges_clip_empty_from_track (clip, track);
1691     ges_track_remove_element (track, track_element);
1692   }
1693 }
1694
1695 static void
1696 track_element_added_cb (GESTrack * track, GESTrackElement * element,
1697     GESTimeline * timeline)
1698 {
1699   if (GES_IS_SOURCE (element))
1700     timeline_tree_create_transitions_for_track_element (timeline->priv->tree,
1701         element, ges_timeline_find_auto_transition);
1702 }
1703
1704 /* returns TRUE if no errors in adding to tracks */
1705 static gboolean
1706 _add_clip_children_to_tracks (GESTimeline * timeline, GESClip * clip,
1707     gboolean add_core, GESTrack * new_track, GList * blacklist, GError ** error)
1708 {
1709   GList *tmp, *children;
1710   gboolean no_errors = TRUE;
1711
1712   /* list of children may change if some are copied into tracks */
1713   children = ges_container_get_children (GES_CONTAINER (clip), FALSE);
1714   for (tmp = children; tmp; tmp = tmp->next) {
1715     GESTrackElement *el = tmp->data;
1716     if (ges_track_element_is_core (el) != add_core)
1717       continue;
1718     if (g_list_find (blacklist, el))
1719       continue;
1720     if (ges_track_element_get_track (el) == NULL) {
1721       gboolean res;
1722       if (new_track)
1723         res = _try_add_track_element_to_track (timeline, clip, el, new_track,
1724             error);
1725       else
1726         res = _add_track_element_to_tracks (timeline, clip, el, error);
1727       if (!res) {
1728         no_errors = FALSE;
1729         if (error)
1730           goto done;
1731       }
1732     }
1733   }
1734
1735 done:
1736   g_list_free_full (children, gst_object_unref);
1737
1738   return no_errors;
1739 }
1740
1741 /* returns TRUE if no errors in adding to tracks */
1742 static gboolean
1743 add_object_to_tracks (GESTimeline * timeline, GESClip * clip,
1744     GESTrack * new_track, GError ** error)
1745 {
1746   GList *tracks, *tmp, *list, *created, *just_added = NULL;
1747   gboolean no_errors = TRUE;
1748
1749   GST_DEBUG_OBJECT (timeline, "Creating %" GST_PTR_FORMAT
1750       " trackelements and adding them to our tracks", clip);
1751
1752   LOCK_DYN (timeline);
1753   tracks =
1754       g_list_copy_deep (timeline->tracks, (GCopyFunc) gst_object_ref, NULL);
1755   timeline->priv->new_track = new_track ? gst_object_ref (new_track) : NULL;
1756   UNLOCK_DYN (timeline);
1757
1758   /* create core elements */
1759   for (tmp = tracks; tmp; tmp = tmp->next) {
1760     GESTrack *track = GES_TRACK (tmp->data);
1761     if (new_track && track != new_track)
1762       continue;
1763
1764     list = ges_clip_create_track_elements (clip, track->type);
1765     /* just_added only used for pointer comparison, so safe to include
1766      * elements that may be destroyed because they fail to be added to
1767      * the clip */
1768     just_added = g_list_concat (just_added, list);
1769
1770     for (created = list; created; created = created->next) {
1771       GESTimelineElement *el = created->data;
1772
1773       gst_object_ref (el);
1774
1775       /* make track selection be handled by clip_track_element_added_cb
1776        * This is needed for backward-compatibility: when adding a clip to
1777        * a layer, the track is set for the core elements of the clip
1778        * during the child-added signal emission, just before the user's
1779        * own connection.
1780        * NOTE: for the children that have not just been created, they
1781        * are already part of the clip and so child-added will not be
1782        * released. And when a child is selected for multiple tracks, their
1783        * copy will be added to the clip before the track is selected, so
1784        * the track will not be set in the child-added signal */
1785       ges_timeline_set_track_selection_error (timeline, FALSE, NULL);
1786       ges_clip_set_add_error (clip, NULL);
1787       if (!ges_container_add (GES_CONTAINER (clip), el)) {
1788         no_errors = FALSE;
1789         if (!error)
1790           GST_ERROR_OBJECT (clip, "Could not add the core element %s "
1791               "to the clip", el->name);
1792       }
1793       gst_object_unref (el);
1794       ges_clip_take_add_error (clip, error);
1795
1796       if (error && !no_errors)
1797         goto done;
1798
1799       if (ges_timeline_take_track_selection_error (timeline, error)) {
1800         no_errors = FALSE;
1801         if (error)
1802           goto done;
1803         /* else, carry on as much as we can */
1804       }
1805     }
1806   }
1807
1808   /* set the tracks for the other children, with core elements first to
1809    * make sure the non-core can be placed above them in the track (a
1810    * non-core can not be in a track by itself) */
1811   /* include just_added as a blacklist to ensure we do not try the track
1812    * selection a second time when track selection returns no tracks */
1813   if (!_add_clip_children_to_tracks (timeline, clip, TRUE, new_track,
1814           just_added, error)) {
1815     no_errors = FALSE;
1816     if (error)
1817       goto done;
1818   }
1819
1820   if (!_add_clip_children_to_tracks (timeline, clip, FALSE, new_track,
1821           just_added, error)) {
1822     no_errors = FALSE;
1823     if (error)
1824       goto done;
1825   }
1826
1827 done:
1828   g_list_free_full (tracks, gst_object_unref);
1829
1830   LOCK_DYN (timeline);
1831   gst_clear_object (&timeline->priv->new_track);
1832   UNLOCK_DYN (timeline);
1833
1834   g_list_free (just_added);
1835
1836   return no_errors;
1837 }
1838
1839 static void
1840 layer_active_changed_cb (GESLayer * layer, gboolean active G_GNUC_UNUSED,
1841     GPtrArray * tracks G_GNUC_UNUSED, GESTimeline * timeline)
1842 {
1843   timeline_tree_reset_layer_active (timeline->priv->tree, layer);
1844 }
1845
1846 static void
1847 layer_auto_transition_changed_cb (GESLayer * layer,
1848     GParamSpec * arg G_GNUC_UNUSED, GESTimeline * timeline)
1849 {
1850   GList *tmp, *clips;
1851
1852   timeline_tree_create_transitions (timeline->priv->tree,
1853       _create_auto_transition_from_transitions);
1854   clips = ges_layer_get_clips (layer);
1855   for (tmp = clips; tmp; tmp = tmp->next) {
1856     if (GES_IS_TRANSITION_CLIP (tmp->data)) {
1857       GList *tmpautotrans;
1858       gboolean found = FALSE;
1859
1860       for (tmpautotrans = timeline->priv->auto_transitions; tmpautotrans;
1861           tmpautotrans = tmpautotrans->next) {
1862         if (GES_AUTO_TRANSITION (tmpautotrans->data)->transition_clip ==
1863             tmp->data) {
1864           found = TRUE;
1865           break;
1866         }
1867       }
1868
1869       if (!found) {
1870         GST_ERROR_OBJECT (timeline,
1871             "Transition %s could not be wrapped into an auto transition"
1872             " REMOVING it", GES_TIMELINE_ELEMENT_NAME (tmp->data));
1873
1874         ges_layer_remove_clip (layer, tmp->data);
1875       }
1876     }
1877   }
1878   g_list_free_full (clips, gst_object_unref);
1879 }
1880
1881 /* returns TRUE if selecting of tracks did not error */
1882 gboolean
1883 ges_timeline_add_clip (GESTimeline * timeline, GESClip * clip, GError ** error)
1884 {
1885   GESProject *project;
1886   gboolean ret;
1887
1888   ges_timeline_element_set_timeline (GES_TIMELINE_ELEMENT (clip), timeline);
1889
1890   /* We make sure not to be connected twice */
1891   g_signal_handlers_disconnect_by_func (clip, clip_track_element_added_cb,
1892       timeline);
1893   g_signal_handlers_disconnect_by_func (clip, clip_track_element_removed_cb,
1894       timeline);
1895
1896   /* And we connect to the object */
1897   g_signal_connect (clip, "child-added",
1898       G_CALLBACK (clip_track_element_added_cb), timeline);
1899   g_signal_connect (clip, "child-removed",
1900       G_CALLBACK (clip_track_element_removed_cb), timeline);
1901
1902   GST_DEBUG ("Making sure that the asset is in our project");
1903   project =
1904       GES_PROJECT (ges_extractable_get_asset (GES_EXTRACTABLE (timeline)));
1905   ges_project_add_asset (project,
1906       ges_extractable_get_asset (GES_EXTRACTABLE (clip)));
1907
1908   if (ges_clip_is_moving_from_layer (clip)) {
1909     GST_DEBUG ("Clip %p moving from one layer to another, not creating "
1910         "TrackElement", clip);
1911     /* timeline-tree handles creation of auto-transitions */
1912     ret = TRUE;
1913   } else {
1914     ret = add_object_to_tracks (timeline, clip, NULL, error);
1915   }
1916
1917   GST_DEBUG ("Done");
1918
1919   return ret;
1920 }
1921
1922 static void
1923 layer_priority_changed_cb (GESLayer * layer,
1924     GParamSpec * arg G_GNUC_UNUSED, GESTimeline * timeline)
1925 {
1926   if (timeline->priv->resyncing_layers)
1927     return;
1928
1929   timeline->layers = g_list_sort (timeline->layers, (GCompareFunc)
1930       sort_layers);
1931 }
1932
1933 void
1934 ges_timeline_remove_clip (GESTimeline * timeline, GESClip * clip)
1935 {
1936   GList *tmp;
1937
1938   if (ges_clip_is_moving_from_layer (clip)) {
1939     GST_DEBUG ("Clip %p is moving from a layer to another, not doing"
1940         " anything on it", clip);
1941     return;
1942   }
1943
1944   GST_DEBUG_OBJECT (timeline, "Clip %" GES_FORMAT " removed from layer",
1945       GES_ARGS (clip));
1946
1947   LOCK_DYN (timeline);
1948   for (tmp = timeline->tracks; tmp; tmp = tmp->next)
1949     ges_clip_empty_from_track (clip, tmp->data);
1950   UNLOCK_DYN (timeline);
1951
1952   g_signal_handlers_disconnect_by_func (clip, clip_track_element_added_cb,
1953       timeline);
1954   g_signal_handlers_disconnect_by_func (clip, clip_track_element_removed_cb,
1955       timeline);
1956
1957   ges_timeline_element_set_timeline (GES_TIMELINE_ELEMENT (clip), NULL);
1958
1959   GST_DEBUG ("Done");
1960 }
1961
1962 static gboolean
1963 update_stream_object (TrackPrivate * tr_priv)
1964 {
1965   gboolean res = FALSE;
1966   GstStreamType type = GST_STREAM_TYPE_UNKNOWN;
1967   gchar *stream_id;
1968
1969   g_object_get (tr_priv->track, "id", &stream_id, NULL);
1970   if (tr_priv->track->type == GES_TRACK_TYPE_VIDEO)
1971     type = GST_STREAM_TYPE_VIDEO;
1972   if (tr_priv->track->type == GES_TRACK_TYPE_AUDIO)
1973     type = GST_STREAM_TYPE_AUDIO;
1974
1975   if (!tr_priv->stream ||
1976       g_strcmp0 (stream_id, gst_stream_get_stream_id (tr_priv->stream))) {
1977     res = TRUE;
1978     gst_object_replace ((GstObject **) & tr_priv->stream,
1979         (GstObject *) gst_stream_new (stream_id,
1980             (GstCaps *) ges_track_get_caps (tr_priv->track),
1981             type, GST_STREAM_FLAG_NONE)
1982         );
1983   }
1984
1985   g_free (stream_id);
1986
1987   return res;
1988 }
1989
1990 static GstPadProbeReturn
1991 _pad_probe_cb (GstPad * mixer_pad, GstPadProbeInfo * info,
1992     TrackPrivate * tr_priv)
1993 {
1994   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
1995   GESTimeline *timeline = tr_priv->timeline;
1996
1997   if (GST_EVENT_TYPE (event) == GST_EVENT_STREAM_START) {
1998     LOCK_DYN (timeline);
1999     if (timeline->priv->stream_start_group_id == -1) {
2000       if (!gst_event_parse_group_id (event,
2001               &timeline->priv->stream_start_group_id))
2002         timeline->priv->stream_start_group_id = gst_util_group_id_next ();
2003     }
2004
2005     gst_event_unref (event);
2006     event = info->data =
2007         gst_event_new_stream_start (gst_stream_get_stream_id (tr_priv->stream));
2008     gst_event_set_stream (event, tr_priv->stream);
2009     gst_event_set_group_id (event, timeline->priv->stream_start_group_id);
2010     UNLOCK_DYN (timeline);
2011
2012     return GST_PAD_PROBE_REMOVE;
2013   }
2014
2015   return GST_PAD_PROBE_OK;
2016 }
2017
2018 static void
2019 _ghost_track_srcpad (TrackPrivate * tr_priv)
2020 {
2021   GstPad *pad;
2022   gchar *padname;
2023   gboolean no_more;
2024   GList *tmp;
2025   GESTrack *track = tr_priv->track;
2026
2027   pad = gst_element_get_static_pad (GST_ELEMENT (track), "src");
2028
2029   GST_DEBUG ("track:%p, pad:%s:%s", track, GST_DEBUG_PAD_NAME (pad));
2030
2031   /* Remember the pad */
2032   LOCK_DYN (tr_priv->timeline);
2033   GST_OBJECT_LOCK (track);
2034   tr_priv->pad = pad;
2035
2036   no_more = TRUE;
2037   for (tmp = tr_priv->timeline->priv->priv_tracks; tmp; tmp = g_list_next (tmp)) {
2038     TrackPrivate *tr_priv = (TrackPrivate *) tmp->data;
2039
2040     if (!tr_priv->pad) {
2041       GST_LOG ("Found track without pad %p", tr_priv->track);
2042       no_more = FALSE;
2043     }
2044   }
2045   GST_OBJECT_UNLOCK (track);
2046
2047   /* ghost it ! */
2048   GST_DEBUG ("Ghosting pad and adding it to ourself");
2049   padname = g_strdup_printf ("track_%p_src", track);
2050   tr_priv->ghostpad = gst_ghost_pad_new (padname, pad);
2051   g_free (padname);
2052   gst_pad_set_active (tr_priv->ghostpad, TRUE);
2053   gst_element_add_pad (GST_ELEMENT (tr_priv->timeline), tr_priv->ghostpad);
2054
2055   if (no_more) {
2056     GST_DEBUG ("Signaling no-more-pads");
2057     gst_element_no_more_pads (GST_ELEMENT (tr_priv->timeline));
2058   }
2059
2060   tr_priv->probe_id = gst_pad_add_probe (pad,
2061       GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
2062       (GstPadProbeCallback) _pad_probe_cb, tr_priv, NULL);
2063
2064   UNLOCK_DYN (tr_priv->timeline);
2065 }
2066
2067 gboolean
2068 timeline_add_element (GESTimeline * timeline, GESTimelineElement * element)
2069 {
2070   /* FIXME: handle NULL element->name */
2071   GESTimelineElement *same_name =
2072       g_hash_table_lookup (timeline->priv->all_elements,
2073       element->name);
2074
2075   GST_DEBUG_OBJECT (timeline, "Adding element: %s", element->name);
2076   if (same_name) {
2077     GST_ERROR_OBJECT (timeline, "%s Already in the timeline %" GST_PTR_FORMAT,
2078         element->name, same_name);
2079     return FALSE;
2080   }
2081
2082   /* FIXME: why is the hash table using the name of the element, rather than
2083    * the pointer to the element itself as the key? This makes it awkward
2084    * to change the name of an element after it has been added. See
2085    * ges_timeline_element_set_name. It means we have to remove and then
2086    * re-add the element. */
2087   g_hash_table_insert (timeline->priv->all_elements,
2088       ges_timeline_element_get_name (element), gst_object_ref (element));
2089
2090   timeline_tree_track_element (timeline->priv->tree, element);
2091   if (GES_IS_SOURCE (element)) {
2092     ges_source_set_rendering_smartly (GES_SOURCE (element),
2093         timeline->priv->rendering_smartly);
2094   }
2095
2096   return TRUE;
2097 }
2098
2099 gboolean
2100 timeline_remove_element (GESTimeline * timeline, GESTimelineElement * element)
2101 {
2102   if (g_hash_table_remove (timeline->priv->all_elements, element->name)) {
2103     timeline_tree_stop_tracking_element (timeline->priv->tree, element);
2104
2105     return TRUE;
2106   }
2107
2108   return FALSE;
2109 }
2110
2111 void
2112 timeline_fill_gaps (GESTimeline * timeline)
2113 {
2114   GList *tmp;
2115
2116   LOCK_DYN (timeline);
2117   for (tmp = timeline->tracks; tmp; tmp = tmp->next) {
2118     track_resort_and_fill_gaps (tmp->data);
2119   }
2120   UNLOCK_DYN (timeline);
2121 }
2122
2123 GNode *
2124 timeline_get_tree (GESTimeline * timeline)
2125 {
2126   return timeline->priv->tree;
2127 }
2128
2129 void
2130 ges_timeline_set_smart_rendering (GESTimeline * timeline,
2131     gboolean rendering_smartly)
2132 {
2133   if (rendering_smartly) {
2134     GList *tmp;
2135
2136     for (tmp = timeline->tracks; tmp; tmp = tmp->next) {
2137       if (ges_track_get_mixing (tmp->data)) {
2138         GST_INFO_OBJECT (timeline, "Smart rendering will not"
2139             " work as track %" GST_PTR_FORMAT " is doing mixing", tmp->data);
2140       } else {
2141         ges_track_set_smart_rendering (tmp->data, rendering_smartly);
2142       }
2143     }
2144   }
2145   timeline_tree_set_smart_rendering (timeline->priv->tree, rendering_smartly);
2146   timeline->priv->rendering_smartly = rendering_smartly;
2147 }
2148
2149 gboolean
2150 ges_timeline_get_smart_rendering (GESTimeline * timeline)
2151 {
2152   return timeline->priv->rendering_smartly;
2153 }
2154
2155 /**** API *****/
2156 /**
2157  * ges_timeline_new:
2158  *
2159  * Creates a new empty timeline.
2160  *
2161  * Returns: (transfer floating): The new timeline.
2162  */
2163
2164 GESTimeline *
2165 ges_timeline_new (void)
2166 {
2167   GESProject *project = ges_project_new (NULL);
2168   GESExtractable *timeline = g_object_new (GES_TYPE_TIMELINE, NULL);
2169
2170   ges_extractable_set_asset (timeline, GES_ASSET (project));
2171   gst_object_unref (project);
2172
2173   return GES_TIMELINE (timeline);
2174 }
2175
2176 /**
2177  * ges_timeline_new_from_uri:
2178  * @uri: The URI to load from
2179  * @error: (out) (allow-none): An error to be set if loading fails, or
2180  * %NULL to ignore
2181  *
2182  * Creates a timeline from the given URI.
2183  *
2184  * Returns: (transfer floating) (nullable): A new timeline if the uri was loaded
2185  * successfully, or %NULL if the uri could not be loaded.
2186  */
2187 GESTimeline *
2188 ges_timeline_new_from_uri (const gchar * uri, GError ** error)
2189 {
2190   GESTimeline *ret;
2191   GESProject *project = ges_project_new (uri);
2192
2193   ret = GES_TIMELINE (ges_asset_extract (GES_ASSET (project), error));
2194   gst_object_unref (project);
2195
2196   return ret;
2197 }
2198
2199 /**
2200  * ges_timeline_load_from_uri:
2201  * @timeline: An empty #GESTimeline into which to load the formatter
2202  * @uri: The URI to load from
2203  * @error: (out) (allow-none): An error to be set if loading fails, or
2204  * %NULL to ignore
2205  *
2206  * Loads the contents of URI into the timeline.
2207  *
2208  * Returns: %TRUE if the timeline was loaded successfully from @uri.
2209  */
2210 gboolean
2211 ges_timeline_load_from_uri (GESTimeline * timeline, const gchar * uri,
2212     GError ** error)
2213 {
2214   GESProject *project;
2215   gboolean ret = FALSE;
2216
2217   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2218   g_return_val_if_fail ((ges_extractable_get_asset (GES_EXTRACTABLE
2219               (timeline)) == NULL), FALSE);
2220
2221   project = ges_project_new (uri);
2222   ret = ges_project_load (project, timeline, error);
2223   gst_object_unref (project);
2224
2225   return ret;
2226 }
2227
2228 /**
2229  * ges_timeline_save_to_uri:
2230  * @timeline: The #GESTimeline
2231  * @uri: The location to save to
2232  * @formatter_asset: (allow-none): The formatter asset to use, or %NULL
2233  * @overwrite: %TRUE to overwrite file if it exists
2234  * @error: (out) (allow-none): An error to be set if saving fails, or
2235  * %NULL to ignore
2236  *
2237  * Saves the timeline to the given location. If @formatter_asset is %NULL,
2238  * the method will attempt to save in the same format the timeline was
2239  * loaded from, before defaulting to the formatter with highest rank.
2240  *
2241  * Returns: %TRUE if @timeline was successfully saved to @uri.
2242  */
2243 gboolean
2244 ges_timeline_save_to_uri (GESTimeline * timeline, const gchar * uri,
2245     GESAsset * formatter_asset, gboolean overwrite, GError ** error)
2246 {
2247   GESProject *project;
2248
2249   gboolean ret, created_proj = FALSE;
2250
2251   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2252   project =
2253       GES_PROJECT (ges_extractable_get_asset (GES_EXTRACTABLE (timeline)));
2254
2255   if (project == NULL) {
2256     project = ges_project_new (NULL);
2257     created_proj = TRUE;
2258   }
2259
2260   ret = ges_project_save (project, timeline, uri, formatter_asset, overwrite,
2261       error);
2262
2263   if (created_proj)
2264     gst_object_unref (project);
2265
2266   return ret;
2267 }
2268
2269 /**
2270  * ges_timeline_get_groups:
2271  * @timeline: The #GESTimeline
2272  *
2273  * Get the list of #GESGroup-s present in the timeline.
2274  *
2275  * Returns: (transfer none) (element-type GESGroup): The list of
2276  * groups that contain clips present in @timeline's layers.
2277  * Must not be changed.
2278  */
2279 GList *
2280 ges_timeline_get_groups (GESTimeline * timeline)
2281 {
2282   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
2283   CHECK_THREAD (timeline);
2284
2285   return timeline->priv->groups;
2286 }
2287
2288 /**
2289  * ges_timeline_append_layer:
2290  * @timeline: The #GESTimeline
2291  *
2292  * Append a newly created layer to the timeline. The layer will
2293  * be added at the lowest #GESLayer:priority (numerically, the highest).
2294  *
2295  * Returns: (transfer none): The newly created layer.
2296  */
2297 GESLayer *
2298 ges_timeline_append_layer (GESTimeline * timeline)
2299 {
2300   GList *tmp;
2301   guint32 priority;
2302   GESLayer *layer;
2303
2304   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
2305   CHECK_THREAD (timeline);
2306
2307   layer = ges_layer_new ();
2308
2309   priority = 0;
2310   for (tmp = timeline->layers; tmp; tmp = tmp->next)
2311     priority = MAX (priority, ges_layer_get_priority (tmp->data) + 1);
2312
2313   ges_layer_set_priority (layer, priority);
2314
2315   ges_timeline_add_layer (timeline, layer);
2316
2317   return layer;
2318 }
2319
2320 /**
2321  * ges_timeline_add_layer:
2322  * @timeline: The #GESTimeline
2323  * @layer: (transfer floating): The layer to add
2324  *
2325  * Add a layer to the timeline.
2326  *
2327  * If the layer contains #GESClip-s, then this may trigger the creation of
2328  * their core track element children for the timeline's tracks, and the
2329  * placement of the clip's children in the tracks of the timeline using
2330  * #GESTimeline::select-tracks-for-object. Some errors may occur if this
2331  * would break one of the configuration rules of the timeline in one of
2332  * its tracks. In such cases, some track elements would fail to be added
2333  * to their tracks, but this method would still return %TRUE. As such, it
2334  * is advised that you only add clips to layers that already part of a
2335  * timeline. In such situations, ges_layer_add_clip() is able to fail if
2336  * adding the clip would cause such an error.
2337  *
2338  * Deprecated: 1.18: This method requires you to ensure the layer's
2339  * #GESLayer:priority will be unique to the timeline. Use
2340  * ges_timeline_append_layer() and ges_timeline_move_layer() instead.
2341  *
2342  * Returns: %TRUE if @layer was properly added.
2343  */
2344 gboolean
2345 ges_timeline_add_layer (GESTimeline * timeline, GESLayer * layer)
2346 {
2347   gboolean auto_transition;
2348   GList *objects, *tmp;
2349
2350   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2351   g_return_val_if_fail (GES_IS_LAYER (layer), FALSE);
2352   CHECK_THREAD (timeline);
2353
2354   GST_DEBUG ("timeline:%p, layer:%p", timeline, layer);
2355
2356   /* We can only add a layer that doesn't already belong to another timeline */
2357   if (G_UNLIKELY (layer->timeline)) {
2358     GST_WARNING ("Layer belongs to another timeline, can't add it");
2359     gst_object_ref_sink (layer);
2360     gst_object_unref (layer);
2361     return FALSE;
2362   }
2363
2364   /* Add to the list of layers, make sure we don't already control it */
2365   if (G_UNLIKELY (g_list_find (timeline->layers, (gconstpointer) layer))) {
2366     GST_WARNING ("Layer is already controlled by this timeline");
2367     gst_object_ref_sink (layer);
2368     gst_object_unref (layer);
2369     return FALSE;
2370   }
2371
2372   /* FIXME: ensure the layer->priority does not conflict with an existing
2373    * layer in the timeline. Currently can add several layers with equal
2374    * layer priorities */
2375
2376   auto_transition = ges_layer_get_auto_transition (layer);
2377
2378   /* If the user doesn't explicitely set layer auto_transition, then set our */
2379   if (!auto_transition) {
2380     auto_transition = ges_timeline_get_auto_transition (timeline);
2381     ges_layer_set_auto_transition (layer, auto_transition);
2382   }
2383
2384   gst_object_ref_sink (layer);
2385   timeline->layers = g_list_insert_sorted (timeline->layers, layer,
2386       (GCompareFunc) sort_layers);
2387
2388   /* Inform the layer that it belongs to a new timeline */
2389   ges_layer_set_timeline (layer, timeline);
2390
2391   /* Connect to 'clip-added'/'clip-removed' signal from the new layer */
2392   g_signal_connect (layer, "notify::priority",
2393       G_CALLBACK (layer_priority_changed_cb), timeline);
2394   g_signal_connect (layer, "notify::auto-transition",
2395       G_CALLBACK (layer_auto_transition_changed_cb), timeline);
2396   g_signal_connect_after (layer, "active-changed",
2397       G_CALLBACK (layer_active_changed_cb), timeline);
2398
2399   GST_DEBUG ("Done adding layer, emitting 'layer-added' signal");
2400   g_signal_emit (timeline, ges_timeline_signals[LAYER_ADDED], 0, layer);
2401
2402   /* add any existing clips to the timeline */
2403   objects = ges_layer_get_clips (layer);
2404   for (tmp = objects; tmp; tmp = tmp->next)
2405     ges_timeline_add_clip (timeline, tmp->data, NULL);
2406   g_list_free_full (objects, gst_object_unref);
2407
2408   return TRUE;
2409 }
2410
2411 /**
2412  * ges_timeline_remove_layer:
2413  * @timeline: The #GESTimeline
2414  * @layer: The layer to remove
2415  *
2416  * Removes a layer from the timeline.
2417  *
2418  * Returns: %TRUE if @layer was properly removed.
2419  */
2420
2421 gboolean
2422 ges_timeline_remove_layer (GESTimeline * timeline, GESLayer * layer)
2423 {
2424   GList *layer_objects, *tmp;
2425
2426   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2427   g_return_val_if_fail (GES_IS_LAYER (layer), FALSE);
2428
2429   if (!timeline->priv->disposed)
2430     CHECK_THREAD (timeline);
2431
2432   GST_DEBUG ("timeline:%p, layer:%p", timeline, layer);
2433
2434   if (G_UNLIKELY (!g_list_find (timeline->layers, layer))) {
2435     GST_WARNING ("Layer doesn't belong to this timeline");
2436     return FALSE;
2437   }
2438
2439   /* remove objects from any private data structures */
2440
2441   layer_objects = ges_layer_get_clips (layer);
2442   for (tmp = layer_objects; tmp; tmp = tmp->next)
2443     ges_timeline_remove_clip (timeline, tmp->data);
2444   g_list_free_full (layer_objects, gst_object_unref);
2445
2446   /* Disconnect signals */
2447   GST_DEBUG ("Disconnecting signal callbacks");
2448   g_signal_handlers_disconnect_by_func (layer, layer_priority_changed_cb,
2449       timeline);
2450   g_signal_handlers_disconnect_by_func (layer,
2451       layer_auto_transition_changed_cb, timeline);
2452   g_signal_handlers_disconnect_by_func (layer, layer_active_changed_cb,
2453       timeline);
2454
2455   timeline->layers = g_list_remove (timeline->layers, layer);
2456   ges_layer_set_timeline (layer, NULL);
2457   /* FIXME: we should resync the layer priorities */
2458
2459   g_signal_emit (timeline, ges_timeline_signals[LAYER_REMOVED], 0, layer);
2460
2461   gst_object_unref (layer);
2462
2463   return TRUE;
2464 }
2465
2466 /**
2467  * ges_timeline_add_track:
2468  * @timeline: The #GESTimeline
2469  * @track: (transfer full): The track to add
2470  *
2471  * Add a track to the timeline.
2472  *
2473  * If the timeline already contains clips, then this may trigger the
2474  * creation of their core track element children for the track, and the
2475  * placement of the clip's children in the track of the timeline using
2476  * #GESTimeline::select-tracks-for-object. Some errors may occur if this
2477  * would break one of the configuration rules for the timeline in the
2478  * track. In such cases, some track elements would fail to be added to the
2479  * track, but this method would still return %TRUE. As such, it is advised
2480  * that you avoid adding tracks to timelines that already contain clips.
2481  *
2482  * Returns: %TRUE if @track was properly added.
2483  */
2484
2485 /* FIXME: create track elements for clips which have already been
2486  * added to existing layers.
2487  */
2488
2489 gboolean
2490 ges_timeline_add_track (GESTimeline * timeline, GESTrack * track)
2491 {
2492   TrackPrivate *tr_priv;
2493   GList *tmp;
2494
2495   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2496   g_return_val_if_fail (GES_IS_TRACK (track), FALSE);
2497   CHECK_THREAD (timeline);
2498
2499   GST_DEBUG ("timeline:%p, track:%p", timeline, track);
2500
2501   /* make sure we don't already control it */
2502   LOCK_DYN (timeline);
2503   if (G_UNLIKELY (g_list_find (timeline->tracks, (gconstpointer) track))) {
2504     UNLOCK_DYN (timeline);
2505     GST_WARNING ("Track is already controlled by this timeline");
2506     return FALSE;
2507   }
2508
2509   /* Add the track to ourself (as a GstBin)
2510    * Reference is stolen ! */
2511   if (G_UNLIKELY (!gst_bin_add (GST_BIN (timeline), GST_ELEMENT (track)))) {
2512     UNLOCK_DYN (timeline);
2513     GST_WARNING ("Couldn't add track to ourself (GST)");
2514     return FALSE;
2515   }
2516
2517   tr_priv = g_new0 (TrackPrivate, 1);
2518   tr_priv->timeline = timeline;
2519   tr_priv->track = track;
2520   tr_priv->track_element_added_sigid = g_signal_connect (track,
2521       "track-element-added", G_CALLBACK (track_element_added_cb), timeline);
2522
2523   update_stream_object (tr_priv);
2524   gst_stream_collection_add_stream (timeline->priv->stream_collection,
2525       gst_object_ref (tr_priv->stream));
2526
2527   /* Add the track to the list of tracks we track */
2528   timeline->priv->priv_tracks = g_list_append (timeline->priv->priv_tracks,
2529       tr_priv);
2530   timeline->tracks = g_list_append (timeline->tracks, track);
2531
2532   /* Inform the track that it's currently being used by ourself */
2533   ges_track_set_timeline (track, timeline);
2534
2535   GST_DEBUG ("Done adding track, emitting 'track-added' signal");
2536
2537   _ghost_track_srcpad (tr_priv);
2538   UNLOCK_DYN (timeline);
2539
2540   /* emit 'track-added' */
2541   g_signal_emit (timeline, ges_timeline_signals[TRACK_ADDED], 0, track);
2542
2543   /* ensure that each existing clip has the opportunity to create a
2544    * track element for this track*/
2545
2546   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
2547     GList *objects, *obj;
2548     objects = ges_layer_get_clips (tmp->data);
2549
2550     for (obj = objects; obj; obj = obj->next)
2551       add_object_to_tracks (timeline, obj->data, track, NULL);
2552
2553     g_list_free_full (objects, gst_object_unref);
2554   }
2555
2556   /* FIXME Check if we should rollback if we can't sync state */
2557   gst_element_sync_state_with_parent (GST_ELEMENT (track));
2558   g_object_set (track, "message-forward", TRUE, NULL);
2559
2560   return TRUE;
2561 }
2562
2563 /**
2564  * ges_timeline_remove_track:
2565  * @timeline: The #GESTimeline
2566  * @track: The track to remove
2567  *
2568  * Remove a track from the timeline.
2569  *
2570  * Returns: %TRUE if @track was properly removed.
2571  */
2572
2573 /* FIXME: release any track elements associated with this layer. currenly this
2574  * will not happen if you remove the track before removing *all*
2575  * clips which have a track element in this track.
2576  */
2577
2578 gboolean
2579 ges_timeline_remove_track (GESTimeline * timeline, GESTrack * track)
2580 {
2581   GList *tmp;
2582   TrackPrivate *tr_priv;
2583   GESTimelinePrivate *priv;
2584
2585   g_return_val_if_fail (GES_IS_TRACK (track), FALSE);
2586   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2587
2588   GST_DEBUG ("timeline:%p, track:%p", timeline, track);
2589
2590   priv = timeline->priv;
2591   LOCK_DYN (timeline);
2592   if (G_UNLIKELY (!(tmp = g_list_find_custom (priv->priv_tracks,
2593                   track, (GCompareFunc) custom_find_track)))) {
2594     GST_WARNING ("Track doesn't belong to this timeline");
2595     UNLOCK_DYN (timeline);
2596     return FALSE;
2597   }
2598
2599   tr_priv = tmp->data;
2600   gst_object_unref (tr_priv->pad);
2601   priv->priv_tracks = g_list_remove (priv->priv_tracks, tr_priv);
2602   UNLOCK_DYN (timeline);
2603
2604   /* empty track of all elements that belong to the timeline's clips */
2605   /* elements with no parent can stay in the track, but their timeline
2606    * will be set to NULL when the track's timeline is set to NULL */
2607
2608   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
2609     GList *clips, *clip;
2610     clips = ges_layer_get_clips (tmp->data);
2611
2612     for (clip = clips; clip; clip = clip->next)
2613       ges_clip_empty_from_track (clip->data, track);
2614
2615     g_list_free_full (clips, gst_object_unref);
2616   }
2617
2618   timeline->tracks = g_list_remove (timeline->tracks, track);
2619   ges_track_set_timeline (track, NULL);
2620
2621   /* Remove ghost pad */
2622   if (tr_priv->ghostpad) {
2623     GST_DEBUG ("Removing ghostpad");
2624     gst_pad_set_active (tr_priv->ghostpad, FALSE);
2625     gst_ghost_pad_set_target ((GstGhostPad *) tr_priv->ghostpad, NULL);
2626     gst_element_remove_pad (GST_ELEMENT (timeline), tr_priv->ghostpad);
2627   }
2628
2629   /* Signal track removal to all layers/objects */
2630   g_signal_emit (timeline, ges_timeline_signals[TRACK_REMOVED], 0, track);
2631
2632   /* remove track from our bin */
2633   gst_object_ref (track);
2634   if (G_UNLIKELY (!gst_bin_remove (GST_BIN (timeline), GST_ELEMENT (track)))) {
2635     GST_WARNING ("Couldn't remove track to ourself (GST)");
2636     gst_object_unref (track);
2637     return FALSE;
2638   }
2639
2640   g_signal_handler_disconnect (track, tr_priv->track_element_added_sigid);
2641
2642   /* set track state to NULL */
2643   gst_element_set_state (GST_ELEMENT (track), GST_STATE_NULL);
2644
2645   gst_object_unref (track);
2646
2647   g_free (tr_priv);
2648
2649   return TRUE;
2650 }
2651
2652 /**
2653  * ges_timeline_get_track_for_pad:
2654  * @timeline: The #GESTimeline
2655  * @pad: A pad
2656  *
2657  * Search for the #GESTrack corresponding to the given timeline's pad.
2658  *
2659  * Returns: (transfer none) (nullable): The track corresponding to @pad,
2660  * or %NULL if there is an error.
2661  */
2662
2663 GESTrack *
2664 ges_timeline_get_track_for_pad (GESTimeline * timeline, GstPad * pad)
2665 {
2666   GList *tmp;
2667
2668   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
2669
2670   LOCK_DYN (timeline);
2671   for (tmp = timeline->priv->priv_tracks; tmp; tmp = g_list_next (tmp)) {
2672     TrackPrivate *tr_priv = (TrackPrivate *) tmp->data;
2673     if (pad == tr_priv->ghostpad) {
2674       UNLOCK_DYN (timeline);
2675       return tr_priv->track;
2676     }
2677   }
2678   UNLOCK_DYN (timeline);
2679
2680   return NULL;
2681 }
2682
2683 /**
2684  * ges_timeline_get_pad_for_track:
2685  * @timeline: The #GESTimeline
2686  * @track: A track
2687  *
2688  * Search for the #GstPad corresponding to the given timeline's track.
2689  * You can link to this pad to receive the output data of the given track.
2690  *
2691  * Returns: (transfer none) (nullable): The pad corresponding to @track,
2692  * or %NULL if there is an error.
2693  */
2694
2695 GstPad *
2696 ges_timeline_get_pad_for_track (GESTimeline * timeline, GESTrack * track)
2697 {
2698   GList *tmp;
2699
2700   LOCK_DYN (timeline);
2701   for (tmp = timeline->priv->priv_tracks; tmp; tmp = g_list_next (tmp)) {
2702     TrackPrivate *tr_priv = (TrackPrivate *) tmp->data;
2703
2704     if (track == tr_priv->track) {
2705       if (tr_priv->ghostpad)
2706         gst_object_ref (tr_priv->ghostpad);
2707
2708       UNLOCK_DYN (timeline);
2709       return tr_priv->ghostpad;
2710     }
2711   }
2712   UNLOCK_DYN (timeline);
2713
2714   return NULL;
2715 }
2716
2717 /**
2718  * ges_timeline_get_tracks:
2719  * @timeline: The #GESTimeline
2720  *
2721  * Get the list of #GESTrack-s used by the timeline.
2722  *
2723  * Returns: (transfer full) (element-type GESTrack): The list of tracks
2724  * used by @timeline.
2725  */
2726 GList *
2727 ges_timeline_get_tracks (GESTimeline * timeline)
2728 {
2729   GList *res = NULL;
2730   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
2731
2732   LOCK_DYN (timeline);
2733   res = g_list_copy_deep (timeline->tracks, (GCopyFunc) gst_object_ref, NULL);
2734   UNLOCK_DYN (timeline);
2735
2736   return res;
2737 }
2738
2739 /**
2740  * ges_timeline_get_layers:
2741  * @timeline: The #GESTimeline
2742  *
2743  * Get the list of #GESLayer-s present in the timeline.
2744  *
2745  * Returns: (transfer full) (element-type GESLayer): The list of
2746  * layers present in @timeline sorted by priority.
2747  */
2748 GList *
2749 ges_timeline_get_layers (GESTimeline * timeline)
2750 {
2751   GList *tmp, *res = NULL;
2752
2753   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
2754   CHECK_THREAD (timeline);
2755
2756   for (tmp = timeline->layers; tmp; tmp = g_list_next (tmp)) {
2757     res = g_list_insert_sorted (res, gst_object_ref (tmp->data),
2758         (GCompareFunc) sort_layers);
2759   }
2760
2761   return res;
2762 }
2763
2764 static void
2765 track_commited_cb (GESTrack * track, GESTimeline * timeline)
2766 {
2767   gboolean emit_commited = FALSE;
2768   GST_OBJECT_LOCK (timeline);
2769   timeline->priv->expected_commited -= 1;
2770   if (timeline->priv->expected_commited == 0)
2771     emit_commited = TRUE;
2772   g_signal_handlers_disconnect_by_func (track, track_commited_cb, timeline);
2773   GST_OBJECT_UNLOCK (timeline);
2774
2775   if (emit_commited) {
2776     g_signal_emit (timeline, ges_timeline_signals[COMMITED], 0);
2777   }
2778 }
2779
2780 /* Must be called with the timeline's DYN_LOCK */
2781 static gboolean
2782 ges_timeline_commit_unlocked (GESTimeline * timeline)
2783 {
2784   GList *tmp;
2785   gboolean res = TRUE;
2786
2787   GST_DEBUG_OBJECT (timeline, "commiting changes");
2788
2789   timeline_tree_create_transitions (timeline->priv->tree,
2790       ges_timeline_find_auto_transition);
2791   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
2792     GESLayer *layer = tmp->data;
2793
2794     /* Ensure clip priorities are correct after an edit */
2795     ges_layer_resync_priorities (layer);
2796   }
2797
2798   timeline->priv->expected_commited =
2799       g_list_length (timeline->priv->priv_tracks);
2800
2801   if (timeline->priv->expected_commited == 0) {
2802     g_signal_emit (timeline, ges_timeline_signals[COMMITED], 0);
2803   } else {
2804     GstStreamCollection *collection = gst_stream_collection_new (NULL);
2805
2806     LOCK_DYN (timeline);
2807     for (tmp = timeline->tracks; tmp; tmp = tmp->next) {
2808       TrackPrivate *tr_priv =
2809           g_list_find_custom (timeline->priv->priv_tracks, tmp->data,
2810           (GCompareFunc) custom_find_track)->data;
2811
2812       update_stream_object (tr_priv);
2813       gst_stream_collection_add_stream (collection,
2814           gst_object_ref (tr_priv->stream));
2815       g_signal_connect (tmp->data, "commited", G_CALLBACK (track_commited_cb),
2816           timeline);
2817       if (!ges_track_commit (GES_TRACK (tmp->data)))
2818         res = FALSE;
2819     }
2820
2821     gst_object_unref (timeline->priv->stream_collection);
2822     timeline->priv->stream_collection = collection;
2823     UNLOCK_DYN (timeline);
2824   }
2825
2826   return res;
2827 }
2828
2829 /**
2830  * ges_timeline_commit:
2831  * @timeline: A #GESTimeline
2832  *
2833  * Commit all the pending changes of the clips contained in the
2834  * timeline.
2835  *
2836  * When changes happen in a timeline, they are not immediately executed
2837  * internally, in a way that effects the output data of the timeline. You
2838  * should call this method when you are done with a set of changes and you
2839  * want them to be executed.
2840  *
2841  * Any pending changes will be executed in the backend. The
2842  * #GESTimeline::commited signal will be emitted once this has completed.
2843  * You should not try to change the state of the timeline, seek it or add
2844  * tracks to it before receiving this signal. You can use
2845  * ges_timeline_commit_sync() if you do not want to perform other tasks in
2846  * the mean time.
2847  *
2848  * Note that all the pending changes will automatically be executed when
2849  * the timeline goes from #GST_STATE_READY to #GST_STATE_PAUSED, which is
2850  * usually triggered by a corresponding state changes in a containing
2851  * #GESPipeline.
2852  *
2853  * Returns: %TRUE if pending changes were committed, or %FALSE if nothing
2854  * needed to be committed.
2855  */
2856 gboolean
2857 ges_timeline_commit (GESTimeline * timeline)
2858 {
2859   gboolean ret;
2860   GstStreamCollection *pcollection = timeline->priv->stream_collection;
2861
2862   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2863
2864   LOCK_DYN (timeline);
2865   ret = ges_timeline_commit_unlocked (timeline);
2866   UNLOCK_DYN (timeline);
2867
2868   if (pcollection != timeline->priv->stream_collection) {
2869     gst_element_post_message ((GstElement *) timeline,
2870         gst_message_new_stream_collection ((GstObject *) timeline,
2871             timeline->priv->stream_collection));
2872   }
2873
2874   ges_timeline_emit_snapping (timeline, NULL, NULL, GST_CLOCK_TIME_NONE);
2875   return ret;
2876 }
2877
2878 static void
2879 commited_cb (GESTimeline * timeline)
2880 {
2881   g_mutex_lock (&timeline->priv->commited_lock);
2882   g_cond_signal (&timeline->priv->commited_cond);
2883   g_mutex_unlock (&timeline->priv->commited_lock);
2884 }
2885
2886 /**
2887  * ges_timeline_commit_sync:
2888  * @timeline: A #GESTimeline
2889  *
2890  * Commit all the pending changes of the clips contained in the
2891  * timeline and wait for the changes to complete.
2892  *
2893  * See ges_timeline_commit().
2894  *
2895  * Returns: %TRUE if pending changes were committed, or %FALSE if nothing
2896  * needed to be committed.
2897  */
2898 gboolean
2899 ges_timeline_commit_sync (GESTimeline * timeline)
2900 {
2901   gboolean ret;
2902   gboolean wait_for_signal;
2903
2904   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2905
2906   /* Let's make sure our state is stable */
2907   gst_element_get_state (GST_ELEMENT (timeline), NULL, NULL,
2908       GST_CLOCK_TIME_NONE);
2909
2910   /* Let's make sure no track gets added between now and the actual commiting */
2911   LOCK_DYN (timeline);
2912   wait_for_signal = g_list_length (timeline->priv->priv_tracks) > 0
2913       && GST_STATE (timeline) >= GST_STATE_PAUSED;
2914
2915   if (!wait_for_signal) {
2916     ret = ges_timeline_commit_unlocked (timeline);
2917   } else {
2918     gulong handler_id =
2919         g_signal_connect (timeline, "commited", (GCallback) commited_cb, NULL);
2920
2921     g_mutex_lock (&timeline->priv->commited_lock);
2922
2923     ret = ges_timeline_commit_unlocked (timeline);
2924     g_cond_wait (&timeline->priv->commited_cond,
2925         &timeline->priv->commited_lock);
2926     g_mutex_unlock (&timeline->priv->commited_lock);
2927     g_signal_handler_disconnect (timeline, handler_id);
2928   }
2929
2930   UNLOCK_DYN (timeline);
2931
2932   return ret;
2933 }
2934
2935 /**
2936  * ges_timeline_get_duration:
2937  * @timeline: The #GESTimeline
2938  *
2939  * Get the current #GESTimeline:duration of the timeline
2940  *
2941  * Returns: The current duration of @timeline.
2942  */
2943 GstClockTime
2944 ges_timeline_get_duration (GESTimeline * timeline)
2945 {
2946   g_return_val_if_fail (GES_IS_TIMELINE (timeline), GST_CLOCK_TIME_NONE);
2947   CHECK_THREAD (timeline);
2948
2949   return timeline->priv->duration;
2950 }
2951
2952 /**
2953  * ges_timeline_get_auto_transition:
2954  * @timeline: The #GESTimeline
2955  *
2956  * Gets #GESTimeline:auto-transition for the timeline.
2957  *
2958  * Returns: The auto-transition of @self.
2959  */
2960 gboolean
2961 ges_timeline_get_auto_transition (GESTimeline * timeline)
2962 {
2963   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
2964   CHECK_THREAD (timeline);
2965
2966   return timeline->priv->auto_transition;
2967 }
2968
2969 /**
2970  * ges_timeline_set_auto_transition:
2971  * @timeline: The #GESTimeline
2972  * @auto_transition: Whether transitions should be automatically added
2973  * to @timeline's layers
2974  *
2975  * Sets #GESTimeline:auto-transition for the timeline. This will also set
2976  * the corresponding #GESLayer:auto-transition for all of the timeline's
2977  * layers to the same value. See ges_layer_set_auto_transition() if you
2978  * wish to set the layer's #GESLayer:auto-transition individually.
2979  */
2980 void
2981 ges_timeline_set_auto_transition (GESTimeline * timeline,
2982     gboolean auto_transition)
2983 {
2984   GList *layers;
2985   GESLayer *layer;
2986
2987   g_return_if_fail (GES_IS_TIMELINE (timeline));
2988   CHECK_THREAD (timeline);
2989
2990   timeline->priv->auto_transition = auto_transition;
2991   g_object_notify (G_OBJECT (timeline), "auto-transition");
2992
2993   layers = timeline->layers;
2994   for (; layers; layers = layers->next) {
2995     layer = layers->data;
2996     ges_layer_set_auto_transition (layer, auto_transition);
2997   }
2998 }
2999
3000 /**
3001  * ges_timeline_get_snapping_distance:
3002  * @timeline: The #GESTimeline
3003  *
3004  * Gets the #GESTimeline:snapping-distance for the timeline.
3005  *
3006  * Returns: The snapping distance (in nanoseconds) of @timeline.
3007  */
3008 GstClockTime
3009 ges_timeline_get_snapping_distance (GESTimeline * timeline)
3010 {
3011   g_return_val_if_fail (GES_IS_TIMELINE (timeline), GST_CLOCK_TIME_NONE);
3012   CHECK_THREAD (timeline);
3013
3014   return timeline->priv->snapping_distance;
3015
3016 }
3017
3018 /**
3019  * ges_timeline_set_snapping_distance:
3020  * @timeline: The #GESTimeline
3021  * @snapping_distance: The snapping distance to use (in nanoseconds)
3022  *
3023  * Sets #GESTimeline:snapping-distance for the timeline. This new value
3024  * will only effect future snappings and will not be used to snap the
3025  * current element positions within the timeline.
3026  */
3027 void
3028 ges_timeline_set_snapping_distance (GESTimeline * timeline,
3029     GstClockTime snapping_distance)
3030 {
3031   g_return_if_fail (GES_IS_TIMELINE (timeline));
3032   CHECK_THREAD (timeline);
3033
3034   timeline->priv->snapping_distance = snapping_distance;
3035 }
3036
3037 /**
3038  * ges_timeline_get_element:
3039  * @timeline: The #GESTimeline
3040  * @name: The name of the element to find
3041  *
3042  * Gets the element contained in the timeline with the given name.
3043  *
3044  * Returns: (transfer full) (nullable): The timeline element in @timeline
3045  * with the given @name, or %NULL if it was not found.
3046  */
3047 GESTimelineElement *
3048 ges_timeline_get_element (GESTimeline * timeline, const gchar * name)
3049 {
3050   GESTimelineElement *ret;
3051
3052   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
3053   CHECK_THREAD (timeline);
3054
3055   /* FIXME: handle NULL name */
3056   ret = g_hash_table_lookup (timeline->priv->all_elements, name);
3057
3058   if (ret)
3059     return gst_object_ref (ret);
3060
3061 #ifndef GST_DISABLE_GST_DEBUG
3062   {
3063     GList *element_names, *tmp;
3064     element_names = g_hash_table_get_keys (timeline->priv->all_elements);
3065
3066     GST_INFO_OBJECT (timeline, "Does not contain element %s", name);
3067
3068     for (tmp = element_names; tmp; tmp = tmp->next) {
3069       GST_DEBUG_OBJECT (timeline, "Containes: %s", (gchar *) tmp->data);
3070     }
3071     g_list_free (element_names);
3072   }
3073 #endif
3074
3075   return NULL;
3076 }
3077
3078 /**
3079  * ges_timeline_is_empty:
3080  * @timeline: The #GESTimeline
3081  *
3082  * Check whether the timeline is empty or not.
3083  *
3084  * Returns: %TRUE if @timeline is empty.
3085  */
3086 gboolean
3087 ges_timeline_is_empty (GESTimeline * timeline)
3088 {
3089   GHashTableIter iter;
3090   gpointer key, value;
3091
3092   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
3093   CHECK_THREAD (timeline);
3094
3095   if (g_hash_table_size (timeline->priv->all_elements) == 0)
3096     return TRUE;
3097
3098   g_hash_table_iter_init (&iter, timeline->priv->all_elements);
3099   while (g_hash_table_iter_next (&iter, &key, &value)) {
3100     if (GES_IS_SOURCE (value) &&
3101         ges_track_element_is_active (GES_TRACK_ELEMENT (value)))
3102       return FALSE;
3103   }
3104
3105   return TRUE;
3106 }
3107
3108 /**
3109  * ges_timeline_get_layer:
3110  * @timeline: The #GESTimeline to retrieve a layer from
3111  * @priority: The priority/index of the layer to find
3112  *
3113  * Retrieve the layer whose index in the timeline matches the given
3114  * priority.
3115  *
3116  * Returns: (transfer full) (nullable): The layer with the given
3117  * @priority, or %NULL if none was found.
3118  *
3119  * Since 1.6
3120  */
3121 GESLayer *
3122 ges_timeline_get_layer (GESTimeline * timeline, guint priority)
3123 {
3124   GList *tmp;
3125   GESLayer *layer = NULL;
3126
3127   g_return_val_if_fail (GES_IS_TIMELINE (timeline), NULL);
3128   CHECK_THREAD (timeline);
3129
3130   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
3131     GESLayer *tmp_layer = GES_LAYER (tmp->data);
3132     guint tmp_priority;
3133
3134     g_object_get (tmp_layer, "priority", &tmp_priority, NULL);
3135     if (tmp_priority == priority) {
3136       layer = gst_object_ref (tmp_layer);
3137       break;
3138     }
3139   }
3140
3141   return layer;
3142 }
3143
3144 gboolean
3145 ges_timeline_layer_priority_in_gap (GESTimeline * timeline, guint priority)
3146 {
3147   GList *tmp;
3148
3149   CHECK_THREAD (timeline);
3150
3151   for (tmp = timeline->layers; tmp; tmp = tmp->next) {
3152     GESLayer *layer = GES_LAYER (tmp->data);
3153     guint tmp_priority = ges_layer_get_priority (layer);
3154
3155     if (tmp_priority == priority)
3156       return FALSE;
3157     else if (tmp_priority > priority)
3158       return TRUE;
3159   }
3160
3161   return FALSE;
3162 }
3163
3164 /**
3165  * ges_timeline_paste_element:
3166  * @timeline: The #GESTimeline onto which @element should be pasted
3167  * @element: The element to paste
3168  * @position: The position in the timeline @element should be pasted to,
3169  * i.e. the #GESTimelineElement:start value for the pasted element.
3170  * @layer_priority: The layer into which the element should be pasted.
3171  * -1 means paste to the same layer from which @element has been copied from
3172  *
3173  * Paste an element inside the timeline. @element **must** be the return of
3174  * ges_timeline_element_copy() with `deep=TRUE`,
3175  * and it should not be changed before pasting. @element itself is not
3176  * placed in the timeline, instead a new element is created, alike to the
3177  * originally copied element. Note that the originally copied element must
3178  * also lie within @timeline, at both the point of copying and pasting.
3179  *
3180  * Pasting may fail if it would place the timeline in an unsupported
3181  * configuration.
3182  *
3183  * After calling this function @element should not be used. In particular,
3184  * @element can **not** be pasted again. Instead, you can copy the
3185  * returned element and paste that copy (although, this is only possible
3186  * if the paste was successful).
3187  *
3188  * See also ges_timeline_element_paste().
3189  *
3190  * Returns: (transfer full) (nullable): The newly created element, or
3191  * %NULL if pasting fails.
3192  */
3193 GESTimelineElement *
3194 ges_timeline_paste_element (GESTimeline * timeline,
3195     GESTimelineElement * element, GstClockTime position, gint layer_priority)
3196 {
3197   GESTimelineElement *res, *copied_from;
3198   GESTimelineElementClass *element_class;
3199
3200   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
3201   g_return_val_if_fail (GES_IS_TIMELINE_ELEMENT (element), FALSE);
3202   CHECK_THREAD (timeline);
3203
3204   element_class = GES_TIMELINE_ELEMENT_GET_CLASS (element);
3205   /* steal ownership of the copied element */
3206   copied_from = ges_timeline_element_get_copied_from (element);
3207
3208   if (!copied_from) {
3209     GST_ERROR_OBJECT (element, "Is not being 'deeply' copied!");
3210
3211     return NULL;
3212   }
3213
3214   if (!element_class->paste) {
3215     GST_ERROR_OBJECT (element, "No paste vmethod implemented");
3216     gst_object_unref (copied_from);
3217     return NULL;
3218   }
3219
3220   /*
3221    * Currently the API only supports pasting onto the same layer from which
3222    * the @element has been copied from, i.e., @layer_priority needs to be -1.
3223    */
3224   if (layer_priority != -1) {
3225     GST_WARNING_OBJECT (timeline,
3226         "Only -1 value for layer priority is supported");
3227     gst_object_unref (copied_from);
3228     return NULL;
3229   }
3230
3231   res = element_class->paste (element, copied_from, position);
3232
3233   gst_object_unref (copied_from);
3234
3235   return res ? g_object_ref_sink (res) : res;
3236 }
3237
3238 /**
3239  * ges_timeline_move_layer:
3240  * @timeline: A #GESTimeline
3241  * @layer: A layer within @timeline, whose priority should be changed
3242  * @new_layer_priority: The new index for @layer
3243  *
3244  * Moves a layer within the timeline to the index given by
3245  * @new_layer_priority.
3246  * An index of 0 corresponds to the layer with the highest priority in a
3247  * timeline. If @new_layer_priority is greater than the number of layers
3248  * present in the timeline, it will become the lowest priority layer.
3249  *
3250  * Since: 1.16
3251  */
3252 gboolean
3253 ges_timeline_move_layer (GESTimeline * timeline, GESLayer * layer,
3254     guint new_layer_priority)
3255 {
3256   gint current_priority;
3257
3258   g_return_val_if_fail (GES_IS_TIMELINE (timeline), FALSE);
3259   g_return_val_if_fail (GES_IS_LAYER (layer), FALSE);
3260   g_return_val_if_fail (ges_layer_get_timeline (layer) == timeline, FALSE);
3261   CHECK_THREAD (timeline);
3262
3263   current_priority = ges_layer_get_priority (layer);
3264
3265   if (new_layer_priority == current_priority) {
3266     GST_DEBUG_OBJECT (timeline,
3267         "Nothing to do for %" GST_PTR_FORMAT ", same priorities", layer);
3268
3269     return TRUE;
3270   }
3271
3272   timeline->layers = g_list_remove (timeline->layers, layer);
3273   timeline->layers = g_list_insert (timeline->layers, layer,
3274       (gint) new_layer_priority);
3275
3276   _resync_layers (timeline);
3277
3278   return TRUE;
3279 }
3280
3281 /**
3282  * ges_timeline_get_frame_time:
3283  * @self: The self on which to retrieve the timestamp for @frame_number
3284  * @frame_number: The frame number to get the corresponding timestamp of in the
3285  *                timeline coordinates
3286  *
3287  * This method allows you to convert a timeline output frame number into a
3288  * timeline #GstClockTime. For example, this time could be used to seek to a
3289  * particular frame in the timeline's output, or as the edit position for
3290  * an element within the timeline.
3291  *
3292  * Returns: The timestamp corresponding to @frame_number in the output of @self.
3293  *
3294  * Since: 1.18
3295  */
3296 GstClockTime
3297 ges_timeline_get_frame_time (GESTimeline * self, GESFrameNumber frame_number)
3298 {
3299   gint fps_n, fps_d;
3300
3301   g_return_val_if_fail (GES_IS_TIMELINE (self), GST_CLOCK_TIME_NONE);
3302   g_return_val_if_fail (GES_FRAME_NUMBER_IS_VALID (frame_number),
3303       GST_CLOCK_TIME_NONE);
3304
3305   timeline_get_framerate (self, &fps_n, &fps_d);
3306
3307   return gst_util_uint64_scale_ceil (frame_number, fps_d * GST_SECOND, fps_n);
3308 }
3309
3310 /**
3311  * ges_timeline_get_frame_at:
3312  * @self: A #GESTimeline
3313  * @timestamp: The timestamp to get the corresponding frame number of
3314  *
3315  * This method allows you to convert a timeline #GstClockTime into its
3316  * corresponding #GESFrameNumber in the timeline's output.
3317  *
3318  * Returns: The frame number @timestamp corresponds to.
3319  *
3320  * Since: 1.18
3321  */
3322 GESFrameNumber
3323 ges_timeline_get_frame_at (GESTimeline * self, GstClockTime timestamp)
3324 {
3325   gint fps_n, fps_d;
3326
3327   g_return_val_if_fail (GES_IS_TIMELINE (self), GES_FRAME_NUMBER_NONE);
3328   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (timestamp),
3329       GES_FRAME_NUMBER_NONE);
3330
3331   timeline_get_framerate (self, &fps_n, &fps_d);
3332
3333   return gst_util_uint64_scale (timestamp, fps_n, fps_d * GST_SECOND);
3334 }