9d3164991a38ed21291c9106651b08b2caa48df7
[platform/upstream/gstreamer.git] / libs / gst / base / gstaggregator.c
1 /* GStreamer aggregator base class
2  * Copyright (C) 2014 Mathieu Duponchelle <mathieu.duponchelle@opencreed.com>
3  * Copyright (C) 2014 Thibault Saunier <tsaunier@gnome.org>
4  *
5  * gstaggregator.c:
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION: gstaggregator
24  * @short_description: manages a set of pads with the purpose of
25  * aggregating their buffers.
26  * @see_also: gstcollectpads for historical reasons.
27  *
28  * Manages a set of pads with the purpose of aggregating their buffers.
29  * Control is given to the subclass when all pads have data.
30  * <itemizedlist>
31  *  <listitem><para>
32  *    Base class for mixers and muxers. Subclasses should at least implement
33  *    the #GstAggregatorClass.aggregate() virtual method.
34  *  </para></listitem>
35  *  <listitem><para>
36  *    When data is queued on all pads, tha aggregate vmethod is called.
37  *  </para></listitem>
38  *  <listitem><para>
39  *    One can peek at the data on any given GstAggregatorPad with the
40  *    gst_aggregator_pad_get_buffer () method, and take ownership of it
41  *    with the gst_aggregator_pad_steal_buffer () method. When a buffer
42  *    has been taken with steal_buffer (), a new buffer can be queued
43  *    on that pad.
44  *  </para></listitem>
45  *  <listitem><para>
46  *    If the subclass wishes to push a buffer downstream in its aggregate
47  *    implementation, it should do so through the
48  *    gst_aggregator_finish_buffer () method. This method will take care
49  *    of sending and ordering mandatory events such as stream start, caps
50  *    and segment.
51  *  </para></listitem>
52  *  <listitem><para>
53  *    Same goes for EOS events, which should not be pushed directly by the
54  *    subclass, it should instead return GST_FLOW_EOS in its aggregate
55  *    implementation.
56  *  </para></listitem>
57  *  <listitem><para>
58  *    Note that the aggregator logic regarding gap event handling is to turn
59  *    these into gap buffers with matching PTS and duration. It will also
60  *    flag these buffers with GST_BUFFER_FLAG_GAP and GST_BUFFER_FLAG_DROPPABLE
61  *    to ease their identification and subsequent processing.
62  *  </para></listitem>
63  * </itemizedlist>
64  */
65
66 #ifdef HAVE_CONFIG_H
67 #  include "config.h"
68 #endif
69
70 #include <string.h>             /* strlen */
71
72 #include "gstaggregator.h"
73
74 typedef enum
75 {
76   GST_AGGREGATOR_START_TIME_SELECTION_ZERO,
77   GST_AGGREGATOR_START_TIME_SELECTION_FIRST,
78   GST_AGGREGATOR_START_TIME_SELECTION_SET
79 } GstAggregatorStartTimeSelection;
80
81 static GType
82 gst_aggregator_start_time_selection_get_type (void)
83 {
84   static GType gtype = 0;
85
86   if (gtype == 0) {
87     static const GEnumValue values[] = {
88       {GST_AGGREGATOR_START_TIME_SELECTION_ZERO,
89           "Start at 0 running time (default)", "zero"},
90       {GST_AGGREGATOR_START_TIME_SELECTION_FIRST,
91           "Start at first observed input running time", "first"},
92       {GST_AGGREGATOR_START_TIME_SELECTION_SET,
93           "Set start time with start-time property", "set"},
94       {0, NULL, NULL}
95     };
96
97     gtype = g_enum_register_static ("GstAggregatorStartTimeSelection", values);
98   }
99   return gtype;
100 }
101
102 /*  Might become API */
103 static void gst_aggregator_merge_tags (GstAggregator * aggregator,
104     const GstTagList * tags, GstTagMergeMode mode);
105 static void gst_aggregator_set_latency_property (GstAggregator * agg,
106     gint64 latency);
107 static gint64 gst_aggregator_get_latency_property (GstAggregator * agg);
108
109
110 /* Locking order, locks in this element must always be taken in this order
111  *
112  * standard sink pad stream lock -> GST_PAD_STREAM_LOCK (aggpad)
113  * Aggregator pad flush lock -> PAD_FLUSH_LOCK(aggpad)
114  * standard src pad stream lock -> GST_PAD_STREAM_LOCK (srcpad)
115  * Aggregator src lock -> SRC_LOCK(agg) w/ SRC_WAIT/BROADCAST
116  * standard element object lock -> GST_OBJECT_LOCK(agg)
117  * Aggregator pad lock -> PAD_LOCK (aggpad) w/ PAD_WAIT/BROADCAST_EVENT(aggpad)
118  * standard src pad object lock -> GST_OBJECT_LOCK(srcpad)
119  * standard sink pad object lock -> GST_OBJECT_LOCK(aggpad)
120  */
121
122
123 static GstClockTime gst_aggregator_get_latency_unlocked (GstAggregator * self);
124
125 GST_DEBUG_CATEGORY_STATIC (aggregator_debug);
126 #define GST_CAT_DEFAULT aggregator_debug
127
128 /* GstAggregatorPad definitions */
129 #define PAD_LOCK(pad)   G_STMT_START {                                  \
130   GST_TRACE_OBJECT (pad, "Taking PAD lock from thread %p",              \
131         g_thread_self());                                               \
132   g_mutex_lock(&pad->priv->lock);                                       \
133   GST_TRACE_OBJECT (pad, "Took PAD lock from thread %p",                \
134         g_thread_self());                                               \
135   } G_STMT_END
136
137 #define PAD_UNLOCK(pad)  G_STMT_START {                                 \
138   GST_TRACE_OBJECT (pad, "Releasing PAD lock from thread %p",           \
139       g_thread_self());                                                 \
140   g_mutex_unlock(&pad->priv->lock);                                     \
141   GST_TRACE_OBJECT (pad, "Release PAD lock from thread %p",             \
142         g_thread_self());                                               \
143   } G_STMT_END
144
145
146 #define PAD_WAIT_EVENT(pad)   G_STMT_START {                            \
147   GST_LOG_OBJECT (pad, "Waiting for buffer to be consumed thread %p",   \
148         g_thread_self());                                               \
149   g_cond_wait(&(((GstAggregatorPad* )pad)->priv->event_cond),           \
150       (&((GstAggregatorPad*)pad)->priv->lock));                         \
151   GST_LOG_OBJECT (pad, "DONE Waiting for buffer to be consumed on thread %p", \
152         g_thread_self());                                               \
153   } G_STMT_END
154
155 #define PAD_BROADCAST_EVENT(pad) G_STMT_START {                        \
156   GST_LOG_OBJECT (pad, "Signaling buffer consumed from thread %p",     \
157         g_thread_self());                                              \
158   g_cond_broadcast(&(((GstAggregatorPad* )pad)->priv->event_cond));    \
159   } G_STMT_END
160
161
162 #define PAD_FLUSH_LOCK(pad)     G_STMT_START {                          \
163   GST_TRACE_OBJECT (pad, "Taking lock from thread %p",                  \
164         g_thread_self());                                               \
165   g_mutex_lock(&pad->priv->flush_lock);                                 \
166   GST_TRACE_OBJECT (pad, "Took lock from thread %p",                    \
167         g_thread_self());                                               \
168   } G_STMT_END
169
170 #define PAD_FLUSH_UNLOCK(pad)   G_STMT_START {                          \
171   GST_TRACE_OBJECT (pad, "Releasing lock from thread %p",               \
172         g_thread_self());                                               \
173   g_mutex_unlock(&pad->priv->flush_lock);                               \
174   GST_TRACE_OBJECT (pad, "Release lock from thread %p",                 \
175         g_thread_self());                                               \
176   } G_STMT_END
177
178 #define SRC_LOCK(self)   G_STMT_START {                             \
179   GST_TRACE_OBJECT (self, "Taking src lock from thread %p",         \
180       g_thread_self());                                             \
181   g_mutex_lock(&self->priv->src_lock);                              \
182   GST_TRACE_OBJECT (self, "Took src lock from thread %p",           \
183         g_thread_self());                                           \
184   } G_STMT_END
185
186 #define SRC_UNLOCK(self)  G_STMT_START {                            \
187   GST_TRACE_OBJECT (self, "Releasing src lock from thread %p",      \
188         g_thread_self());                                           \
189   g_mutex_unlock(&self->priv->src_lock);                            \
190   GST_TRACE_OBJECT (self, "Released src lock from thread %p",       \
191         g_thread_self());                                           \
192   } G_STMT_END
193
194 #define SRC_WAIT(self) G_STMT_START {                               \
195   GST_LOG_OBJECT (self, "Waiting for src on thread %p",             \
196         g_thread_self());                                           \
197   g_cond_wait(&(self->priv->src_cond), &(self->priv->src_lock));    \
198   GST_LOG_OBJECT (self, "DONE Waiting for src on thread %p",        \
199         g_thread_self());                                           \
200   } G_STMT_END
201
202 #define SRC_BROADCAST(self) G_STMT_START {                          \
203     GST_LOG_OBJECT (self, "Signaling src from thread %p",           \
204         g_thread_self());                                           \
205     if (self->priv->aggregate_id)                                   \
206       gst_clock_id_unschedule (self->priv->aggregate_id);           \
207     g_cond_broadcast(&(self->priv->src_cond));                      \
208   } G_STMT_END
209
210 struct _GstAggregatorPadPrivate
211 {
212   /* Following fields are protected by the PAD_LOCK */
213   GstFlowReturn flow_return;
214   gboolean pending_flush_start;
215   gboolean pending_flush_stop;
216   gboolean pending_eos;
217
218   GQueue buffers;
219   guint num_buffers;
220   GstClockTime head_position;
221   GstClockTime tail_position;
222   GstClockTime head_time;
223   GstClockTime tail_time;
224   GstClockTime time_level;
225
226   gboolean eos;
227
228   GMutex lock;
229   GCond event_cond;
230   /* This lock prevents a flush start processing happening while
231    * the chain function is also happening.
232    */
233   GMutex flush_lock;
234 };
235
236 static gboolean
237 gst_aggregator_pad_flush (GstAggregatorPad * aggpad, GstAggregator * agg)
238 {
239   GstAggregatorPadClass *klass = GST_AGGREGATOR_PAD_GET_CLASS (aggpad);
240
241   PAD_LOCK (aggpad);
242   aggpad->priv->pending_eos = FALSE;
243   aggpad->priv->eos = FALSE;
244   aggpad->priv->flow_return = GST_FLOW_OK;
245   GST_OBJECT_LOCK (aggpad);
246   gst_segment_init (&aggpad->segment, GST_FORMAT_UNDEFINED);
247   gst_segment_init (&aggpad->clip_segment, GST_FORMAT_UNDEFINED);
248   GST_OBJECT_UNLOCK (aggpad);
249   aggpad->priv->head_position = GST_CLOCK_TIME_NONE;
250   aggpad->priv->tail_position = GST_CLOCK_TIME_NONE;
251   aggpad->priv->head_time = GST_CLOCK_TIME_NONE;
252   aggpad->priv->tail_time = GST_CLOCK_TIME_NONE;
253   aggpad->priv->time_level = 0;
254   PAD_UNLOCK (aggpad);
255
256   if (klass->flush)
257     return klass->flush (aggpad, agg);
258
259   return TRUE;
260 }
261
262 /*************************************
263  * GstAggregator implementation  *
264  *************************************/
265 static GstElementClass *aggregator_parent_class = NULL;
266
267 /* All members are protected by the object lock unless otherwise noted */
268
269 struct _GstAggregatorPrivate
270 {
271   gint padcount;
272
273   /* Our state is >= PAUSED */
274   gboolean running;             /* protected by src_lock */
275
276   gint seqnum;
277   gboolean send_stream_start;   /* protected by srcpad stream lock */
278   gboolean send_segment;
279   gboolean flush_seeking;
280   gboolean pending_flush_start;
281   gboolean send_eos;            /* protected by srcpad stream lock */
282
283   GstCaps *srccaps;             /* protected by the srcpad stream lock */
284
285   GstTagList *tags;
286   gboolean tags_changed;
287
288   gboolean peer_latency_live;   /* protected by src_lock */
289   GstClockTime peer_latency_min;        /* protected by src_lock */
290   GstClockTime peer_latency_max;        /* protected by src_lock */
291   gboolean has_peer_latency;
292
293   GstClockTime sub_latency_min; /* protected by src_lock */
294   GstClockTime sub_latency_max; /* protected by src_lock */
295
296   /* aggregate */
297   GstClockID aggregate_id;      /* protected by src_lock */
298   GMutex src_lock;
299   GCond src_cond;
300
301   gboolean first_buffer;
302   GstAggregatorStartTimeSelection start_time_selection;
303   GstClockTime start_time;
304
305   /* properties */
306   gint64 latency;               /* protected by both src_lock and all pad locks */
307 };
308
309 typedef struct
310 {
311   GstEvent *event;
312   gboolean result;
313   gboolean flush;
314
315   gboolean one_actually_seeked;
316 } EventData;
317
318 #define DEFAULT_LATENCY              0
319 #define DEFAULT_START_TIME_SELECTION GST_AGGREGATOR_START_TIME_SELECTION_ZERO
320 #define DEFAULT_START_TIME           (-1)
321
322 enum
323 {
324   PROP_0,
325   PROP_LATENCY,
326   PROP_START_TIME_SELECTION,
327   PROP_START_TIME,
328   PROP_LAST
329 };
330
331 static GstFlowReturn gst_aggregator_pad_chain_internal (GstAggregator * self,
332     GstAggregatorPad * aggpad, GstBuffer * buffer, gboolean head);
333
334 /**
335  * gst_aggregator_iterate_sinkpads:
336  * @self: The #GstAggregator
337  * @func: (scope call): The function to call.
338  * @user_data: (closure): The data to pass to @func.
339  *
340  * Iterate the sinkpads of aggregator to call a function on them.
341  *
342  * This method guarantees that @func will be called only once for each
343  * sink pad.
344  */
345 gboolean
346 gst_aggregator_iterate_sinkpads (GstAggregator * self,
347     GstAggregatorPadForeachFunc func, gpointer user_data)
348 {
349   gboolean result = FALSE;
350   GstIterator *iter;
351   gboolean done = FALSE;
352   GValue item = { 0, };
353   GList *seen_pads = NULL;
354
355   iter = gst_element_iterate_sink_pads (GST_ELEMENT (self));
356
357   if (!iter)
358     goto no_iter;
359
360   while (!done) {
361     switch (gst_iterator_next (iter, &item)) {
362       case GST_ITERATOR_OK:
363       {
364         GstAggregatorPad *pad;
365
366         pad = g_value_get_object (&item);
367
368         /* if already pushed, skip. FIXME, find something faster to tag pads */
369         if (pad == NULL || g_list_find (seen_pads, pad)) {
370           g_value_reset (&item);
371           break;
372         }
373
374         GST_LOG_OBJECT (pad, "calling function %s on pad",
375             GST_DEBUG_FUNCPTR_NAME (func));
376
377         result = func (self, pad, user_data);
378
379         done = !result;
380
381         seen_pads = g_list_prepend (seen_pads, pad);
382
383         g_value_reset (&item);
384         break;
385       }
386       case GST_ITERATOR_RESYNC:
387         gst_iterator_resync (iter);
388         break;
389       case GST_ITERATOR_ERROR:
390         GST_ERROR_OBJECT (self,
391             "Could not iterate over internally linked pads");
392         done = TRUE;
393         break;
394       case GST_ITERATOR_DONE:
395         done = TRUE;
396         break;
397     }
398   }
399   g_value_unset (&item);
400   gst_iterator_free (iter);
401
402   if (seen_pads == NULL) {
403     GST_DEBUG_OBJECT (self, "No pad seen");
404     return FALSE;
405   }
406
407   g_list_free (seen_pads);
408
409 no_iter:
410   return result;
411 }
412
413 static gboolean
414 gst_aggregator_pad_queue_is_empty (GstAggregatorPad * pad)
415 {
416   return (g_queue_peek_tail (&pad->priv->buffers) == NULL);
417 }
418
419 static gboolean
420 gst_aggregator_check_pads_ready (GstAggregator * self)
421 {
422   GstAggregatorPad *pad;
423   GList *l, *sinkpads;
424
425   GST_LOG_OBJECT (self, "checking pads");
426
427   GST_OBJECT_LOCK (self);
428
429   sinkpads = GST_ELEMENT_CAST (self)->sinkpads;
430   if (sinkpads == NULL)
431     goto no_sinkpads;
432
433   for (l = sinkpads; l != NULL; l = l->next) {
434     pad = l->data;
435
436     PAD_LOCK (pad);
437
438     /* In live mode, having a single pad with buffers is enough to
439      * generate a start time from it. In non-live mode all pads need
440      * to have a buffer
441      */
442     if (self->priv->peer_latency_live &&
443         !gst_aggregator_pad_queue_is_empty (pad))
444       self->priv->first_buffer = FALSE;
445
446     if (gst_aggregator_pad_queue_is_empty (pad) && !pad->priv->eos) {
447       PAD_UNLOCK (pad);
448       goto pad_not_ready;
449     }
450     PAD_UNLOCK (pad);
451
452   }
453
454   self->priv->first_buffer = FALSE;
455
456   GST_OBJECT_UNLOCK (self);
457   GST_LOG_OBJECT (self, "pads are ready");
458   return TRUE;
459
460 no_sinkpads:
461   {
462     GST_LOG_OBJECT (self, "pads not ready: no sink pads");
463     GST_OBJECT_UNLOCK (self);
464     return FALSE;
465   }
466 pad_not_ready:
467   {
468     GST_LOG_OBJECT (pad, "pad not ready to be aggregated yet");
469     GST_OBJECT_UNLOCK (self);
470     return FALSE;
471   }
472 }
473
474 static void
475 gst_aggregator_reset_flow_values (GstAggregator * self)
476 {
477   GST_OBJECT_LOCK (self);
478   self->priv->send_stream_start = TRUE;
479   self->priv->send_segment = TRUE;
480   gst_segment_init (&self->segment, GST_FORMAT_TIME);
481   self->priv->first_buffer = TRUE;
482   GST_OBJECT_UNLOCK (self);
483 }
484
485 static inline void
486 gst_aggregator_push_mandatory_events (GstAggregator * self)
487 {
488   GstAggregatorPrivate *priv = self->priv;
489   GstEvent *segment = NULL;
490   GstEvent *tags = NULL;
491
492   if (self->priv->send_stream_start) {
493     gchar s_id[32];
494
495     GST_INFO_OBJECT (self, "pushing stream start");
496     /* stream-start (FIXME: create id based on input ids) */
497     g_snprintf (s_id, sizeof (s_id), "agg-%08x", g_random_int ());
498     if (!gst_pad_push_event (self->srcpad, gst_event_new_stream_start (s_id))) {
499       GST_WARNING_OBJECT (self->srcpad, "Sending stream start event failed");
500     }
501     self->priv->send_stream_start = FALSE;
502   }
503
504   if (self->priv->srccaps) {
505
506     GST_INFO_OBJECT (self, "pushing caps: %" GST_PTR_FORMAT,
507         self->priv->srccaps);
508     if (!gst_pad_push_event (self->srcpad,
509             gst_event_new_caps (self->priv->srccaps))) {
510       GST_WARNING_OBJECT (self->srcpad, "Sending caps event failed");
511     }
512     gst_caps_unref (self->priv->srccaps);
513     self->priv->srccaps = NULL;
514   }
515
516   GST_OBJECT_LOCK (self);
517   if (self->priv->send_segment && !self->priv->flush_seeking) {
518     segment = gst_event_new_segment (&self->segment);
519
520     if (!self->priv->seqnum)
521       self->priv->seqnum = gst_event_get_seqnum (segment);
522     else
523       gst_event_set_seqnum (segment, self->priv->seqnum);
524     self->priv->send_segment = FALSE;
525
526     GST_DEBUG_OBJECT (self, "pushing segment %" GST_PTR_FORMAT, segment);
527   }
528
529   if (priv->tags && priv->tags_changed && !self->priv->flush_seeking) {
530     tags = gst_event_new_tag (gst_tag_list_ref (priv->tags));
531     priv->tags_changed = FALSE;
532   }
533   GST_OBJECT_UNLOCK (self);
534
535   if (segment)
536     gst_pad_push_event (self->srcpad, segment);
537   if (tags)
538     gst_pad_push_event (self->srcpad, tags);
539
540 }
541
542 /**
543  * gst_aggregator_set_src_caps:
544  * @self: The #GstAggregator
545  * @caps: The #GstCaps to set on the src pad.
546  *
547  * Sets the caps to be used on the src pad.
548  */
549 void
550 gst_aggregator_set_src_caps (GstAggregator * self, GstCaps * caps)
551 {
552   GST_PAD_STREAM_LOCK (self->srcpad);
553   gst_caps_replace (&self->priv->srccaps, caps);
554   gst_aggregator_push_mandatory_events (self);
555   GST_PAD_STREAM_UNLOCK (self->srcpad);
556 }
557
558 /**
559  * gst_aggregator_finish_buffer:
560  * @self: The #GstAggregator
561  * @buffer: (transfer full): the #GstBuffer to push.
562  *
563  * This method will push the provided output buffer downstream. If needed,
564  * mandatory events such as stream-start, caps, and segment events will be
565  * sent before pushing the buffer.
566  */
567 GstFlowReturn
568 gst_aggregator_finish_buffer (GstAggregator * self, GstBuffer * buffer)
569 {
570   gst_aggregator_push_mandatory_events (self);
571
572   GST_OBJECT_LOCK (self);
573   if (!self->priv->flush_seeking && gst_pad_is_active (self->srcpad)) {
574     GST_TRACE_OBJECT (self, "pushing buffer %" GST_PTR_FORMAT, buffer);
575     GST_OBJECT_UNLOCK (self);
576     return gst_pad_push (self->srcpad, buffer);
577   } else {
578     GST_INFO_OBJECT (self, "Not pushing (active: %i, flushing: %i)",
579         self->priv->flush_seeking, gst_pad_is_active (self->srcpad));
580     GST_OBJECT_UNLOCK (self);
581     gst_buffer_unref (buffer);
582     return GST_FLOW_OK;
583   }
584 }
585
586 static void
587 gst_aggregator_push_eos (GstAggregator * self)
588 {
589   GstEvent *event;
590   gst_aggregator_push_mandatory_events (self);
591
592   event = gst_event_new_eos ();
593
594   GST_OBJECT_LOCK (self);
595   self->priv->send_eos = FALSE;
596   gst_event_set_seqnum (event, self->priv->seqnum);
597   GST_OBJECT_UNLOCK (self);
598
599   gst_pad_push_event (self->srcpad, event);
600 }
601
602 static GstClockTime
603 gst_aggregator_get_next_time (GstAggregator * self)
604 {
605   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
606
607   if (klass->get_next_time)
608     return klass->get_next_time (self);
609
610   return GST_CLOCK_TIME_NONE;
611 }
612
613 static gboolean
614 gst_aggregator_wait_and_check (GstAggregator * self, gboolean * timeout)
615 {
616   GstClockTime latency;
617   GstClockTime start;
618   gboolean res;
619
620   *timeout = FALSE;
621
622   SRC_LOCK (self);
623
624   latency = gst_aggregator_get_latency_unlocked (self);
625
626   if (gst_aggregator_check_pads_ready (self)) {
627     GST_DEBUG_OBJECT (self, "all pads have data");
628     SRC_UNLOCK (self);
629
630     return TRUE;
631   }
632
633   /* Before waiting, check if we're actually still running */
634   if (!self->priv->running || !self->priv->send_eos) {
635     SRC_UNLOCK (self);
636
637     return FALSE;
638   }
639
640   start = gst_aggregator_get_next_time (self);
641
642   /* If we're not live, or if we use the running time
643    * of the first buffer as start time, we wait until
644    * all pads have buffers.
645    * Otherwise (i.e. if we are live!), we wait on the clock
646    * and if a pad does not have a buffer in time we ignore
647    * that pad.
648    */
649   if (!GST_CLOCK_TIME_IS_VALID (latency) ||
650       !GST_IS_CLOCK (GST_ELEMENT_CLOCK (self)) ||
651       !GST_CLOCK_TIME_IS_VALID (start) ||
652       (self->priv->first_buffer
653           && self->priv->start_time_selection ==
654           GST_AGGREGATOR_START_TIME_SELECTION_FIRST)) {
655     /* We wake up here when something happened, and below
656      * then check if we're ready now. If we return FALSE,
657      * we will be directly called again.
658      */
659     SRC_WAIT (self);
660   } else {
661     GstClockTime base_time, time;
662     GstClock *clock;
663     GstClockReturn status;
664     GstClockTimeDiff jitter;
665
666     GST_DEBUG_OBJECT (self, "got subclass start time: %" GST_TIME_FORMAT,
667         GST_TIME_ARGS (start));
668
669     GST_OBJECT_LOCK (self);
670     base_time = GST_ELEMENT_CAST (self)->base_time;
671     clock = GST_ELEMENT_CLOCK (self);
672     if (clock)
673       gst_object_ref (clock);
674     GST_OBJECT_UNLOCK (self);
675
676     time = base_time + start;
677     time += latency;
678
679     GST_DEBUG_OBJECT (self, "possibly waiting for clock to reach %"
680         GST_TIME_FORMAT " (base %" GST_TIME_FORMAT " start %" GST_TIME_FORMAT
681         " latency %" GST_TIME_FORMAT " current %" GST_TIME_FORMAT ")",
682         GST_TIME_ARGS (time),
683         GST_TIME_ARGS (GST_ELEMENT_CAST (self)->base_time),
684         GST_TIME_ARGS (start), GST_TIME_ARGS (latency),
685         GST_TIME_ARGS (gst_clock_get_time (clock)));
686
687     self->priv->aggregate_id = gst_clock_new_single_shot_id (clock, time);
688     gst_object_unref (clock);
689     SRC_UNLOCK (self);
690
691     jitter = 0;
692     status = gst_clock_id_wait (self->priv->aggregate_id, &jitter);
693
694     SRC_LOCK (self);
695     if (self->priv->aggregate_id) {
696       gst_clock_id_unref (self->priv->aggregate_id);
697       self->priv->aggregate_id = NULL;
698     }
699
700     GST_DEBUG_OBJECT (self,
701         "clock returned %d (jitter: %s%" GST_TIME_FORMAT ")",
702         status, (jitter < 0 ? "-" : " "),
703         GST_TIME_ARGS ((jitter < 0 ? -jitter : jitter)));
704
705     /* we timed out */
706     if (status == GST_CLOCK_OK || status == GST_CLOCK_EARLY) {
707       SRC_UNLOCK (self);
708       *timeout = TRUE;
709       return TRUE;
710     }
711   }
712
713   res = gst_aggregator_check_pads_ready (self);
714   SRC_UNLOCK (self);
715
716   return res;
717 }
718
719 static gboolean
720 check_events (GstAggregator * self, GstAggregatorPad * pad, gpointer user_data)
721 {
722   GstEvent *event = NULL;
723   GstAggregatorClass *klass = NULL;
724   gboolean *processed_event = user_data;
725
726   do {
727     event = NULL;
728
729     PAD_LOCK (pad);
730     if (gst_aggregator_pad_queue_is_empty (pad) && pad->priv->pending_eos) {
731       pad->priv->pending_eos = FALSE;
732       pad->priv->eos = TRUE;
733     }
734     if (GST_IS_EVENT (g_queue_peek_tail (&pad->priv->buffers))) {
735       event = g_queue_pop_tail (&pad->priv->buffers);
736       PAD_BROADCAST_EVENT (pad);
737     }
738     PAD_UNLOCK (pad);
739     if (event) {
740       if (processed_event)
741         *processed_event = TRUE;
742       if (klass == NULL)
743         klass = GST_AGGREGATOR_GET_CLASS (self);
744
745       GST_LOG_OBJECT (pad, "Processing %" GST_PTR_FORMAT, event);
746       klass->sink_event (self, pad, event);
747     }
748   } while (event != NULL);
749
750   return TRUE;
751 }
752
753 static void
754 gst_aggregator_pad_set_flushing (GstAggregatorPad * aggpad,
755     GstFlowReturn flow_return, gboolean full)
756 {
757   GList *item;
758
759   PAD_LOCK (aggpad);
760   if (flow_return == GST_FLOW_NOT_LINKED)
761     aggpad->priv->flow_return = MIN (flow_return, aggpad->priv->flow_return);
762   else
763     aggpad->priv->flow_return = flow_return;
764
765   item = g_queue_peek_head_link (&aggpad->priv->buffers);
766   while (item) {
767     GList *next = item->next;
768
769     /* In partial flush, we do like the pad, we get rid of non-sticky events
770      * and EOS/SEGMENT.
771      */
772     if (full || GST_IS_BUFFER (item->data) ||
773         GST_EVENT_TYPE (item->data) == GST_EVENT_EOS ||
774         GST_EVENT_TYPE (item->data) == GST_EVENT_SEGMENT ||
775         !GST_EVENT_IS_STICKY (item->data)) {
776       gst_mini_object_unref (item->data);
777       g_queue_delete_link (&aggpad->priv->buffers, item);
778     }
779     item = next;
780   }
781   aggpad->priv->num_buffers = 0;
782
783   PAD_BROADCAST_EVENT (aggpad);
784   PAD_UNLOCK (aggpad);
785 }
786
787 static void
788 gst_aggregator_aggregate_func (GstAggregator * self)
789 {
790   GstAggregatorPrivate *priv = self->priv;
791   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
792   gboolean timeout = FALSE;
793
794   if (self->priv->running == FALSE) {
795     GST_DEBUG_OBJECT (self, "Not running anymore");
796     return;
797   }
798
799   GST_LOG_OBJECT (self, "Checking aggregate");
800   while (priv->send_eos && priv->running) {
801     GstFlowReturn flow_return;
802     gboolean processed_event = FALSE;
803
804     gst_aggregator_iterate_sinkpads (self, check_events, NULL);
805
806     if (!gst_aggregator_wait_and_check (self, &timeout))
807       continue;
808
809     gst_aggregator_iterate_sinkpads (self, check_events, &processed_event);
810     if (processed_event)
811       continue;
812
813     GST_TRACE_OBJECT (self, "Actually aggregating!");
814     flow_return = klass->aggregate (self, timeout);
815
816     GST_OBJECT_LOCK (self);
817     if (flow_return == GST_FLOW_FLUSHING && priv->flush_seeking) {
818       /* We don't want to set the pads to flushing, but we want to
819        * stop the thread, so just break here */
820       GST_OBJECT_UNLOCK (self);
821       break;
822     }
823     GST_OBJECT_UNLOCK (self);
824
825     if (flow_return == GST_FLOW_EOS || flow_return == GST_FLOW_ERROR) {
826       gst_aggregator_push_eos (self);
827     }
828
829     GST_LOG_OBJECT (self, "flow return is %s", gst_flow_get_name (flow_return));
830
831     if (flow_return != GST_FLOW_OK) {
832       GList *item;
833
834       GST_OBJECT_LOCK (self);
835       for (item = GST_ELEMENT (self)->sinkpads; item; item = item->next) {
836         GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (item->data);
837
838         gst_aggregator_pad_set_flushing (aggpad, flow_return, TRUE);
839       }
840       GST_OBJECT_UNLOCK (self);
841       break;
842     }
843   }
844
845   /* Pause the task here, the only ways to get here are:
846    * 1) We're stopping, in which case the task is stopped anyway
847    * 2) We got a flow error above, in which case it might take
848    *    some time to forward the flow return upstream and we
849    *    would otherwise call the task function over and over
850    *    again without doing anything
851    */
852   gst_pad_pause_task (self->srcpad);
853 }
854
855 static gboolean
856 gst_aggregator_start (GstAggregator * self)
857 {
858   GstAggregatorClass *klass;
859   gboolean result;
860
861   self->priv->running = TRUE;
862   self->priv->send_stream_start = TRUE;
863   self->priv->send_segment = TRUE;
864   self->priv->send_eos = TRUE;
865   self->priv->srccaps = NULL;
866
867   klass = GST_AGGREGATOR_GET_CLASS (self);
868
869   if (klass->start)
870     result = klass->start (self);
871   else
872     result = TRUE;
873
874   return result;
875 }
876
877 static gboolean
878 _check_pending_flush_stop (GstAggregatorPad * pad)
879 {
880   gboolean res;
881
882   PAD_LOCK (pad);
883   res = (!pad->priv->pending_flush_stop && !pad->priv->pending_flush_start);
884   PAD_UNLOCK (pad);
885
886   return res;
887 }
888
889 static gboolean
890 gst_aggregator_stop_srcpad_task (GstAggregator * self, GstEvent * flush_start)
891 {
892   gboolean res = TRUE;
893
894   GST_INFO_OBJECT (self, "%s srcpad task",
895       flush_start ? "Pausing" : "Stopping");
896
897   SRC_LOCK (self);
898   self->priv->running = FALSE;
899   SRC_BROADCAST (self);
900   SRC_UNLOCK (self);
901
902   if (flush_start) {
903     res = gst_pad_push_event (self->srcpad, flush_start);
904   }
905
906   gst_pad_stop_task (self->srcpad);
907
908   return res;
909 }
910
911 static void
912 gst_aggregator_start_srcpad_task (GstAggregator * self)
913 {
914   GST_INFO_OBJECT (self, "Starting srcpad task");
915
916   self->priv->running = TRUE;
917   gst_pad_start_task (GST_PAD (self->srcpad),
918       (GstTaskFunction) gst_aggregator_aggregate_func, self, NULL);
919 }
920
921 static GstFlowReturn
922 gst_aggregator_flush (GstAggregator * self)
923 {
924   GstFlowReturn ret = GST_FLOW_OK;
925   GstAggregatorPrivate *priv = self->priv;
926   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
927
928   GST_DEBUG_OBJECT (self, "Flushing everything");
929   GST_OBJECT_LOCK (self);
930   priv->send_segment = TRUE;
931   priv->flush_seeking = FALSE;
932   priv->tags_changed = FALSE;
933   GST_OBJECT_UNLOCK (self);
934   if (klass->flush)
935     ret = klass->flush (self);
936
937   return ret;
938 }
939
940
941 /* Called with GstAggregator's object lock held */
942
943 static gboolean
944 gst_aggregator_all_flush_stop_received_locked (GstAggregator * self)
945 {
946   GList *tmp;
947   GstAggregatorPad *tmppad;
948
949   for (tmp = GST_ELEMENT (self)->sinkpads; tmp; tmp = tmp->next) {
950     tmppad = (GstAggregatorPad *) tmp->data;
951
952     if (_check_pending_flush_stop (tmppad) == FALSE) {
953       GST_DEBUG_OBJECT (tmppad, "Is not last %i -- %i",
954           tmppad->priv->pending_flush_start, tmppad->priv->pending_flush_stop);
955       return FALSE;
956     }
957   }
958
959   return TRUE;
960 }
961
962 static void
963 gst_aggregator_flush_start (GstAggregator * self, GstAggregatorPad * aggpad,
964     GstEvent * event)
965 {
966   GstAggregatorPrivate *priv = self->priv;
967   GstAggregatorPadPrivate *padpriv = aggpad->priv;
968
969   gst_aggregator_pad_set_flushing (aggpad, GST_FLOW_FLUSHING, FALSE);
970
971   PAD_FLUSH_LOCK (aggpad);
972   PAD_LOCK (aggpad);
973   if (padpriv->pending_flush_start) {
974     GST_DEBUG_OBJECT (aggpad, "Expecting FLUSH_STOP now");
975
976     padpriv->pending_flush_start = FALSE;
977     padpriv->pending_flush_stop = TRUE;
978   }
979   PAD_UNLOCK (aggpad);
980
981   GST_OBJECT_LOCK (self);
982   if (priv->flush_seeking) {
983     /* If flush_seeking we forward the first FLUSH_START */
984     if (priv->pending_flush_start) {
985       priv->pending_flush_start = FALSE;
986       GST_OBJECT_UNLOCK (self);
987
988       GST_INFO_OBJECT (self, "Flushing, pausing srcpad task");
989       gst_aggregator_stop_srcpad_task (self, event);
990
991       GST_INFO_OBJECT (self, "Getting STREAM_LOCK while seeking");
992       GST_PAD_STREAM_LOCK (self->srcpad);
993       GST_LOG_OBJECT (self, "GOT STREAM_LOCK");
994       event = NULL;
995     } else {
996       GST_OBJECT_UNLOCK (self);
997       gst_event_unref (event);
998     }
999   } else {
1000     GST_OBJECT_UNLOCK (self);
1001     gst_event_unref (event);
1002   }
1003   PAD_FLUSH_UNLOCK (aggpad);
1004 }
1005
1006 /* Must be called with the the PAD_LOCK held */
1007 static void
1008 update_time_level (GstAggregatorPad * aggpad, gboolean head)
1009 {
1010   if (head) {
1011     if (GST_CLOCK_TIME_IS_VALID (aggpad->priv->head_position) &&
1012         aggpad->clip_segment.format == GST_FORMAT_TIME)
1013       aggpad->priv->head_time =
1014           gst_segment_to_running_time (&aggpad->clip_segment,
1015           GST_FORMAT_TIME, aggpad->priv->head_position);
1016     else
1017       aggpad->priv->head_time = GST_CLOCK_TIME_NONE;
1018   } else {
1019     if (GST_CLOCK_TIME_IS_VALID (aggpad->priv->tail_position) &&
1020         aggpad->segment.format == GST_FORMAT_TIME)
1021       aggpad->priv->tail_time =
1022           gst_segment_to_running_time (&aggpad->segment,
1023           GST_FORMAT_TIME, aggpad->priv->tail_position);
1024     else
1025       aggpad->priv->tail_time = aggpad->priv->head_time;
1026   }
1027
1028   if (aggpad->priv->head_time == GST_CLOCK_TIME_NONE ||
1029       aggpad->priv->tail_time == GST_CLOCK_TIME_NONE) {
1030     aggpad->priv->time_level = 0;
1031     return;
1032   }
1033
1034   if (aggpad->priv->tail_time > aggpad->priv->head_time)
1035     aggpad->priv->time_level = 0;
1036   else
1037     aggpad->priv->time_level = aggpad->priv->head_time -
1038         aggpad->priv->tail_time;
1039 }
1040
1041
1042 /* GstAggregator vmethods default implementations */
1043 static gboolean
1044 gst_aggregator_default_sink_event (GstAggregator * self,
1045     GstAggregatorPad * aggpad, GstEvent * event)
1046 {
1047   gboolean res = TRUE;
1048   GstPad *pad = GST_PAD (aggpad);
1049   GstAggregatorPrivate *priv = self->priv;
1050
1051   switch (GST_EVENT_TYPE (event)) {
1052     case GST_EVENT_FLUSH_START:
1053     {
1054       gst_aggregator_flush_start (self, aggpad, event);
1055       /* We forward only in one case: right after flush_seeking */
1056       event = NULL;
1057       goto eat;
1058     }
1059     case GST_EVENT_FLUSH_STOP:
1060     {
1061       GST_DEBUG_OBJECT (aggpad, "Got FLUSH_STOP");
1062
1063       gst_aggregator_pad_flush (aggpad, self);
1064       GST_OBJECT_LOCK (self);
1065       if (priv->flush_seeking) {
1066         g_atomic_int_set (&aggpad->priv->pending_flush_stop, FALSE);
1067         if (gst_aggregator_all_flush_stop_received_locked (self)) {
1068           GST_OBJECT_UNLOCK (self);
1069           /* That means we received FLUSH_STOP/FLUSH_STOP on
1070            * all sinkpads -- Seeking is Done... sending FLUSH_STOP */
1071           gst_aggregator_flush (self);
1072           gst_pad_push_event (self->srcpad, event);
1073           event = NULL;
1074           SRC_LOCK (self);
1075           priv->send_eos = TRUE;
1076           SRC_BROADCAST (self);
1077           SRC_UNLOCK (self);
1078
1079           GST_INFO_OBJECT (self, "Releasing source pad STREAM_LOCK");
1080           GST_PAD_STREAM_UNLOCK (self->srcpad);
1081           gst_aggregator_start_srcpad_task (self);
1082         } else {
1083           GST_OBJECT_UNLOCK (self);
1084         }
1085       } else {
1086         GST_OBJECT_UNLOCK (self);
1087       }
1088
1089       /* We never forward the event */
1090       goto eat;
1091     }
1092     case GST_EVENT_EOS:
1093     {
1094       GST_DEBUG_OBJECT (aggpad, "EOS");
1095
1096       /* We still have a buffer, and we don't want the subclass to have to
1097        * check for it. Mark pending_eos, eos will be set when steal_buffer is
1098        * called
1099        */
1100       SRC_LOCK (self);
1101       PAD_LOCK (aggpad);
1102       if (gst_aggregator_pad_queue_is_empty (aggpad)) {
1103         aggpad->priv->eos = TRUE;
1104       } else {
1105         aggpad->priv->pending_eos = TRUE;
1106       }
1107       PAD_UNLOCK (aggpad);
1108
1109       SRC_BROADCAST (self);
1110       SRC_UNLOCK (self);
1111       goto eat;
1112     }
1113     case GST_EVENT_SEGMENT:
1114     {
1115       PAD_LOCK (aggpad);
1116       GST_OBJECT_LOCK (aggpad);
1117       gst_event_copy_segment (event, &aggpad->segment);
1118       update_time_level (aggpad, FALSE);
1119       GST_OBJECT_UNLOCK (aggpad);
1120       PAD_UNLOCK (aggpad);
1121
1122       GST_OBJECT_LOCK (self);
1123       self->priv->seqnum = gst_event_get_seqnum (event);
1124       GST_OBJECT_UNLOCK (self);
1125       goto eat;
1126     }
1127     case GST_EVENT_STREAM_START:
1128     {
1129       goto eat;
1130     }
1131     case GST_EVENT_GAP:
1132     {
1133       GstClockTime pts, endpts;
1134       GstClockTime duration;
1135       GstBuffer *gapbuf;
1136
1137       gst_event_parse_gap (event, &pts, &duration);
1138       gapbuf = gst_buffer_new ();
1139
1140       if (GST_CLOCK_TIME_IS_VALID (duration))
1141         endpts = pts + duration;
1142       else
1143         endpts = GST_CLOCK_TIME_NONE;
1144
1145       GST_OBJECT_LOCK (aggpad);
1146       res = gst_segment_clip (&aggpad->segment, GST_FORMAT_TIME, pts, endpts,
1147           &pts, &endpts);
1148       GST_OBJECT_UNLOCK (aggpad);
1149
1150       if (!res) {
1151         GST_WARNING_OBJECT (self, "GAP event outside segment, dropping");
1152         goto eat;
1153       }
1154
1155       if (GST_CLOCK_TIME_IS_VALID (endpts) && GST_CLOCK_TIME_IS_VALID (pts))
1156         duration = endpts - pts;
1157       else
1158         duration = GST_CLOCK_TIME_NONE;
1159
1160       GST_BUFFER_PTS (gapbuf) = pts;
1161       GST_BUFFER_DURATION (gapbuf) = duration;
1162       GST_BUFFER_FLAG_SET (gapbuf, GST_BUFFER_FLAG_GAP);
1163       GST_BUFFER_FLAG_SET (gapbuf, GST_BUFFER_FLAG_DROPPABLE);
1164
1165       if (gst_aggregator_pad_chain_internal (self, aggpad, gapbuf, FALSE) !=
1166           GST_FLOW_OK) {
1167         GST_WARNING_OBJECT (self, "Failed to chain gap buffer");
1168         res = FALSE;
1169       }
1170
1171       goto eat;
1172     }
1173     case GST_EVENT_TAG:
1174     {
1175       GstTagList *tags;
1176
1177       gst_event_parse_tag (event, &tags);
1178
1179       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1180         gst_aggregator_merge_tags (self, tags, GST_TAG_MERGE_REPLACE);
1181         gst_event_unref (event);
1182         event = NULL;
1183         goto eat;
1184       }
1185       break;
1186     }
1187     default:
1188     {
1189       break;
1190     }
1191   }
1192
1193   GST_DEBUG_OBJECT (pad, "Forwarding event: %" GST_PTR_FORMAT, event);
1194   return gst_pad_event_default (pad, GST_OBJECT (self), event);
1195
1196 eat:
1197   GST_DEBUG_OBJECT (pad, "Eating event: %" GST_PTR_FORMAT, event);
1198   if (event)
1199     gst_event_unref (event);
1200
1201   return res;
1202 }
1203
1204 static inline gboolean
1205 gst_aggregator_stop_pad (GstAggregator * self, GstAggregatorPad * pad,
1206     gpointer unused_udata)
1207 {
1208   gst_aggregator_pad_flush (pad, self);
1209
1210   return TRUE;
1211 }
1212
1213 static gboolean
1214 gst_aggregator_stop (GstAggregator * agg)
1215 {
1216   GstAggregatorClass *klass;
1217   gboolean result;
1218
1219   gst_aggregator_reset_flow_values (agg);
1220
1221   gst_aggregator_iterate_sinkpads (agg, gst_aggregator_stop_pad, NULL);
1222
1223   klass = GST_AGGREGATOR_GET_CLASS (agg);
1224
1225   if (klass->stop)
1226     result = klass->stop (agg);
1227   else
1228     result = TRUE;
1229
1230   agg->priv->has_peer_latency = FALSE;
1231   agg->priv->peer_latency_live = FALSE;
1232   agg->priv->peer_latency_min = agg->priv->peer_latency_max = FALSE;
1233
1234   if (agg->priv->tags)
1235     gst_tag_list_unref (agg->priv->tags);
1236   agg->priv->tags = NULL;
1237
1238   return result;
1239 }
1240
1241 /* GstElement vmethods implementations */
1242 static GstStateChangeReturn
1243 gst_aggregator_change_state (GstElement * element, GstStateChange transition)
1244 {
1245   GstStateChangeReturn ret;
1246   GstAggregator *self = GST_AGGREGATOR (element);
1247
1248   switch (transition) {
1249     case GST_STATE_CHANGE_READY_TO_PAUSED:
1250       if (!gst_aggregator_start (self))
1251         goto error_start;
1252       break;
1253     default:
1254       break;
1255   }
1256
1257   if ((ret =
1258           GST_ELEMENT_CLASS (aggregator_parent_class)->change_state (element,
1259               transition)) == GST_STATE_CHANGE_FAILURE)
1260     goto failure;
1261
1262
1263   switch (transition) {
1264     case GST_STATE_CHANGE_PAUSED_TO_READY:
1265       if (!gst_aggregator_stop (self)) {
1266         /* What to do in this case? Error out? */
1267         GST_ERROR_OBJECT (self, "Subclass failed to stop.");
1268       }
1269       break;
1270     default:
1271       break;
1272   }
1273
1274   return ret;
1275
1276 /* ERRORS */
1277 failure:
1278   {
1279     GST_ERROR_OBJECT (element, "parent failed state change");
1280     return ret;
1281   }
1282 error_start:
1283   {
1284     GST_ERROR_OBJECT (element, "Subclass failed to start");
1285     return GST_STATE_CHANGE_FAILURE;
1286   }
1287 }
1288
1289 static void
1290 gst_aggregator_release_pad (GstElement * element, GstPad * pad)
1291 {
1292   GstAggregator *self = GST_AGGREGATOR (element);
1293   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1294
1295   GST_INFO_OBJECT (pad, "Removing pad");
1296
1297   SRC_LOCK (self);
1298   gst_aggregator_pad_set_flushing (aggpad, GST_FLOW_FLUSHING, TRUE);
1299   gst_element_remove_pad (element, pad);
1300
1301   self->priv->has_peer_latency = FALSE;
1302   SRC_BROADCAST (self);
1303   SRC_UNLOCK (self);
1304 }
1305
1306 static GstPad *
1307 gst_aggregator_request_new_pad (GstElement * element,
1308     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
1309 {
1310   GstAggregator *self;
1311   GstAggregatorPad *agg_pad;
1312
1313   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
1314   GstAggregatorPrivate *priv = GST_AGGREGATOR (element)->priv;
1315
1316   self = GST_AGGREGATOR (element);
1317
1318   if (templ == gst_element_class_get_pad_template (klass, "sink_%u")) {
1319     gint serial = 0;
1320     gchar *name = NULL;
1321
1322     GST_OBJECT_LOCK (element);
1323     if (req_name == NULL || strlen (req_name) < 6
1324         || !g_str_has_prefix (req_name, "sink_")) {
1325       /* no name given when requesting the pad, use next available int */
1326       priv->padcount++;
1327     } else {
1328       /* parse serial number from requested padname */
1329       serial = g_ascii_strtoull (&req_name[5], NULL, 10);
1330       if (serial >= priv->padcount)
1331         priv->padcount = serial;
1332     }
1333
1334     name = g_strdup_printf ("sink_%u", priv->padcount);
1335     agg_pad = g_object_new (GST_AGGREGATOR_GET_CLASS (self)->sinkpads_type,
1336         "name", name, "direction", GST_PAD_SINK, "template", templ, NULL);
1337     g_free (name);
1338
1339     GST_OBJECT_UNLOCK (element);
1340
1341   } else {
1342     return NULL;
1343   }
1344
1345   GST_DEBUG_OBJECT (element, "Adding pad %s", GST_PAD_NAME (agg_pad));
1346   self->priv->has_peer_latency = FALSE;
1347
1348   if (priv->running)
1349     gst_pad_set_active (GST_PAD (agg_pad), TRUE);
1350
1351   /* add the pad to the element */
1352   gst_element_add_pad (element, GST_PAD (agg_pad));
1353
1354   return GST_PAD (agg_pad);
1355 }
1356
1357 /* Must be called with SRC_LOCK held */
1358
1359 static gboolean
1360 gst_aggregator_query_latency_unlocked (GstAggregator * self, GstQuery * query)
1361 {
1362   gboolean query_ret, live;
1363   GstClockTime our_latency, min, max;
1364
1365   query_ret = gst_pad_query_default (self->srcpad, GST_OBJECT (self), query);
1366
1367   if (!query_ret) {
1368     GST_WARNING_OBJECT (self, "Latency query failed");
1369     return FALSE;
1370   }
1371
1372   gst_query_parse_latency (query, &live, &min, &max);
1373
1374   our_latency = self->priv->latency;
1375
1376   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (min))) {
1377     GST_ERROR_OBJECT (self, "Invalid minimum latency %" GST_TIME_FORMAT
1378         ". Please file a bug at " PACKAGE_BUGREPORT ".", GST_TIME_ARGS (min));
1379     return FALSE;
1380   }
1381
1382   if (min > max && GST_CLOCK_TIME_IS_VALID (max)) {
1383     GST_ELEMENT_WARNING (self, CORE, CLOCK, (NULL),
1384         ("Impossible to configure latency: max %" GST_TIME_FORMAT " < min %"
1385             GST_TIME_FORMAT ". Add queues or other buffering elements.",
1386             GST_TIME_ARGS (max), GST_TIME_ARGS (min)));
1387     return FALSE;
1388   }
1389
1390   self->priv->peer_latency_live = live;
1391   self->priv->peer_latency_min = min;
1392   self->priv->peer_latency_max = max;
1393   self->priv->has_peer_latency = TRUE;
1394
1395   /* add our own */
1396   min += our_latency;
1397   min += self->priv->sub_latency_min;
1398   if (GST_CLOCK_TIME_IS_VALID (self->priv->sub_latency_max)
1399       && GST_CLOCK_TIME_IS_VALID (max))
1400     max += self->priv->sub_latency_max + our_latency;
1401   else
1402     max = GST_CLOCK_TIME_NONE;
1403
1404   if (live && min > max) {
1405     GST_ELEMENT_WARNING (self, CORE, NEGOTIATION,
1406         ("%s", "Latency too big"),
1407         ("The requested latency value is too big for the current pipeline. "
1408             "Limiting to %" G_GINT64_FORMAT, max));
1409     min = max;
1410     /* FIXME: This could in theory become negative, but in
1411      * that case all is lost anyway */
1412     self->priv->latency -= min - max;
1413     /* FIXME: shouldn't we g_object_notify() the change here? */
1414   }
1415
1416   SRC_BROADCAST (self);
1417
1418   GST_DEBUG_OBJECT (self, "configured latency live:%s min:%" G_GINT64_FORMAT
1419       " max:%" G_GINT64_FORMAT, live ? "true" : "false", min, max);
1420
1421   gst_query_set_latency (query, live, min, max);
1422
1423   return query_ret;
1424 }
1425
1426 /*
1427  * MUST be called with the src_lock held.
1428  *
1429  * See  gst_aggregator_get_latency() for doc
1430  */
1431 static GstClockTime
1432 gst_aggregator_get_latency_unlocked (GstAggregator * self)
1433 {
1434   GstClockTime latency;
1435
1436   g_return_val_if_fail (GST_IS_AGGREGATOR (self), 0);
1437
1438   if (!self->priv->has_peer_latency) {
1439     GstQuery *query = gst_query_new_latency ();
1440     gboolean ret;
1441
1442     ret = gst_aggregator_query_latency_unlocked (self, query);
1443     gst_query_unref (query);
1444     if (!ret)
1445       return GST_CLOCK_TIME_NONE;
1446   }
1447
1448   if (!self->priv->has_peer_latency || !self->priv->peer_latency_live)
1449     return GST_CLOCK_TIME_NONE;
1450
1451   /* latency_min is never GST_CLOCK_TIME_NONE by construction */
1452   latency = self->priv->peer_latency_min;
1453
1454   /* add our own */
1455   latency += self->priv->latency;
1456   latency += self->priv->sub_latency_min;
1457
1458   return latency;
1459 }
1460
1461 /**
1462  * gst_aggregator_get_latency:
1463  * @self: a #GstAggregator
1464  *
1465  * Retrieves the latency values reported by @self in response to the latency
1466  * query, or %GST_CLOCK_TIME_NONE if there is not live source connected and the element
1467  * will not wait for the clock.
1468  *
1469  * Typically only called by subclasses.
1470  *
1471  * Returns: The latency or %GST_CLOCK_TIME_NONE if the element does not sync
1472  */
1473 GstClockTime
1474 gst_aggregator_get_latency (GstAggregator * self)
1475 {
1476   GstClockTime ret;
1477
1478   SRC_LOCK (self);
1479   ret = gst_aggregator_get_latency_unlocked (self);
1480   SRC_UNLOCK (self);
1481
1482   return ret;
1483 }
1484
1485 static gboolean
1486 gst_aggregator_send_event (GstElement * element, GstEvent * event)
1487 {
1488   GstAggregator *self = GST_AGGREGATOR (element);
1489
1490   GST_STATE_LOCK (element);
1491   if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK &&
1492       GST_STATE (element) < GST_STATE_PAUSED) {
1493     gdouble rate;
1494     GstFormat fmt;
1495     GstSeekFlags flags;
1496     GstSeekType start_type, stop_type;
1497     gint64 start, stop;
1498
1499     gst_event_parse_seek (event, &rate, &fmt, &flags, &start_type,
1500         &start, &stop_type, &stop);
1501
1502     GST_OBJECT_LOCK (self);
1503     gst_segment_do_seek (&self->segment, rate, fmt, flags, start_type, start,
1504         stop_type, stop, NULL);
1505     self->priv->seqnum = gst_event_get_seqnum (event);
1506     self->priv->first_buffer = FALSE;
1507     GST_OBJECT_UNLOCK (self);
1508
1509     GST_DEBUG_OBJECT (element, "Storing segment %" GST_PTR_FORMAT, event);
1510   }
1511   GST_STATE_UNLOCK (element);
1512
1513
1514   return GST_ELEMENT_CLASS (aggregator_parent_class)->send_event (element,
1515       event);
1516 }
1517
1518 static gboolean
1519 gst_aggregator_default_src_query (GstAggregator * self, GstQuery * query)
1520 {
1521   gboolean res = TRUE;
1522
1523   switch (GST_QUERY_TYPE (query)) {
1524     case GST_QUERY_SEEKING:
1525     {
1526       GstFormat format;
1527
1528       /* don't pass it along as some (file)sink might claim it does
1529        * whereas with a collectpads in between that will not likely work */
1530       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
1531       gst_query_set_seeking (query, format, FALSE, 0, -1);
1532       res = TRUE;
1533
1534       break;
1535     }
1536     case GST_QUERY_LATENCY:
1537       SRC_LOCK (self);
1538       res = gst_aggregator_query_latency_unlocked (self, query);
1539       SRC_UNLOCK (self);
1540       break;
1541     default:
1542       return gst_pad_query_default (self->srcpad, GST_OBJECT (self), query);
1543   }
1544
1545   return res;
1546 }
1547
1548 static gboolean
1549 gst_aggregator_event_forward_func (GstPad * pad, gpointer user_data)
1550 {
1551   EventData *evdata = user_data;
1552   gboolean ret = TRUE;
1553   GstPad *peer = gst_pad_get_peer (pad);
1554   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1555
1556   if (peer) {
1557     ret = gst_pad_send_event (peer, gst_event_ref (evdata->event));
1558     GST_DEBUG_OBJECT (pad, "return of event push is %d", ret);
1559     gst_object_unref (peer);
1560   }
1561
1562   if (ret == FALSE) {
1563     if (GST_EVENT_TYPE (evdata->event) == GST_EVENT_SEEK)
1564       GST_ERROR_OBJECT (pad, "Event %" GST_PTR_FORMAT " failed", evdata->event);
1565
1566     if (GST_EVENT_TYPE (evdata->event) == GST_EVENT_SEEK) {
1567       GstQuery *seeking = gst_query_new_seeking (GST_FORMAT_TIME);
1568
1569       if (gst_pad_query (peer, seeking)) {
1570         gboolean seekable;
1571
1572         gst_query_parse_seeking (seeking, NULL, &seekable, NULL, NULL);
1573
1574         if (seekable == FALSE) {
1575           GST_INFO_OBJECT (pad,
1576               "Source not seekable, We failed but it does not matter!");
1577
1578           ret = TRUE;
1579         }
1580       } else {
1581         GST_ERROR_OBJECT (pad, "Query seeking FAILED");
1582       }
1583
1584       gst_query_unref (seeking);
1585     }
1586
1587     if (evdata->flush) {
1588       PAD_LOCK (aggpad);
1589       aggpad->priv->pending_flush_start = FALSE;
1590       aggpad->priv->pending_flush_stop = FALSE;
1591       PAD_UNLOCK (aggpad);
1592     }
1593   } else {
1594     evdata->one_actually_seeked = TRUE;
1595   }
1596
1597   evdata->result &= ret;
1598
1599   /* Always send to all pads */
1600   return FALSE;
1601 }
1602
1603 static EventData
1604 gst_aggregator_forward_event_to_all_sinkpads (GstAggregator * self,
1605     GstEvent * event, gboolean flush)
1606 {
1607   EventData evdata;
1608
1609   evdata.event = event;
1610   evdata.result = TRUE;
1611   evdata.flush = flush;
1612   evdata.one_actually_seeked = FALSE;
1613
1614   /* We first need to set all pads as flushing in a first pass
1615    * as flush_start flush_stop is sometimes sent synchronously
1616    * while we send the seek event */
1617   if (flush) {
1618     GList *l;
1619
1620     GST_OBJECT_LOCK (self);
1621     for (l = GST_ELEMENT_CAST (self)->sinkpads; l != NULL; l = l->next) {
1622       GstAggregatorPad *pad = l->data;
1623
1624       PAD_LOCK (pad);
1625       pad->priv->pending_flush_start = TRUE;
1626       pad->priv->pending_flush_stop = FALSE;
1627       PAD_UNLOCK (pad);
1628     }
1629     GST_OBJECT_UNLOCK (self);
1630   }
1631
1632   gst_pad_forward (self->srcpad, gst_aggregator_event_forward_func, &evdata);
1633
1634   gst_event_unref (event);
1635
1636   return evdata;
1637 }
1638
1639 static gboolean
1640 gst_aggregator_do_seek (GstAggregator * self, GstEvent * event)
1641 {
1642   gdouble rate;
1643   GstFormat fmt;
1644   GstSeekFlags flags;
1645   GstSeekType start_type, stop_type;
1646   gint64 start, stop;
1647   gboolean flush;
1648   EventData evdata;
1649   GstAggregatorPrivate *priv = self->priv;
1650
1651   gst_event_parse_seek (event, &rate, &fmt, &flags, &start_type,
1652       &start, &stop_type, &stop);
1653
1654   GST_INFO_OBJECT (self, "starting SEEK");
1655
1656   flush = flags & GST_SEEK_FLAG_FLUSH;
1657
1658   GST_OBJECT_LOCK (self);
1659   if (flush) {
1660     priv->pending_flush_start = TRUE;
1661     priv->flush_seeking = TRUE;
1662   }
1663
1664   gst_segment_do_seek (&self->segment, rate, fmt, flags, start_type, start,
1665       stop_type, stop, NULL);
1666
1667   /* Seeking sets a position */
1668   self->priv->first_buffer = FALSE;
1669   GST_OBJECT_UNLOCK (self);
1670
1671   /* forward the seek upstream */
1672   evdata = gst_aggregator_forward_event_to_all_sinkpads (self, event, flush);
1673   event = NULL;
1674
1675   if (!evdata.result || !evdata.one_actually_seeked) {
1676     GST_OBJECT_LOCK (self);
1677     priv->flush_seeking = FALSE;
1678     priv->pending_flush_start = FALSE;
1679     GST_OBJECT_UNLOCK (self);
1680   }
1681
1682   GST_INFO_OBJECT (self, "seek done, result: %d", evdata.result);
1683
1684   return evdata.result;
1685 }
1686
1687 static gboolean
1688 gst_aggregator_default_src_event (GstAggregator * self, GstEvent * event)
1689 {
1690   EventData evdata;
1691   gboolean res = TRUE;
1692
1693   switch (GST_EVENT_TYPE (event)) {
1694     case GST_EVENT_SEEK:
1695     {
1696       gst_event_ref (event);
1697       res = gst_aggregator_do_seek (self, event);
1698       gst_event_unref (event);
1699       event = NULL;
1700       goto done;
1701     }
1702     case GST_EVENT_NAVIGATION:
1703     {
1704       /* navigation is rather pointless. */
1705       res = FALSE;
1706       gst_event_unref (event);
1707       goto done;
1708     }
1709     default:
1710     {
1711       break;
1712     }
1713   }
1714
1715   evdata = gst_aggregator_forward_event_to_all_sinkpads (self, event, FALSE);
1716   res = evdata.result;
1717
1718 done:
1719   return res;
1720 }
1721
1722 static gboolean
1723 gst_aggregator_src_pad_event_func (GstPad * pad, GstObject * parent,
1724     GstEvent * event)
1725 {
1726   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1727
1728   return klass->src_event (GST_AGGREGATOR (parent), event);
1729 }
1730
1731 static gboolean
1732 gst_aggregator_src_pad_query_func (GstPad * pad, GstObject * parent,
1733     GstQuery * query)
1734 {
1735   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1736
1737   return klass->src_query (GST_AGGREGATOR (parent), query);
1738 }
1739
1740 static gboolean
1741 gst_aggregator_src_pad_activate_mode_func (GstPad * pad,
1742     GstObject * parent, GstPadMode mode, gboolean active)
1743 {
1744   GstAggregator *self = GST_AGGREGATOR (parent);
1745   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1746
1747   if (klass->src_activate) {
1748     if (klass->src_activate (self, mode, active) == FALSE) {
1749       return FALSE;
1750     }
1751   }
1752
1753   if (active == TRUE) {
1754     switch (mode) {
1755       case GST_PAD_MODE_PUSH:
1756       {
1757         GST_INFO_OBJECT (pad, "Activating pad!");
1758         gst_aggregator_start_srcpad_task (self);
1759         return TRUE;
1760       }
1761       default:
1762       {
1763         GST_ERROR_OBJECT (pad, "Only supported mode is PUSH");
1764         return FALSE;
1765       }
1766     }
1767   }
1768
1769   /* deactivating */
1770   GST_INFO_OBJECT (self, "Deactivating srcpad");
1771   gst_aggregator_stop_srcpad_task (self, FALSE);
1772
1773   return TRUE;
1774 }
1775
1776 static gboolean
1777 gst_aggregator_default_sink_query (GstAggregator * self,
1778     GstAggregatorPad * aggpad, GstQuery * query)
1779 {
1780   GstPad *pad = GST_PAD (aggpad);
1781
1782   return gst_pad_query_default (pad, GST_OBJECT (self), query);
1783 }
1784
1785 static void
1786 gst_aggregator_finalize (GObject * object)
1787 {
1788   GstAggregator *self = (GstAggregator *) object;
1789
1790   g_mutex_clear (&self->priv->src_lock);
1791   g_cond_clear (&self->priv->src_cond);
1792
1793   G_OBJECT_CLASS (aggregator_parent_class)->finalize (object);
1794 }
1795
1796 /*
1797  * gst_aggregator_set_latency_property:
1798  * @agg: a #GstAggregator
1799  * @latency: the new latency value (in nanoseconds).
1800  *
1801  * Sets the new latency value to @latency. This value is used to limit the
1802  * amount of time a pad waits for data to appear before considering the pad
1803  * as unresponsive.
1804  */
1805 static void
1806 gst_aggregator_set_latency_property (GstAggregator * self, gint64 latency)
1807 {
1808   gboolean changed;
1809
1810   g_return_if_fail (GST_IS_AGGREGATOR (self));
1811   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (latency));
1812
1813   SRC_LOCK (self);
1814   changed = (self->priv->latency != latency);
1815
1816   if (changed) {
1817     GList *item;
1818
1819     GST_OBJECT_LOCK (self);
1820     /* First lock all the pads */
1821     for (item = GST_ELEMENT_CAST (self)->sinkpads; item; item = item->next) {
1822       GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (item->data);
1823       PAD_LOCK (aggpad);
1824     }
1825
1826     self->priv->latency = latency;
1827
1828     SRC_BROADCAST (self);
1829
1830     /* Now wake up the pads */
1831     for (item = GST_ELEMENT_CAST (self)->sinkpads; item; item = item->next) {
1832       GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (item->data);
1833       PAD_BROADCAST_EVENT (aggpad);
1834       PAD_UNLOCK (aggpad);
1835     }
1836     GST_OBJECT_UNLOCK (self);
1837   }
1838
1839   SRC_UNLOCK (self);
1840
1841   if (changed)
1842     gst_element_post_message (GST_ELEMENT_CAST (self),
1843         gst_message_new_latency (GST_OBJECT_CAST (self)));
1844 }
1845
1846 /*
1847  * gst_aggregator_get_latency_property:
1848  * @agg: a #GstAggregator
1849  *
1850  * Gets the latency value. See gst_aggregator_set_latency for
1851  * more details.
1852  *
1853  * Returns: The time in nanoseconds to wait for data to arrive on a sink pad 
1854  * before a pad is deemed unresponsive. A value of -1 means an
1855  * unlimited time.
1856  */
1857 static gint64
1858 gst_aggregator_get_latency_property (GstAggregator * agg)
1859 {
1860   gint64 res;
1861
1862   g_return_val_if_fail (GST_IS_AGGREGATOR (agg), -1);
1863
1864   GST_OBJECT_LOCK (agg);
1865   res = agg->priv->latency;
1866   GST_OBJECT_UNLOCK (agg);
1867
1868   return res;
1869 }
1870
1871 static void
1872 gst_aggregator_set_property (GObject * object, guint prop_id,
1873     const GValue * value, GParamSpec * pspec)
1874 {
1875   GstAggregator *agg = GST_AGGREGATOR (object);
1876
1877   switch (prop_id) {
1878     case PROP_LATENCY:
1879       gst_aggregator_set_latency_property (agg, g_value_get_int64 (value));
1880       break;
1881     case PROP_START_TIME_SELECTION:
1882       agg->priv->start_time_selection = g_value_get_enum (value);
1883       break;
1884     case PROP_START_TIME:
1885       agg->priv->start_time = g_value_get_uint64 (value);
1886       break;
1887     default:
1888       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1889       break;
1890   }
1891 }
1892
1893 static void
1894 gst_aggregator_get_property (GObject * object, guint prop_id,
1895     GValue * value, GParamSpec * pspec)
1896 {
1897   GstAggregator *agg = GST_AGGREGATOR (object);
1898
1899   switch (prop_id) {
1900     case PROP_LATENCY:
1901       g_value_set_int64 (value, gst_aggregator_get_latency_property (agg));
1902       break;
1903     case PROP_START_TIME_SELECTION:
1904       g_value_set_enum (value, agg->priv->start_time_selection);
1905       break;
1906     case PROP_START_TIME:
1907       g_value_set_uint64 (value, agg->priv->start_time);
1908       break;
1909     default:
1910       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1911       break;
1912   }
1913 }
1914
1915 /* GObject vmethods implementations */
1916 static void
1917 gst_aggregator_class_init (GstAggregatorClass * klass)
1918 {
1919   GObjectClass *gobject_class = (GObjectClass *) klass;
1920   GstElementClass *gstelement_class = (GstElementClass *) klass;
1921
1922   aggregator_parent_class = g_type_class_peek_parent (klass);
1923   g_type_class_add_private (klass, sizeof (GstAggregatorPrivate));
1924
1925   GST_DEBUG_CATEGORY_INIT (aggregator_debug, "aggregator",
1926       GST_DEBUG_FG_MAGENTA, "GstAggregator");
1927
1928   klass->sinkpads_type = GST_TYPE_AGGREGATOR_PAD;
1929
1930   klass->sink_event = gst_aggregator_default_sink_event;
1931   klass->sink_query = gst_aggregator_default_sink_query;
1932
1933   klass->src_event = gst_aggregator_default_src_event;
1934   klass->src_query = gst_aggregator_default_src_query;
1935
1936   gstelement_class->request_new_pad =
1937       GST_DEBUG_FUNCPTR (gst_aggregator_request_new_pad);
1938   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_aggregator_send_event);
1939   gstelement_class->release_pad =
1940       GST_DEBUG_FUNCPTR (gst_aggregator_release_pad);
1941   gstelement_class->change_state =
1942       GST_DEBUG_FUNCPTR (gst_aggregator_change_state);
1943
1944   gobject_class->set_property = gst_aggregator_set_property;
1945   gobject_class->get_property = gst_aggregator_get_property;
1946   gobject_class->finalize = gst_aggregator_finalize;
1947
1948   g_object_class_install_property (gobject_class, PROP_LATENCY,
1949       g_param_spec_int64 ("latency", "Buffer latency",
1950           "Additional latency in live mode to allow upstream "
1951           "to take longer to produce buffers for the current "
1952           "position (in nanoseconds)", 0,
1953           (G_MAXLONG == G_MAXINT64) ? G_MAXINT64 : (G_MAXLONG * GST_SECOND - 1),
1954           DEFAULT_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1955
1956   g_object_class_install_property (gobject_class, PROP_START_TIME_SELECTION,
1957       g_param_spec_enum ("start-time-selection", "Start Time Selection",
1958           "Decides which start time is output",
1959           gst_aggregator_start_time_selection_get_type (),
1960           DEFAULT_START_TIME_SELECTION,
1961           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1962
1963   g_object_class_install_property (gobject_class, PROP_START_TIME,
1964       g_param_spec_uint64 ("start-time", "Start Time",
1965           "Start time to use if start-time-selection=set", 0,
1966           G_MAXUINT64,
1967           DEFAULT_START_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1968
1969   GST_DEBUG_REGISTER_FUNCPTR (gst_aggregator_stop_pad);
1970 }
1971
1972 static void
1973 gst_aggregator_init (GstAggregator * self, GstAggregatorClass * klass)
1974 {
1975   GstPadTemplate *pad_template;
1976   GstAggregatorPrivate *priv;
1977
1978   g_return_if_fail (klass->aggregate != NULL);
1979
1980   self->priv =
1981       G_TYPE_INSTANCE_GET_PRIVATE (self, GST_TYPE_AGGREGATOR,
1982       GstAggregatorPrivate);
1983
1984   priv = self->priv;
1985
1986   pad_template =
1987       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
1988   g_return_if_fail (pad_template != NULL);
1989
1990   priv->padcount = -1;
1991   priv->tags_changed = FALSE;
1992
1993   self->priv->peer_latency_live = FALSE;
1994   self->priv->peer_latency_min = self->priv->sub_latency_min = 0;
1995   self->priv->peer_latency_max = self->priv->sub_latency_max = 0;
1996   self->priv->has_peer_latency = FALSE;
1997   gst_aggregator_reset_flow_values (self);
1998
1999   self->srcpad = gst_pad_new_from_template (pad_template, "src");
2000
2001   gst_pad_set_event_function (self->srcpad,
2002       GST_DEBUG_FUNCPTR (gst_aggregator_src_pad_event_func));
2003   gst_pad_set_query_function (self->srcpad,
2004       GST_DEBUG_FUNCPTR (gst_aggregator_src_pad_query_func));
2005   gst_pad_set_activatemode_function (self->srcpad,
2006       GST_DEBUG_FUNCPTR (gst_aggregator_src_pad_activate_mode_func));
2007
2008   gst_element_add_pad (GST_ELEMENT (self), self->srcpad);
2009
2010   self->priv->latency = DEFAULT_LATENCY;
2011   self->priv->start_time_selection = DEFAULT_START_TIME_SELECTION;
2012   self->priv->start_time = DEFAULT_START_TIME;
2013
2014   g_mutex_init (&self->priv->src_lock);
2015   g_cond_init (&self->priv->src_cond);
2016 }
2017
2018 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
2019  * method to get to the padtemplates */
2020 GType
2021 gst_aggregator_get_type (void)
2022 {
2023   static volatile gsize type = 0;
2024
2025   if (g_once_init_enter (&type)) {
2026     GType _type;
2027     static const GTypeInfo info = {
2028       sizeof (GstAggregatorClass),
2029       NULL,
2030       NULL,
2031       (GClassInitFunc) gst_aggregator_class_init,
2032       NULL,
2033       NULL,
2034       sizeof (GstAggregator),
2035       0,
2036       (GInstanceInitFunc) gst_aggregator_init,
2037     };
2038
2039     _type = g_type_register_static (GST_TYPE_ELEMENT,
2040         "GstAggregator", &info, G_TYPE_FLAG_ABSTRACT);
2041     g_once_init_leave (&type, _type);
2042   }
2043   return type;
2044 }
2045
2046 /* Must be called with SRC lock and PAD lock held */
2047 static gboolean
2048 gst_aggregator_pad_has_space (GstAggregator * self, GstAggregatorPad * aggpad)
2049 {
2050   /* Empty queue always has space */
2051   if (g_queue_get_length (&aggpad->priv->buffers) == 0)
2052     return TRUE;
2053
2054   /* We also want at least two buffers, one is being processed and one is ready
2055    * for the next iteration when we operate in live mode. */
2056   if (self->priv->peer_latency_live && aggpad->priv->num_buffers < 2)
2057     return TRUE;
2058
2059   /* zero latency, if there is a buffer, it's full */
2060   if (self->priv->latency == 0)
2061     return FALSE;
2062
2063   /* Allow no more buffers than the latency */
2064   return (aggpad->priv->time_level <= self->priv->latency);
2065 }
2066
2067 /* Must be called with the PAD_LOCK held */
2068 static void
2069 apply_buffer (GstAggregatorPad * aggpad, GstBuffer * buffer, gboolean head)
2070 {
2071   GstClockTime timestamp;
2072
2073   if (GST_BUFFER_DTS_IS_VALID (buffer))
2074     timestamp = GST_BUFFER_DTS (buffer);
2075   else
2076     timestamp = GST_BUFFER_PTS (buffer);
2077
2078   if (timestamp == GST_CLOCK_TIME_NONE) {
2079     if (head)
2080       timestamp = aggpad->priv->head_position;
2081     else
2082       timestamp = aggpad->priv->tail_position;
2083   }
2084
2085   /* add duration */
2086   if (GST_BUFFER_DURATION_IS_VALID (buffer))
2087     timestamp += GST_BUFFER_DURATION (buffer);
2088
2089   if (head)
2090     aggpad->priv->head_position = timestamp;
2091   else
2092     aggpad->priv->tail_position = timestamp;
2093
2094   update_time_level (aggpad, head);
2095 }
2096
2097 static GstFlowReturn
2098 gst_aggregator_pad_chain_internal (GstAggregator * self,
2099     GstAggregatorPad * aggpad, GstBuffer * buffer, gboolean head)
2100 {
2101   GstBuffer *actual_buf = buffer;
2102   GstAggregatorClass *aggclass = GST_AGGREGATOR_GET_CLASS (self);
2103   GstFlowReturn flow_return;
2104   GstClockTime buf_pts;
2105
2106   GST_DEBUG_OBJECT (aggpad, "Start chaining a buffer %" GST_PTR_FORMAT, buffer);
2107
2108   PAD_FLUSH_LOCK (aggpad);
2109
2110   PAD_LOCK (aggpad);
2111   flow_return = aggpad->priv->flow_return;
2112   if (flow_return != GST_FLOW_OK)
2113     goto flushing;
2114
2115   if (aggpad->priv->pending_eos == TRUE)
2116     goto eos;
2117
2118   flow_return = aggpad->priv->flow_return;
2119   if (flow_return != GST_FLOW_OK)
2120     goto flushing;
2121
2122   PAD_UNLOCK (aggpad);
2123
2124   if (aggclass->clip && head) {
2125     aggclass->clip (self, aggpad, buffer, &actual_buf);
2126   }
2127
2128   if (actual_buf == NULL) {
2129     GST_LOG_OBJECT (actual_buf, "Buffer dropped by clip function");
2130     goto done;
2131   }
2132
2133   buf_pts = GST_BUFFER_PTS (actual_buf);
2134
2135   for (;;) {
2136     SRC_LOCK (self);
2137     PAD_LOCK (aggpad);
2138     if (gst_aggregator_pad_has_space (self, aggpad)
2139         && aggpad->priv->flow_return == GST_FLOW_OK) {
2140       if (head)
2141         g_queue_push_head (&aggpad->priv->buffers, actual_buf);
2142       else
2143         g_queue_push_tail (&aggpad->priv->buffers, actual_buf);
2144       apply_buffer (aggpad, actual_buf, head);
2145       aggpad->priv->num_buffers++;
2146       actual_buf = buffer = NULL;
2147       SRC_BROADCAST (self);
2148       break;
2149     }
2150
2151     flow_return = aggpad->priv->flow_return;
2152     if (flow_return != GST_FLOW_OK) {
2153       SRC_UNLOCK (self);
2154       goto flushing;
2155     }
2156     GST_DEBUG_OBJECT (aggpad, "Waiting for buffer to be consumed");
2157     SRC_UNLOCK (self);
2158     PAD_WAIT_EVENT (aggpad);
2159
2160     PAD_UNLOCK (aggpad);
2161   }
2162
2163   if (self->priv->first_buffer) {
2164     GstClockTime start_time;
2165
2166     switch (self->priv->start_time_selection) {
2167       case GST_AGGREGATOR_START_TIME_SELECTION_ZERO:
2168       default:
2169         start_time = 0;
2170         break;
2171       case GST_AGGREGATOR_START_TIME_SELECTION_FIRST:
2172         if (aggpad->segment.format == GST_FORMAT_TIME) {
2173           start_time = buf_pts;
2174           if (start_time != -1) {
2175             start_time = MAX (start_time, aggpad->segment.start);
2176             start_time =
2177                 gst_segment_to_running_time (&aggpad->segment, GST_FORMAT_TIME,
2178                 start_time);
2179           }
2180         } else {
2181           start_time = 0;
2182           GST_WARNING_OBJECT (aggpad,
2183               "Ignoring request of selecting the first start time "
2184               "as the segment is a %s segment instead of a time segment",
2185               gst_format_get_name (aggpad->segment.format));
2186         }
2187         break;
2188       case GST_AGGREGATOR_START_TIME_SELECTION_SET:
2189         start_time = self->priv->start_time;
2190         if (start_time == -1)
2191           start_time = 0;
2192         break;
2193     }
2194
2195     if (start_time != -1) {
2196       if (self->segment.position == -1)
2197         self->segment.position = start_time;
2198       else
2199         self->segment.position = MIN (start_time, self->segment.position);
2200       self->segment.start = MIN (start_time, self->segment.start);
2201       self->segment.time = MIN (start_time, self->segment.time);
2202
2203       GST_DEBUG_OBJECT (self, "Selecting start time %" GST_TIME_FORMAT,
2204           GST_TIME_ARGS (start_time));
2205     }
2206   }
2207
2208   PAD_UNLOCK (aggpad);
2209   SRC_UNLOCK (self);
2210
2211 done:
2212
2213   PAD_FLUSH_UNLOCK (aggpad);
2214
2215   GST_DEBUG_OBJECT (aggpad, "Done chaining");
2216
2217   return flow_return;
2218
2219 flushing:
2220   PAD_UNLOCK (aggpad);
2221   PAD_FLUSH_UNLOCK (aggpad);
2222
2223   GST_DEBUG_OBJECT (aggpad, "Pad is %s, dropping buffer",
2224       gst_flow_get_name (flow_return));
2225   if (buffer)
2226     gst_buffer_unref (buffer);
2227
2228   return flow_return;
2229
2230 eos:
2231   PAD_UNLOCK (aggpad);
2232   PAD_FLUSH_UNLOCK (aggpad);
2233
2234   gst_buffer_unref (buffer);
2235   GST_DEBUG_OBJECT (aggpad, "We are EOS already...");
2236
2237   return GST_FLOW_EOS;
2238 }
2239
2240 static GstFlowReturn
2241 gst_aggregator_pad_chain (GstPad * pad, GstObject * object, GstBuffer * buffer)
2242 {
2243   return gst_aggregator_pad_chain_internal (GST_AGGREGATOR_CAST (object),
2244       GST_AGGREGATOR_PAD_CAST (pad), buffer, TRUE);
2245 }
2246
2247 static gboolean
2248 gst_aggregator_pad_query_func (GstPad * pad, GstObject * parent,
2249     GstQuery * query)
2250 {
2251   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
2252   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
2253
2254   if (GST_QUERY_IS_SERIALIZED (query)) {
2255     PAD_LOCK (aggpad);
2256
2257     while (!gst_aggregator_pad_queue_is_empty (aggpad)
2258         && aggpad->priv->flow_return == GST_FLOW_OK) {
2259       GST_DEBUG_OBJECT (aggpad, "Waiting for buffer to be consumed");
2260       PAD_WAIT_EVENT (aggpad);
2261     }
2262
2263     if (aggpad->priv->flow_return != GST_FLOW_OK)
2264       goto flushing;
2265
2266     PAD_UNLOCK (aggpad);
2267   }
2268
2269   return klass->sink_query (GST_AGGREGATOR (parent),
2270       GST_AGGREGATOR_PAD (pad), query);
2271
2272 flushing:
2273   GST_DEBUG_OBJECT (aggpad, "Pad is %s, dropping query",
2274       gst_flow_get_name (aggpad->priv->flow_return));
2275   PAD_UNLOCK (aggpad);
2276   return FALSE;
2277 }
2278
2279 static gboolean
2280 gst_aggregator_pad_event_func (GstPad * pad, GstObject * parent,
2281     GstEvent * event)
2282 {
2283   GstAggregator *self = GST_AGGREGATOR (parent);
2284   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
2285   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
2286
2287   if (GST_EVENT_IS_SERIALIZED (event) && GST_EVENT_TYPE (event) != GST_EVENT_EOS
2288       /* && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT_DONE */ ) {
2289     SRC_LOCK (self);
2290     PAD_LOCK (aggpad);
2291
2292     if (aggpad->priv->flow_return != GST_FLOW_OK
2293         && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP)
2294       goto flushing;
2295
2296     if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
2297       GST_OBJECT_LOCK (aggpad);
2298       gst_event_copy_segment (event, &aggpad->clip_segment);
2299       aggpad->priv->head_position = aggpad->clip_segment.position;
2300       update_time_level (aggpad, TRUE);
2301       GST_OBJECT_UNLOCK (aggpad);
2302     }
2303
2304     if (!gst_aggregator_pad_queue_is_empty (aggpad) &&
2305         GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
2306       GST_DEBUG_OBJECT (aggpad, "Store event in queue: %" GST_PTR_FORMAT,
2307           event);
2308       g_queue_push_head (&aggpad->priv->buffers, event);
2309       event = NULL;
2310       SRC_BROADCAST (self);
2311     }
2312     PAD_UNLOCK (aggpad);
2313     SRC_UNLOCK (self);
2314   }
2315
2316   if (event)
2317     return klass->sink_event (self, aggpad, event);
2318   else
2319     return TRUE;
2320
2321 flushing:
2322   GST_DEBUG_OBJECT (aggpad, "Pad is %s, dropping event",
2323       gst_flow_get_name (aggpad->priv->flow_return));
2324   PAD_UNLOCK (aggpad);
2325   SRC_UNLOCK (self);
2326   if (GST_EVENT_IS_STICKY (event))
2327     gst_pad_store_sticky_event (pad, event);
2328   gst_event_unref (event);
2329   return FALSE;
2330 }
2331
2332 static gboolean
2333 gst_aggregator_pad_activate_mode_func (GstPad * pad,
2334     GstObject * parent, GstPadMode mode, gboolean active)
2335 {
2336   GstAggregator *self = GST_AGGREGATOR (parent);
2337   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
2338
2339   if (active == FALSE) {
2340     SRC_LOCK (self);
2341     gst_aggregator_pad_set_flushing (aggpad, GST_FLOW_FLUSHING, TRUE);
2342     SRC_BROADCAST (self);
2343     SRC_UNLOCK (self);
2344   } else {
2345     PAD_LOCK (aggpad);
2346     aggpad->priv->flow_return = GST_FLOW_OK;
2347     PAD_BROADCAST_EVENT (aggpad);
2348     PAD_UNLOCK (aggpad);
2349   }
2350
2351   return TRUE;
2352 }
2353
2354 /***********************************
2355  * GstAggregatorPad implementation  *
2356  ************************************/
2357 G_DEFINE_TYPE (GstAggregatorPad, gst_aggregator_pad, GST_TYPE_PAD);
2358
2359 static void
2360 gst_aggregator_pad_constructed (GObject * object)
2361 {
2362   GstPad *pad = GST_PAD (object);
2363
2364   gst_pad_set_chain_function (pad,
2365       GST_DEBUG_FUNCPTR (gst_aggregator_pad_chain));
2366   gst_pad_set_event_function (pad,
2367       GST_DEBUG_FUNCPTR (gst_aggregator_pad_event_func));
2368   gst_pad_set_query_function (pad,
2369       GST_DEBUG_FUNCPTR (gst_aggregator_pad_query_func));
2370   gst_pad_set_activatemode_function (pad,
2371       GST_DEBUG_FUNCPTR (gst_aggregator_pad_activate_mode_func));
2372 }
2373
2374 static void
2375 gst_aggregator_pad_finalize (GObject * object)
2376 {
2377   GstAggregatorPad *pad = (GstAggregatorPad *) object;
2378
2379   g_cond_clear (&pad->priv->event_cond);
2380   g_mutex_clear (&pad->priv->flush_lock);
2381   g_mutex_clear (&pad->priv->lock);
2382
2383   G_OBJECT_CLASS (gst_aggregator_pad_parent_class)->finalize (object);
2384 }
2385
2386 static void
2387 gst_aggregator_pad_dispose (GObject * object)
2388 {
2389   GstAggregatorPad *pad = (GstAggregatorPad *) object;
2390
2391   gst_aggregator_pad_set_flushing (pad, GST_FLOW_FLUSHING, TRUE);
2392
2393   G_OBJECT_CLASS (gst_aggregator_pad_parent_class)->dispose (object);
2394 }
2395
2396 static void
2397 gst_aggregator_pad_class_init (GstAggregatorPadClass * klass)
2398 {
2399   GObjectClass *gobject_class = (GObjectClass *) klass;
2400
2401   g_type_class_add_private (klass, sizeof (GstAggregatorPadPrivate));
2402
2403   gobject_class->constructed = gst_aggregator_pad_constructed;
2404   gobject_class->finalize = gst_aggregator_pad_finalize;
2405   gobject_class->dispose = gst_aggregator_pad_dispose;
2406 }
2407
2408 static void
2409 gst_aggregator_pad_init (GstAggregatorPad * pad)
2410 {
2411   pad->priv =
2412       G_TYPE_INSTANCE_GET_PRIVATE (pad, GST_TYPE_AGGREGATOR_PAD,
2413       GstAggregatorPadPrivate);
2414
2415   g_queue_init (&pad->priv->buffers);
2416   g_cond_init (&pad->priv->event_cond);
2417
2418   g_mutex_init (&pad->priv->flush_lock);
2419   g_mutex_init (&pad->priv->lock);
2420 }
2421
2422 /**
2423  * gst_aggregator_pad_steal_buffer:
2424  * @pad: the pad to get buffer from
2425  *
2426  * Steal the ref to the buffer currently queued in @pad.
2427  *
2428  * Returns: (transfer full): The buffer in @pad or NULL if no buffer was
2429  *   queued. You should unref the buffer after usage.
2430  */
2431 GstBuffer *
2432 gst_aggregator_pad_steal_buffer (GstAggregatorPad * pad)
2433 {
2434   GstBuffer *buffer = NULL;
2435
2436   PAD_LOCK (pad);
2437   if (GST_IS_BUFFER (g_queue_peek_tail (&pad->priv->buffers)))
2438     buffer = g_queue_pop_tail (&pad->priv->buffers);
2439
2440   if (buffer) {
2441     apply_buffer (pad, buffer, FALSE);
2442     pad->priv->num_buffers--;
2443     GST_TRACE_OBJECT (pad, "Consuming buffer");
2444     if (gst_aggregator_pad_queue_is_empty (pad) && pad->priv->pending_eos) {
2445       pad->priv->pending_eos = FALSE;
2446       pad->priv->eos = TRUE;
2447     }
2448     PAD_BROADCAST_EVENT (pad);
2449     GST_DEBUG_OBJECT (pad, "Consumed: %" GST_PTR_FORMAT, buffer);
2450   }
2451   PAD_UNLOCK (pad);
2452
2453   return buffer;
2454 }
2455
2456 /**
2457  * gst_aggregator_pad_drop_buffer:
2458  * @pad: the pad where to drop any pending buffer
2459  *
2460  * Drop the buffer currently queued in @pad.
2461  *
2462  * Returns: TRUE if there was a buffer queued in @pad, or FALSE if not.
2463  */
2464 gboolean
2465 gst_aggregator_pad_drop_buffer (GstAggregatorPad * pad)
2466 {
2467   GstBuffer *buf;
2468
2469   buf = gst_aggregator_pad_steal_buffer (pad);
2470
2471   if (buf == NULL)
2472     return FALSE;
2473
2474   gst_buffer_unref (buf);
2475   return TRUE;
2476 }
2477
2478 /**
2479  * gst_aggregator_pad_get_buffer:
2480  * @pad: the pad to get buffer from
2481  *
2482  * Returns: (transfer full): A reference to the buffer in @pad or
2483  * NULL if no buffer was queued. You should unref the buffer after
2484  * usage.
2485  */
2486 GstBuffer *
2487 gst_aggregator_pad_get_buffer (GstAggregatorPad * pad)
2488 {
2489   GstBuffer *buffer = NULL;
2490
2491   PAD_LOCK (pad);
2492   buffer = g_queue_peek_tail (&pad->priv->buffers);
2493   /* The tail should always be a buffer, because if it is an event,
2494    * it will be consumed immeditaly in gst_aggregator_steal_buffer */
2495
2496   if (GST_IS_BUFFER (buffer))
2497     gst_buffer_ref (buffer);
2498   else
2499     buffer = NULL;
2500   PAD_UNLOCK (pad);
2501
2502   return buffer;
2503 }
2504
2505 gboolean
2506 gst_aggregator_pad_is_eos (GstAggregatorPad * pad)
2507 {
2508   gboolean is_eos;
2509
2510   PAD_LOCK (pad);
2511   is_eos = pad->priv->eos;
2512   PAD_UNLOCK (pad);
2513
2514   return is_eos;
2515 }
2516
2517 /**
2518  * gst_aggregator_merge_tags:
2519  * @self: a #GstAggregator
2520  * @tags: a #GstTagList to merge
2521  * @mode: the #GstTagMergeMode to use
2522  *
2523  * Adds tags to so-called pending tags, which will be processed
2524  * before pushing out data downstream.
2525  *
2526  * Note that this is provided for convenience, and the subclass is
2527  * not required to use this and can still do tag handling on its own.
2528  *
2529  * MT safe.
2530  */
2531 void
2532 gst_aggregator_merge_tags (GstAggregator * self,
2533     const GstTagList * tags, GstTagMergeMode mode)
2534 {
2535   GstTagList *otags;
2536
2537   g_return_if_fail (GST_IS_AGGREGATOR (self));
2538   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2539
2540   /* FIXME Check if we can use OBJECT lock here! */
2541   GST_OBJECT_LOCK (self);
2542   if (tags)
2543     GST_DEBUG_OBJECT (self, "merging tags %" GST_PTR_FORMAT, tags);
2544   otags = self->priv->tags;
2545   self->priv->tags = gst_tag_list_merge (self->priv->tags, tags, mode);
2546   if (otags)
2547     gst_tag_list_unref (otags);
2548   self->priv->tags_changed = TRUE;
2549   GST_OBJECT_UNLOCK (self);
2550 }
2551
2552 /**
2553  * gst_aggregator_set_latency:
2554  * @self: a #GstAggregator
2555  * @min_latency: minimum latency
2556  * @max_latency: maximum latency
2557  *
2558  * Lets #GstAggregator sub-classes tell the baseclass what their internal
2559  * latency is. Will also post a LATENCY message on the bus so the pipeline
2560  * can reconfigure its global latency.
2561  */
2562 void
2563 gst_aggregator_set_latency (GstAggregator * self,
2564     GstClockTime min_latency, GstClockTime max_latency)
2565 {
2566   gboolean changed = FALSE;
2567
2568   g_return_if_fail (GST_IS_AGGREGATOR (self));
2569   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
2570   g_return_if_fail (max_latency >= min_latency);
2571
2572   SRC_LOCK (self);
2573   if (self->priv->sub_latency_min != min_latency) {
2574     self->priv->sub_latency_min = min_latency;
2575     changed = TRUE;
2576   }
2577   if (self->priv->sub_latency_max != max_latency) {
2578     self->priv->sub_latency_max = max_latency;
2579     changed = TRUE;
2580   }
2581
2582   if (changed)
2583     SRC_BROADCAST (self);
2584   SRC_UNLOCK (self);
2585
2586   if (changed) {
2587     gst_element_post_message (GST_ELEMENT_CAST (self),
2588         gst_message_new_latency (GST_OBJECT_CAST (self)));
2589   }
2590 }