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