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