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