f18bbdbf99b40705e8714f2d0eccd7c740ba91b8
[platform/upstream/gstreamer.git] / libs / gst / base / gstaggregator.c
1 /* GStreamer
2  * Copyright (C) 2014 Mathieu Duponchelle <mathieu.duponchelle@opencreed.com>
3  * Copyright (C) 2014 Thibault Saunier <tsaunier@gnome.org>
4  *
5  * gstaggregator.c:
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION: gstaggregator
24  * @short_description: manages a set of pads with the purpose of
25  * aggregating their buffers.
26  * @see_also: gstcollectpads for historical reasons.
27  *
28  * Manages a set of pads with the purpose of aggregating their buffers.
29  * Control is given to the subclass when all pads have data.
30  * <itemizedlist>
31  *  <listitem><para>
32  *    Base class for mixers and muxers. Implementers should at least implement
33  *    the aggregate () vmethod.
34  *  </para></listitem>
35  *  <listitem><para>
36  *    When data is queued on all pads, tha aggregate vmethod is called.
37  *  </para></listitem>
38  *  <listitem><para>
39  *    One can peek at the data on any given GstAggregatorPad with the
40  *    gst_aggregator_pad_get_buffer () method, and take ownership of it
41  *    with the gst_aggregator_pad_steal_buffer () method. When a buffer
42  *    has been taken with steal_buffer (), a new buffer can be queued
43  *    on that pad.
44  *  </para></listitem>
45  *  <listitem><para>
46  *    If the subclass wishes to push a buffer downstream in its aggregate
47  *    implementation, it should do so through the
48  *    gst_aggregator_finish_buffer () method. This method will take care
49  *    of sending and ordering mandatory events such as stream start, caps
50  *    and segment.
51  *  </para></listitem>
52  *  <listitem><para>
53  *    Same goes for EOS events, which should not be pushed directly by the
54  *    subclass, it should instead return GST_FLOW_EOS in its aggregate
55  *    implementation.
56  *  </para></listitem>
57  * </itemizedlist>
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
69 /*  Might become API */
70 static void gst_aggregator_merge_tags (GstAggregator * aggregator,
71     const GstTagList * tags, GstTagMergeMode mode);
72 static void gst_aggregator_set_latency_property (GstAggregator * agg,
73     gint64 latency);
74 static gint64 gst_aggregator_get_latency_property (GstAggregator * agg);
75
76
77 GST_DEBUG_CATEGORY_STATIC (aggregator_debug);
78 #define GST_CAT_DEFAULT aggregator_debug
79
80 /* GstAggregatorPad definitions */
81 #define PAD_LOCK_EVENT(pad)   G_STMT_START {                            \
82   GST_LOG_OBJECT (pad, "Taking EVENT lock from thread %p",              \
83         g_thread_self());                                               \
84   g_mutex_lock(&pad->priv->event_lock);                                 \
85   GST_LOG_OBJECT (pad, "Took EVENT lock from thread %p",              \
86         g_thread_self());                                               \
87   } G_STMT_END
88
89 #define PAD_UNLOCK_EVENT(pad)  G_STMT_START {                           \
90   GST_LOG_OBJECT (pad, "Releasing EVENT lock from thread %p",          \
91         g_thread_self());                                               \
92   g_mutex_unlock(&pad->priv->event_lock);                               \
93   GST_LOG_OBJECT (pad, "Release EVENT lock from thread %p",          \
94         g_thread_self());                                               \
95   } G_STMT_END
96
97
98 #define PAD_WAIT_EVENT(pad)   G_STMT_START {                            \
99   GST_LOG_OBJECT (pad, "Waiting for EVENT on thread %p",               \
100         g_thread_self());                                               \
101   g_cond_wait(&(((GstAggregatorPad* )pad)->priv->event_cond),       \
102       &(pad->priv->event_lock));                                        \
103   GST_LOG_OBJECT (pad, "DONE Waiting for EVENT on thread %p",               \
104         g_thread_self());                                               \
105   } G_STMT_END
106
107 #define PAD_BROADCAST_EVENT(pad) {                                          \
108   GST_LOG_OBJECT (pad, "Signaling EVENT from thread %p",               \
109         g_thread_self());                                                   \
110   g_cond_broadcast(&(((GstAggregatorPad* )pad)->priv->event_cond)); \
111   }
112
113 #define GST_AGGREGATOR_SETCAPS_LOCK(self)   G_STMT_START {        \
114   GST_LOG_OBJECT (self, "Taking SETCAPS lock from thread %p",   \
115         g_thread_self());                                         \
116   g_mutex_lock(&self->priv->setcaps_lock);                         \
117   GST_LOG_OBJECT (self, "Took SETCAPS lock from thread %p",     \
118         g_thread_self());                                         \
119   } G_STMT_END
120
121 #define GST_AGGREGATOR_SETCAPS_UNLOCK(self)   G_STMT_START {        \
122   GST_LOG_OBJECT (self, "Releasing SETCAPS lock from thread %p",  \
123         g_thread_self());                                           \
124   g_mutex_unlock(&self->priv->setcaps_lock);                         \
125   GST_LOG_OBJECT (self, "Took SETCAPS lock from thread %p",       \
126         g_thread_self());                                           \
127   } G_STMT_END
128
129 #define PAD_STREAM_LOCK(pad)   G_STMT_START {                            \
130   GST_LOG_OBJECT (pad, "Taking lock from thread %p",              \
131         g_thread_self());                                               \
132   g_mutex_lock(&pad->priv->stream_lock);                                 \
133   GST_LOG_OBJECT (pad, "Took lock from thread %p",              \
134         g_thread_self());                                               \
135   } G_STMT_END
136
137 #define PAD_STREAM_UNLOCK(pad)  G_STMT_START {                           \
138   GST_LOG_OBJECT (pad, "Releasing lock from thread %p",          \
139         g_thread_self());                                               \
140   g_mutex_unlock(&pad->priv->stream_lock);                               \
141   GST_LOG_OBJECT (pad, "Release lock from thread %p",          \
142         g_thread_self());                                               \
143   } G_STMT_END
144
145 #define SRC_STREAM_LOCK(self)   G_STMT_START {                             \
146   GST_LOG_OBJECT (self, "Taking src STREAM lock from thread %p",           \
147         g_thread_self());                                                  \
148   g_mutex_lock(&self->priv->src_lock);                                     \
149   GST_LOG_OBJECT (self, "Took src STREAM lock from thread %p",             \
150         g_thread_self());                                                  \
151   } G_STMT_END
152
153 #define SRC_STREAM_UNLOCK(self)  G_STMT_START {                            \
154   GST_LOG_OBJECT (self, "Releasing src STREAM lock from thread %p",        \
155         g_thread_self());                                                  \
156   g_mutex_unlock(&self->priv->src_lock);                                   \
157   GST_LOG_OBJECT (self, "Release src STREAM lock from thread %p",          \
158         g_thread_self());                                                  \
159   } G_STMT_END
160
161 #define SRC_STREAM_WAIT(self)   G_STMT_START {                             \
162   GST_LOG_OBJECT (self, "Waiting for src STREAM on thread %p",             \
163         g_thread_self());                                                  \
164   g_cond_wait(&(self->priv->src_cond), &(self->priv->src_lock));           \
165   GST_LOG_OBJECT (self, "DONE Waiting for src STREAM on thread %p",        \
166         g_thread_self());                                                  \
167   } G_STMT_END
168
169 #define SRC_STREAM_BROADCAST(self) {                                       \
170   GST_LOG_OBJECT (self, "Signaling src STREAM from thread %p",             \
171         g_thread_self());                                                  \
172   g_cond_broadcast(&(self->priv->src_cond));                               \
173   }
174
175 #define KICK_SRC_THREAD(self) \
176   do { \
177     SRC_STREAM_LOCK (self); \
178     GST_LOG_OBJECT (self, "kicking src STREAM from thread %p", \
179           g_thread_self ()); \
180     if (self->priv->aggregate_id) \
181       gst_clock_id_unschedule (self->priv->aggregate_id); \
182     self->priv->n_kicks++; \
183     SRC_STREAM_BROADCAST (self); \
184     SRC_STREAM_UNLOCK (self); \
185   } while (0)
186
187 struct _GstAggregatorPadPrivate
188 {
189   gboolean pending_flush_start;
190   gboolean pending_flush_stop;
191   gboolean pending_eos;
192   gboolean flushing;
193
194   GMutex event_lock;
195   GCond event_cond;
196
197   GMutex stream_lock;
198 };
199
200 static gboolean
201 _aggpad_flush (GstAggregatorPad * aggpad, GstAggregator * agg)
202 {
203   GstAggregatorPadClass *klass = GST_AGGREGATOR_PAD_GET_CLASS (aggpad);
204
205   aggpad->eos = FALSE;
206   aggpad->priv->flushing = FALSE;
207
208   if (klass->flush)
209     return klass->flush (aggpad, agg);
210
211   return TRUE;
212 }
213
214 /*************************************
215  * GstAggregator implementation  *
216  *************************************/
217 static GstElementClass *aggregator_parent_class = NULL;
218
219 struct _GstAggregatorPrivate
220 {
221   gint padcount;
222
223   /* Our state is >= PAUSED */
224   gboolean running;
225
226
227   gint seqnum;
228   gboolean send_stream_start;
229   gboolean send_segment;
230   gboolean flush_seeking;
231   gboolean pending_flush_start;
232   gboolean send_eos;
233   GstFlowReturn flow_return;
234
235   GstCaps *srccaps;
236
237   GstTagList *tags;
238   gboolean tags_changed;
239
240   /* Lock to prevent two src setcaps from happening at the same time  */
241   GMutex setcaps_lock;
242
243   gboolean latency_live;
244   GstClockTime latency_min;
245   GstClockTime latency_max;
246
247   /* aggregate */
248   GstClockID aggregate_id;
249   gint n_kicks;
250   GMutex src_lock;
251   GCond src_cond;
252 };
253
254 typedef struct
255 {
256   GstEvent *event;
257   gboolean result;
258   gboolean flush;
259
260   gboolean one_actually_seeked;
261 } EventData;
262
263 #define DEFAULT_LATENCY        -1
264
265 enum
266 {
267   PROP_0,
268   PROP_LATENCY,
269   PROP_LAST
270 };
271
272 /**
273  * gst_aggregator_iterate_sinkpads:
274  * @self: The #GstAggregator
275  * @func: The function to call.
276  * @user_data: The data to pass to @func.
277  *
278  * Iterate the sinkpads of aggregator to call a function on them.
279  *
280  * This method guarantees that @func will be called only once for each
281  * sink pad.
282  */
283 gboolean
284 gst_aggregator_iterate_sinkpads (GstAggregator * self,
285     GstAggregatorPadForeachFunc func, gpointer user_data)
286 {
287   gboolean result = FALSE;
288   GstIterator *iter;
289   gboolean done = FALSE;
290   GValue item = { 0, };
291   GList *seen_pads = NULL;
292
293   iter = gst_element_iterate_sink_pads (GST_ELEMENT (self));
294
295   if (!iter)
296     goto no_iter;
297
298   while (!done) {
299     switch (gst_iterator_next (iter, &item)) {
300       case GST_ITERATOR_OK:
301       {
302         GstPad *pad;
303
304         pad = g_value_get_object (&item);
305
306         /* if already pushed, skip. FIXME, find something faster to tag pads */
307         if (pad == NULL || g_list_find (seen_pads, pad)) {
308           g_value_reset (&item);
309           break;
310         }
311
312         GST_LOG_OBJECT (self, "calling function on pad %s:%s",
313             GST_DEBUG_PAD_NAME (pad));
314         result = func (self, pad, user_data);
315
316         done = !result;
317
318         seen_pads = g_list_prepend (seen_pads, pad);
319
320         g_value_reset (&item);
321         break;
322       }
323       case GST_ITERATOR_RESYNC:
324         gst_iterator_resync (iter);
325         break;
326       case GST_ITERATOR_ERROR:
327         GST_ERROR_OBJECT (self,
328             "Could not iterate over internally linked pads");
329         done = TRUE;
330         break;
331       case GST_ITERATOR_DONE:
332         done = TRUE;
333         break;
334     }
335   }
336   g_value_unset (&item);
337   gst_iterator_free (iter);
338
339   if (seen_pads == NULL) {
340     GST_DEBUG_OBJECT (self, "No pad seen");
341     return FALSE;
342   }
343
344   g_list_free (seen_pads);
345
346 no_iter:
347   return result;
348 }
349
350 static inline gboolean
351 _check_all_pads_with_data_or_eos (GstAggregator * self,
352     GstAggregatorPad * aggpad, gpointer user_data)
353 {
354   if (aggpad->buffer || aggpad->eos) {
355     return TRUE;
356   }
357
358   GST_LOG_OBJECT (aggpad, "Not ready to be aggregated");
359
360   return FALSE;
361 }
362
363 static void
364 _reset_flow_values (GstAggregator * self)
365 {
366   self->priv->flow_return = GST_FLOW_FLUSHING;
367   self->priv->send_stream_start = TRUE;
368   self->priv->send_segment = TRUE;
369   gst_segment_init (&self->segment, GST_FORMAT_TIME);
370 }
371
372 static inline void
373 _push_mandatory_events (GstAggregator * self)
374 {
375   GstAggregatorPrivate *priv = self->priv;
376
377   if (g_atomic_int_get (&self->priv->send_stream_start)) {
378     gchar s_id[32];
379
380     GST_INFO_OBJECT (self, "pushing stream start");
381     /* stream-start (FIXME: create id based on input ids) */
382     g_snprintf (s_id, sizeof (s_id), "agg-%08x", g_random_int ());
383     if (!gst_pad_push_event (self->srcpad, gst_event_new_stream_start (s_id))) {
384       GST_WARNING_OBJECT (self->srcpad, "Sending stream start event failed");
385     }
386     g_atomic_int_set (&self->priv->send_stream_start, FALSE);
387   }
388
389   if (self->priv->srccaps) {
390
391     GST_INFO_OBJECT (self, "pushing caps: %" GST_PTR_FORMAT,
392         self->priv->srccaps);
393     if (!gst_pad_push_event (self->srcpad,
394             gst_event_new_caps (self->priv->srccaps))) {
395       GST_WARNING_OBJECT (self->srcpad, "Sending caps event failed");
396     }
397     gst_caps_unref (self->priv->srccaps);
398     self->priv->srccaps = NULL;
399   }
400
401   if (g_atomic_int_get (&self->priv->send_segment)) {
402     if (!g_atomic_int_get (&self->priv->flush_seeking)) {
403       GstEvent *segev = gst_event_new_segment (&self->segment);
404
405       if (!self->priv->seqnum)
406         self->priv->seqnum = gst_event_get_seqnum (segev);
407       else
408         gst_event_set_seqnum (segev, self->priv->seqnum);
409
410       GST_DEBUG_OBJECT (self, "pushing segment %" GST_PTR_FORMAT, segev);
411       gst_pad_push_event (self->srcpad, segev);
412       g_atomic_int_set (&self->priv->send_segment, FALSE);
413     }
414   }
415
416   if (priv->tags && priv->tags_changed) {
417     gst_pad_push_event (self->srcpad,
418         gst_event_new_tag (gst_tag_list_ref (priv->tags)));
419     priv->tags_changed = FALSE;
420   }
421 }
422
423 /**
424  * gst_aggregator_set_src_caps:
425  * @self: The #GstAggregator
426  * @caps: The #GstCaps to set on the src pad.
427  *
428  * Sets the caps to be used on the src pad.
429  */
430 void
431 gst_aggregator_set_src_caps (GstAggregator * self, GstCaps * caps)
432 {
433   GST_AGGREGATOR_SETCAPS_LOCK (self);
434   gst_caps_replace (&self->priv->srccaps, caps);
435   _push_mandatory_events (self);
436   GST_AGGREGATOR_SETCAPS_UNLOCK (self);
437 }
438
439 /**
440  * gst_aggregator_finish_buffer:
441  * @self: The #GstAggregator
442  * @buffer: the #GstBuffer to push.
443  *
444  * This method will take care of sending mandatory events before pushing
445  * the provided buffer.
446  */
447 GstFlowReturn
448 gst_aggregator_finish_buffer (GstAggregator * self, GstBuffer * buffer)
449 {
450   _push_mandatory_events (self);
451
452   if (!g_atomic_int_get (&self->priv->flush_seeking) &&
453       gst_pad_is_active (self->srcpad)) {
454     GST_TRACE_OBJECT (self, "pushing buffer %" GST_PTR_FORMAT, buffer);
455     return gst_pad_push (self->srcpad, buffer);
456   } else {
457     GST_INFO_OBJECT (self, "Not pushing (active: %i, flushing: %i)",
458         g_atomic_int_get (&self->priv->flush_seeking),
459         gst_pad_is_active (self->srcpad));
460     gst_buffer_unref (buffer);
461     return GST_FLOW_OK;
462   }
463 }
464
465 static void
466 _push_eos (GstAggregator * self)
467 {
468   GstEvent *event;
469   _push_mandatory_events (self);
470
471   self->priv->send_eos = FALSE;
472   event = gst_event_new_eos ();
473   gst_event_set_seqnum (event, self->priv->seqnum);
474   gst_pad_push_event (self->srcpad, event);
475 }
476
477 static GstClockTime
478 gst_aggregator_get_next_time (GstAggregator * self)
479 {
480   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
481
482   if (klass->get_next_time)
483     return klass->get_next_time (self);
484
485   return GST_CLOCK_TIME_NONE;
486 }
487
488 /* called with the src STREAM lock */
489 static gboolean
490 _wait_and_check (GstAggregator * self)
491 {
492   GstClockTime latency_max, latency_min;
493   GstClockTime start;
494   gboolean live;
495
496   gst_aggregator_get_latency (self, &live, &latency_min, &latency_max);
497
498   if (gst_aggregator_iterate_sinkpads (self,
499           (GstAggregatorPadForeachFunc) _check_all_pads_with_data_or_eos,
500           NULL)) {
501     GST_DEBUG_OBJECT (self, "all pads have data");
502     return TRUE;
503   }
504
505   SRC_STREAM_LOCK (self);
506   start = gst_aggregator_get_next_time (self);
507
508   if (!live || !GST_IS_CLOCK (GST_ELEMENT_CLOCK (self))
509       || !GST_CLOCK_TIME_IS_VALID (start)) {
510     while (self->priv->n_kicks <= 0)
511       SRC_STREAM_WAIT (self);
512     self->priv->n_kicks--;
513   } else {
514     GstClockTime time;
515     GstClockReturn status;
516
517     GST_DEBUG_OBJECT (self, "got subclass start time: %" GST_TIME_FORMAT,
518         GST_TIME_ARGS (start));
519
520     time = GST_ELEMENT_CAST (self)->base_time + start;
521
522     if (GST_CLOCK_TIME_IS_VALID (latency_max)) {
523       time += latency_max;
524     } else if (GST_CLOCK_TIME_IS_VALID (latency_min)) {
525       time += latency_min;
526     } else {
527       time += self->latency;
528     }
529
530     GST_DEBUG_OBJECT (self, "possibly waiting for clock to reach %"
531         GST_TIME_FORMAT " (base %" GST_TIME_FORMAT " start %" GST_TIME_FORMAT
532         " latency max %" GST_TIME_FORMAT " latency min %" GST_TIME_FORMAT
533         " current %" GST_TIME_FORMAT ")", GST_TIME_ARGS (time),
534         GST_TIME_ARGS (GST_ELEMENT_CAST (self)->base_time),
535         GST_TIME_ARGS (start), GST_TIME_ARGS (latency_max),
536         GST_TIME_ARGS (latency_min),
537         GST_TIME_ARGS (gst_clock_get_time (GST_ELEMENT_CLOCK (self))));
538
539     self->priv->aggregate_id =
540         gst_clock_new_single_shot_id (GST_ELEMENT_CLOCK (self), time);
541     SRC_STREAM_UNLOCK (self);
542
543     status = gst_clock_id_wait (self->priv->aggregate_id, NULL);
544
545     SRC_STREAM_LOCK (self);
546     if (self->priv->aggregate_id) {
547       gst_clock_id_unref (self->priv->aggregate_id);
548       self->priv->aggregate_id = NULL;
549     }
550     self->priv->n_kicks--;
551
552     GST_DEBUG_OBJECT (self, "clock returned %d", status);
553
554     /* we timed out */
555     if (status == GST_CLOCK_OK || status == GST_CLOCK_EARLY) {
556       SRC_STREAM_UNLOCK (self);
557       return TRUE;
558     }
559   }
560   SRC_STREAM_UNLOCK (self);
561
562   return gst_aggregator_iterate_sinkpads (self,
563       (GstAggregatorPadForeachFunc) _check_all_pads_with_data_or_eos, NULL);
564 }
565
566 static void
567 aggregate_func (GstAggregator * self)
568 {
569   GstAggregatorPrivate *priv = self->priv;
570   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
571
572   if (self->priv->running == FALSE) {
573     GST_DEBUG_OBJECT (self, "Not running anymore");
574     return;
575   }
576
577   GST_LOG_OBJECT (self, "Checking aggregate");
578   while (priv->send_eos && priv->running) {
579     if (!_wait_and_check (self))
580       continue;
581
582     GST_TRACE_OBJECT (self, "Actually aggregating!");
583
584     priv->flow_return = klass->aggregate (self);
585
586     if (priv->flow_return == GST_FLOW_EOS) {
587       _push_eos (self);
588     }
589
590     if (priv->flow_return == GST_FLOW_FLUSHING &&
591         g_atomic_int_get (&priv->flush_seeking))
592       priv->flow_return = GST_FLOW_OK;
593
594     GST_LOG_OBJECT (self, "flow return is %s",
595         gst_flow_get_name (priv->flow_return));
596
597     if (priv->flow_return != GST_FLOW_OK)
598       break;
599   }
600 }
601
602 static gboolean
603 _start (GstAggregator * self)
604 {
605   self->priv->running = TRUE;
606   self->priv->send_stream_start = TRUE;
607   self->priv->send_segment = TRUE;
608   self->priv->send_eos = TRUE;
609   self->priv->srccaps = NULL;
610   self->priv->flow_return = GST_FLOW_OK;
611
612   return TRUE;
613 }
614
615 static gboolean
616 _check_pending_flush_stop (GstAggregatorPad * pad)
617 {
618   return (!pad->priv->pending_flush_stop && !pad->priv->pending_flush_start);
619 }
620
621 static gboolean
622 _stop_srcpad_task (GstAggregator * self, GstEvent * flush_start)
623 {
624   gboolean res = TRUE;
625
626   GST_INFO_OBJECT (self, "%s srcpad task",
627       flush_start ? "Pausing" : "Stopping");
628
629   self->priv->running = FALSE;
630   KICK_SRC_THREAD (self);
631
632   if (flush_start) {
633     res = gst_pad_push_event (self->srcpad, flush_start);
634   }
635
636   gst_pad_stop_task (self->srcpad);
637   KICK_SRC_THREAD (self);
638
639   return res;
640 }
641
642 static void
643 _start_srcpad_task (GstAggregator * self)
644 {
645   GST_INFO_OBJECT (self, "Starting srcpad task");
646
647   self->priv->running = TRUE;
648   self->priv->n_kicks = 0;
649   gst_pad_start_task (GST_PAD (self->srcpad),
650       (GstTaskFunction) aggregate_func, self, NULL);
651 }
652
653 static GstFlowReturn
654 _flush (GstAggregator * self)
655 {
656   GstFlowReturn ret = GST_FLOW_OK;
657   GstAggregatorPrivate *priv = self->priv;
658   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (self);
659
660   GST_DEBUG_OBJECT (self, "Flushing everything");
661   g_atomic_int_set (&priv->send_segment, TRUE);
662   g_atomic_int_set (&priv->flush_seeking, FALSE);
663   g_atomic_int_set (&priv->tags_changed, FALSE);
664   if (klass->flush)
665     ret = klass->flush (self);
666
667   return ret;
668 }
669
670 static gboolean
671 _all_flush_stop_received (GstAggregator * self)
672 {
673   GList *tmp;
674   GstAggregatorPad *tmppad;
675
676   GST_OBJECT_LOCK (self);
677   for (tmp = GST_ELEMENT (self)->sinkpads; tmp; tmp = tmp->next) {
678     tmppad = (GstAggregatorPad *) tmp->data;
679
680     if (_check_pending_flush_stop (tmppad) == FALSE) {
681       GST_DEBUG_OBJECT (tmppad, "Is not last %i -- %i",
682           tmppad->priv->pending_flush_start, tmppad->priv->pending_flush_stop);
683       GST_OBJECT_UNLOCK (self);
684       return FALSE;
685     }
686   }
687   GST_OBJECT_UNLOCK (self);
688
689   return TRUE;
690 }
691
692 static void
693 _flush_start (GstAggregator * self, GstAggregatorPad * aggpad, GstEvent * event)
694 {
695   GstBuffer *tmpbuf;
696   GstAggregatorPrivate *priv = self->priv;
697   GstAggregatorPadPrivate *padpriv = aggpad->priv;
698
699   g_atomic_int_set (&aggpad->priv->flushing, TRUE);
700   /*  Remove pad buffer and wake up the streaming thread */
701   tmpbuf = gst_aggregator_pad_steal_buffer (aggpad);
702   gst_buffer_replace (&tmpbuf, NULL);
703   PAD_STREAM_LOCK (aggpad);
704   if (g_atomic_int_compare_and_exchange (&padpriv->pending_flush_start,
705           TRUE, FALSE) == TRUE) {
706     GST_DEBUG_OBJECT (aggpad, "Expecting FLUSH_STOP now");
707     g_atomic_int_set (&padpriv->pending_flush_stop, TRUE);
708   }
709
710   if (g_atomic_int_get (&priv->flush_seeking)) {
711     /* If flush_seeking we forward the first FLUSH_START */
712     if (g_atomic_int_compare_and_exchange (&priv->pending_flush_start,
713             TRUE, FALSE) == TRUE) {
714
715       GST_INFO_OBJECT (self, "Flushing, pausing srcpad task");
716       _stop_srcpad_task (self, event);
717       priv->flow_return = GST_FLOW_OK;
718
719       GST_INFO_OBJECT (self, "Getting STREAM_LOCK while seeking");
720       GST_PAD_STREAM_LOCK (self->srcpad);
721       GST_LOG_OBJECT (self, "GOT STREAM_LOCK");
722       event = NULL;
723     }
724   } else {
725     gst_event_unref (event);
726   }
727   PAD_STREAM_UNLOCK (aggpad);
728
729   tmpbuf = gst_aggregator_pad_steal_buffer (aggpad);
730   gst_buffer_replace (&tmpbuf, NULL);
731 }
732
733 /* GstAggregator vmethods default implementations */
734 static gboolean
735 _sink_event (GstAggregator * self, GstAggregatorPad * aggpad, GstEvent * event)
736 {
737   gboolean res = TRUE;
738   GstPad *pad = GST_PAD (aggpad);
739   GstAggregatorPrivate *priv = self->priv;
740
741   switch (GST_EVENT_TYPE (event)) {
742     case GST_EVENT_FLUSH_START:
743     {
744       _flush_start (self, aggpad, event);
745       /* We forward only in one case: right after flush_seeking */
746       event = NULL;
747       goto eat;
748     }
749     case GST_EVENT_FLUSH_STOP:
750     {
751       GST_DEBUG_OBJECT (aggpad, "Got FLUSH_STOP");
752
753       _aggpad_flush (aggpad, self);
754       if (g_atomic_int_get (&priv->flush_seeking)) {
755         g_atomic_int_set (&aggpad->priv->pending_flush_stop, FALSE);
756
757         if (g_atomic_int_get (&priv->flush_seeking)) {
758           if (_all_flush_stop_received (self)) {
759             /* That means we received FLUSH_STOP/FLUSH_STOP on
760              * all sinkpads -- Seeking is Done... sending FLUSH_STOP */
761             _flush (self);
762             gst_pad_push_event (self->srcpad, event);
763             priv->send_eos = TRUE;
764             event = NULL;
765             KICK_SRC_THREAD (self);
766
767             GST_INFO_OBJECT (self, "Releasing source pad STREAM_LOCK");
768             GST_PAD_STREAM_UNLOCK (self->srcpad);
769             _start_srcpad_task (self);
770           }
771         }
772       }
773
774       /* We never forward the event */
775       goto eat;
776     }
777     case GST_EVENT_EOS:
778     {
779       GST_DEBUG_OBJECT (aggpad, "EOS");
780
781       /* We still have a buffer, and we don't want the subclass to have to
782        * check for it. Mark pending_eos, eos will be set when steal_buffer is
783        * called
784        */
785       PAD_LOCK_EVENT (aggpad);
786       if (!aggpad->buffer) {
787         aggpad->eos = TRUE;
788       } else {
789         aggpad->priv->pending_eos = TRUE;
790       }
791       PAD_UNLOCK_EVENT (aggpad);
792
793       KICK_SRC_THREAD (self);
794       goto eat;
795     }
796     case GST_EVENT_SEGMENT:
797     {
798       PAD_LOCK_EVENT (aggpad);
799       gst_event_copy_segment (event, &aggpad->segment);
800       self->priv->seqnum = gst_event_get_seqnum (event);
801       PAD_UNLOCK_EVENT (aggpad);
802       goto eat;
803     }
804     case GST_EVENT_STREAM_START:
805     {
806       goto eat;
807     }
808     case GST_EVENT_TAG:
809     {
810       GstTagList *tags;
811
812       gst_event_parse_tag (event, &tags);
813
814       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
815         gst_aggregator_merge_tags (self, tags, GST_TAG_MERGE_REPLACE);
816         gst_event_unref (event);
817         event = NULL;
818         goto eat;
819       }
820       break;
821     }
822     default:
823     {
824       break;
825     }
826   }
827
828   GST_DEBUG_OBJECT (pad, "Forwarding event: %" GST_PTR_FORMAT, event);
829   return gst_pad_event_default (pad, GST_OBJECT (self), event);
830
831 eat:
832   GST_DEBUG_OBJECT (pad, "Eating event: %" GST_PTR_FORMAT, event);
833   if (event)
834     gst_event_unref (event);
835
836   return res;
837 }
838
839 static gboolean
840 _stop_pad (GstAggregator * self, GstAggregatorPad * pad, gpointer unused_udata)
841 {
842   _aggpad_flush (pad, self);
843
844   return TRUE;
845 }
846
847 static gboolean
848 _stop (GstAggregator * agg)
849 {
850   _reset_flow_values (agg);
851
852   gst_aggregator_iterate_sinkpads (agg,
853       (GstAggregatorPadForeachFunc) _stop_pad, NULL);
854
855   if (agg->priv->tags)
856     gst_tag_list_unref (agg->priv->tags);
857   agg->priv->tags = NULL;
858
859   return TRUE;
860 }
861
862 /* GstElement vmethods implementations */
863 static GstStateChangeReturn
864 _change_state (GstElement * element, GstStateChange transition)
865 {
866   GstStateChangeReturn ret;
867   GstAggregator *self = GST_AGGREGATOR (element);
868   GstAggregatorClass *agg_class = GST_AGGREGATOR_GET_CLASS (self);
869
870
871   switch (transition) {
872     case GST_STATE_CHANGE_READY_TO_PAUSED:
873       agg_class->start (self);
874       break;
875     default:
876       break;
877   }
878
879   if ((ret =
880           GST_ELEMENT_CLASS (aggregator_parent_class)->change_state (element,
881               transition)) == GST_STATE_CHANGE_FAILURE)
882     goto failure;
883
884
885   switch (transition) {
886     case GST_STATE_CHANGE_PAUSED_TO_READY:
887       agg_class->stop (self);
888       break;
889     default:
890       break;
891   }
892
893   return ret;
894
895 failure:
896   {
897     GST_ERROR_OBJECT (element, "parent failed state change");
898     return ret;
899   }
900 }
901
902 static void
903 _release_pad (GstElement * element, GstPad * pad)
904 {
905   GstAggregator *self = GST_AGGREGATOR (element);
906   GstBuffer *tmpbuf;
907
908   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
909
910   GST_INFO_OBJECT (pad, "Removing pad");
911
912   g_atomic_int_set (&aggpad->priv->flushing, TRUE);
913   tmpbuf = gst_aggregator_pad_steal_buffer (aggpad);
914   gst_buffer_replace (&tmpbuf, NULL);
915   gst_element_remove_pad (element, pad);
916
917   KICK_SRC_THREAD (self);
918 }
919
920 static GstPad *
921 _request_new_pad (GstElement * element,
922     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
923 {
924   GstAggregator *self;
925   GstAggregatorPad *agg_pad;
926
927   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
928   GstAggregatorPrivate *priv = GST_AGGREGATOR (element)->priv;
929
930   self = GST_AGGREGATOR (element);
931
932   if (templ == gst_element_class_get_pad_template (klass, "sink_%u")) {
933     gint serial = 0;
934     gchar *name = NULL;
935
936     GST_OBJECT_LOCK (element);
937     if (req_name == NULL || strlen (req_name) < 6
938         || !g_str_has_prefix (req_name, "sink_")) {
939       /* no name given when requesting the pad, use next available int */
940       priv->padcount++;
941     } else {
942       /* parse serial number from requested padname */
943       serial = g_ascii_strtoull (&req_name[5], NULL, 10);
944       if (serial >= priv->padcount)
945         priv->padcount = serial;
946     }
947
948     name = g_strdup_printf ("sink_%u", priv->padcount);
949     agg_pad = g_object_new (GST_AGGREGATOR_GET_CLASS (self)->sinkpads_type,
950         "name", name, "direction", GST_PAD_SINK, "template", templ, NULL);
951     g_free (name);
952
953     GST_OBJECT_UNLOCK (element);
954
955   } else {
956     return NULL;
957   }
958
959   GST_DEBUG_OBJECT (element, "Adding pad %s", GST_PAD_NAME (agg_pad));
960
961   if (priv->running)
962     gst_pad_set_active (GST_PAD (agg_pad), TRUE);
963
964   /* add the pad to the element */
965   gst_element_add_pad (element, GST_PAD (agg_pad));
966
967   return GST_PAD (agg_pad);
968 }
969
970 typedef struct
971 {
972   GstClockTime min, max;
973   gboolean live;
974 } LatencyData;
975
976 static gboolean
977 _latency_query (GstAggregator * self, GstPad * pad, gpointer user_data)
978 {
979   LatencyData *data = user_data;
980   GstClockTime min, max;
981   GstQuery *query;
982   gboolean live, res;
983
984   query = gst_query_new_latency ();
985   res = gst_pad_peer_query (pad, query);
986
987   if (res) {
988     gst_query_parse_latency (query, &live, &min, &max);
989
990     GST_LOG_OBJECT (self, "got latency live:%s min:%" G_GINT64_FORMAT
991         " max:%" G_GINT64_FORMAT, live ? "true" : "false", min, max);
992
993     if (min > data->min)
994       data->min = min;
995
996     if (max != GST_CLOCK_TIME_NONE &&
997         ((data->max != GST_CLOCK_TIME_NONE && max < data->max) ||
998             (data->max == GST_CLOCK_TIME_NONE)))
999       data->max = max;
1000
1001     data->live |= live;
1002   }
1003
1004   gst_query_unref (query);
1005
1006   return TRUE;
1007 }
1008
1009 /**
1010  * gst_aggregator_get_latency:
1011  * @self: a #GstAggregator
1012  * @live: (out) (allow-none): whether @self is live
1013  * @min_latency: (out) (allow-none): the configured minimum latency of @self
1014  * @max_latency: (out) (allow-none): the configured maximum latency of @self
1015  *
1016  * Retreives the latency values reported by @self in response to the latency
1017  * query.
1018  *
1019  * Typically only called by subclasses.
1020  */
1021 void
1022 gst_aggregator_get_latency (GstAggregator * self, gboolean * live,
1023     GstClockTime * min_latency, GstClockTime * max_latency)
1024 {
1025   GstClockTime min, max;
1026
1027   g_return_if_fail (GST_IS_AGGREGATOR (self));
1028
1029   min = self->priv->latency_min;
1030   max = self->priv->latency_max;
1031
1032   if (GST_CLOCK_TIME_IS_VALID (self->latency)) {
1033     if (GST_CLOCK_TIME_IS_VALID (min))
1034       min += self->latency;
1035     if (GST_CLOCK_TIME_IS_VALID (max))
1036       max += self->latency;
1037   }
1038
1039   if (live)
1040     *live = self->priv->latency_live;
1041   if (min_latency)
1042     *min_latency = min;
1043   if (max_latency)
1044     *max_latency = max;
1045 }
1046
1047 static gboolean
1048 gst_aggregator_query_latency (GstAggregator * self, GstQuery * query)
1049 {
1050   LatencyData data;
1051
1052   data.min = 0;
1053   data.max = GST_CLOCK_TIME_NONE;
1054   data.live = FALSE;
1055
1056   /* query upstream's latency */
1057   gst_aggregator_iterate_sinkpads (self,
1058       (GstAggregatorPadForeachFunc) _latency_query, &data);
1059
1060   if (data.live && GST_CLOCK_TIME_IS_VALID (self->latency) &&
1061       self->latency > data.max) {
1062     GST_ELEMENT_WARNING (self, CORE, NEGOTIATION,
1063         ("%s", "Latency too big"),
1064         ("The requested latency value is too big for the current pipeline.  "
1065             "Limiting to %" G_GINT64_FORMAT, data.max));
1066     self->latency = data.max;
1067   }
1068
1069   self->priv->latency_live = data.live;
1070   self->priv->latency_min = data.min;
1071   self->priv->latency_max = data.max;
1072
1073   /* add our own */
1074   if (GST_CLOCK_TIME_IS_VALID (self->latency)) {
1075     if (GST_CLOCK_TIME_IS_VALID (data.min))
1076       data.min += self->latency;
1077     if (GST_CLOCK_TIME_IS_VALID (data.max))
1078       data.max += self->latency;
1079   }
1080
1081   GST_DEBUG_OBJECT (self, "configured latency live:%s min:%" G_GINT64_FORMAT
1082       " max:%" G_GINT64_FORMAT, data.live ? "true" : "false", data.min,
1083       data.max);
1084
1085   gst_query_set_latency (query, data.live, data.min, data.max);
1086
1087   return TRUE;
1088 }
1089
1090 static gboolean
1091 _send_event (GstElement * element, GstEvent * event)
1092 {
1093   GstAggregator *self = GST_AGGREGATOR (element);
1094
1095   GST_STATE_LOCK (element);
1096   if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK &&
1097       GST_STATE (element) < GST_STATE_PAUSED) {
1098     gdouble rate;
1099     GstFormat fmt;
1100     GstSeekFlags flags;
1101     GstSeekType start_type, stop_type;
1102     gint64 start, stop;
1103
1104     gst_event_parse_seek (event, &rate, &fmt, &flags, &start_type,
1105         &start, &stop_type, &stop);
1106     gst_segment_do_seek (&self->segment, rate, fmt, flags, start_type, start,
1107         stop_type, stop, NULL);
1108
1109     self->priv->seqnum = gst_event_get_seqnum (event);
1110     GST_DEBUG_OBJECT (element, "Storing segment %" GST_PTR_FORMAT, event);
1111   }
1112   GST_STATE_UNLOCK (element);
1113
1114
1115   return GST_ELEMENT_CLASS (aggregator_parent_class)->send_event (element,
1116       event);
1117 }
1118
1119 static gboolean
1120 _src_query (GstAggregator * self, GstQuery * query)
1121 {
1122   gboolean res = TRUE;
1123
1124   switch (GST_QUERY_TYPE (query)) {
1125     case GST_QUERY_SEEKING:
1126     {
1127       GstFormat format;
1128
1129       /* don't pass it along as some (file)sink might claim it does
1130        * whereas with a collectpads in between that will not likely work */
1131       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
1132       gst_query_set_seeking (query, format, FALSE, 0, -1);
1133       res = TRUE;
1134
1135       goto discard;
1136     }
1137     case GST_QUERY_LATENCY:
1138     {
1139       return gst_aggregator_query_latency (self, query);
1140     }
1141     default:
1142       break;
1143   }
1144
1145   return gst_pad_query_default (self->srcpad, GST_OBJECT (self), query);
1146
1147 discard:
1148   return res;
1149 }
1150
1151 static gboolean
1152 event_forward_func (GstPad * pad, EventData * evdata)
1153 {
1154   gboolean ret = TRUE;
1155   GstPad *peer = gst_pad_get_peer (pad);
1156   GstAggregatorPadPrivate *padpriv = GST_AGGREGATOR_PAD (pad)->priv;
1157
1158   if (peer) {
1159     ret = gst_pad_send_event (peer, gst_event_ref (evdata->event));
1160     GST_DEBUG_OBJECT (pad, "return of event push is %d", ret);
1161     gst_object_unref (peer);
1162   }
1163
1164   if (ret == FALSE) {
1165     if (GST_EVENT_TYPE (evdata->event) == GST_EVENT_SEEK)
1166       GST_ERROR_OBJECT (pad, "Event %" GST_PTR_FORMAT " failed", evdata->event);
1167
1168     if (GST_EVENT_TYPE (evdata->event) == GST_EVENT_SEEK) {
1169       GstQuery *seeking = gst_query_new_seeking (GST_FORMAT_TIME);
1170
1171       if (gst_pad_query (peer, seeking)) {
1172         gboolean seekable;
1173
1174         gst_query_parse_seeking (seeking, NULL, &seekable, NULL, NULL);
1175
1176         if (seekable == FALSE) {
1177           GST_INFO_OBJECT (pad,
1178               "Source not seekable, We failed but it does not matter!");
1179
1180           ret = TRUE;
1181         }
1182       } else {
1183         GST_ERROR_OBJECT (pad, "Query seeking FAILED");
1184       }
1185     }
1186
1187     if (evdata->flush) {
1188       padpriv->pending_flush_start = FALSE;
1189       padpriv->pending_flush_stop = FALSE;
1190     }
1191   } else {
1192     evdata->one_actually_seeked = TRUE;
1193   }
1194
1195   evdata->result &= ret;
1196
1197   /* Always send to all pads */
1198   return FALSE;
1199 }
1200
1201 static gboolean
1202 _set_flush_pending (GstAggregator * self, GstAggregatorPad * pad,
1203     gpointer udata)
1204 {
1205   pad->priv->pending_flush_start = TRUE;
1206   pad->priv->pending_flush_stop = FALSE;
1207
1208   return TRUE;
1209 }
1210
1211 static EventData
1212 _forward_event_to_all_sinkpads (GstAggregator * self, GstEvent * event,
1213     gboolean flush)
1214 {
1215   EventData evdata;
1216
1217   evdata.event = event;
1218   evdata.result = TRUE;
1219   evdata.flush = flush;
1220   evdata.one_actually_seeked = FALSE;
1221
1222   /* We first need to set all pads as flushing in a first pass
1223    * as flush_start flush_stop is sometimes sent synchronously
1224    * while we send the seek event */
1225   if (flush)
1226     gst_aggregator_iterate_sinkpads (self,
1227         (GstAggregatorPadForeachFunc) _set_flush_pending, NULL);
1228   gst_pad_forward (self->srcpad, (GstPadForwardFunction) event_forward_func,
1229       &evdata);
1230
1231   gst_event_unref (event);
1232
1233   return evdata;
1234 }
1235
1236 static gboolean
1237 _do_seek (GstAggregator * self, GstEvent * event)
1238 {
1239   gdouble rate;
1240   GstFormat fmt;
1241   GstSeekFlags flags;
1242   GstSeekType start_type, stop_type;
1243   gint64 start, stop;
1244   gboolean flush;
1245   EventData evdata;
1246   GstAggregatorPrivate *priv = self->priv;
1247
1248   gst_event_parse_seek (event, &rate, &fmt, &flags, &start_type,
1249       &start, &stop_type, &stop);
1250
1251   GST_INFO_OBJECT (self, "starting SEEK");
1252
1253   flush = flags & GST_SEEK_FLAG_FLUSH;
1254
1255   if (flush) {
1256     g_atomic_int_set (&priv->pending_flush_start, TRUE);
1257     g_atomic_int_set (&priv->flush_seeking, TRUE);
1258   }
1259
1260   gst_segment_do_seek (&self->segment, rate, fmt, flags, start_type, start,
1261       stop_type, stop, NULL);
1262
1263   /* forward the seek upstream */
1264   evdata = _forward_event_to_all_sinkpads (self, event, flush);
1265   event = NULL;
1266
1267   if (!evdata.result || !evdata.one_actually_seeked) {
1268     g_atomic_int_set (&priv->flush_seeking, FALSE);
1269     g_atomic_int_set (&priv->pending_flush_start, FALSE);
1270   }
1271
1272   GST_INFO_OBJECT (self, "seek done, result: %d", evdata.result);
1273
1274   return evdata.result;
1275 }
1276
1277 static gboolean
1278 _src_event (GstAggregator * self, GstEvent * event)
1279 {
1280   EventData evdata;
1281   gboolean res = TRUE;
1282
1283   switch (GST_EVENT_TYPE (event)) {
1284     case GST_EVENT_SEEK:
1285     {
1286       gst_event_ref (event);
1287       res = _do_seek (self, event);
1288       gst_event_unref (event);
1289       event = NULL;
1290       goto done;
1291     }
1292     case GST_EVENT_NAVIGATION:
1293     {
1294       /* navigation is rather pointless. */
1295       res = FALSE;
1296       gst_event_unref (event);
1297       goto done;
1298     }
1299     default:
1300     {
1301       break;
1302     }
1303   }
1304
1305   evdata = _forward_event_to_all_sinkpads (self, event, FALSE);
1306   res = evdata.result;
1307
1308 done:
1309   return res;
1310 }
1311
1312 static gboolean
1313 src_event_func (GstPad * pad, GstObject * parent, GstEvent * event)
1314 {
1315   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1316
1317   return klass->src_event (GST_AGGREGATOR (parent), event);
1318 }
1319
1320 static gboolean
1321 src_query_func (GstPad * pad, GstObject * parent, GstQuery * query)
1322 {
1323   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1324
1325   return klass->src_query (GST_AGGREGATOR (parent), query);
1326 }
1327
1328 static gboolean
1329 src_activate_mode (GstPad * pad,
1330     GstObject * parent, GstPadMode mode, gboolean active)
1331 {
1332   GstAggregator *self = GST_AGGREGATOR (parent);
1333   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1334
1335   if (klass->src_activate) {
1336     if (klass->src_activate (self, mode, active) == FALSE) {
1337       return FALSE;
1338     }
1339   }
1340
1341   if (active == TRUE) {
1342     switch (mode) {
1343       case GST_PAD_MODE_PUSH:
1344       {
1345         GST_INFO_OBJECT (pad, "Activating pad!");
1346         _start_srcpad_task (self);
1347         return TRUE;
1348       }
1349       default:
1350       {
1351         GST_ERROR_OBJECT (pad, "Only supported mode is PUSH");
1352         return FALSE;
1353       }
1354     }
1355   }
1356
1357   /* deactivating */
1358   GST_INFO_OBJECT (self, "Deactivating srcpad");
1359   _stop_srcpad_task (self, FALSE);
1360
1361   return TRUE;
1362 }
1363
1364 static gboolean
1365 _sink_query (GstAggregator * self, GstAggregatorPad * aggpad, GstQuery * query)
1366 {
1367   GstPad *pad = GST_PAD (aggpad);
1368
1369   return gst_pad_query_default (pad, GST_OBJECT (self), query);
1370 }
1371
1372 static void
1373 gst_aggregator_finalize (GObject * object)
1374 {
1375   GstAggregator *self = (GstAggregator *) object;
1376
1377   gst_object_unref (self->clock);
1378   g_mutex_clear (&self->priv->setcaps_lock);
1379   g_mutex_clear (&self->priv->src_lock);
1380   g_cond_clear (&self->priv->src_cond);
1381
1382   G_OBJECT_CLASS (aggregator_parent_class)->finalize (object);
1383 }
1384
1385 static void
1386 gst_aggregator_dispose (GObject * object)
1387 {
1388   G_OBJECT_CLASS (aggregator_parent_class)->dispose (object);
1389 }
1390
1391 /*
1392  * gst_aggregator_set_latency_property:
1393  * @agg: a #GstAggregator
1394  * @latency: the new latency value.
1395  *
1396  * Sets the new latency value to @latency. This value is used to limit the
1397  * amount of time a pad waits for data to appear before considering the pad
1398  * as unresponsive.
1399  */
1400 static void
1401 gst_aggregator_set_latency_property (GstAggregator * self, gint64 latency)
1402 {
1403   g_return_if_fail (GST_IS_AGGREGATOR (self));
1404
1405   GST_OBJECT_LOCK (self);
1406
1407   if (self->priv->latency_live && self->priv->latency_max != 0 &&
1408       GST_CLOCK_TIME_IS_VALID (latency) && latency > self->priv->latency_max) {
1409     GST_ELEMENT_WARNING (self, CORE, NEGOTIATION,
1410         ("%s", "Latency too big"),
1411         ("The requested latency value is too big for the latency in the "
1412             "current pipeline.  Limiting to %" G_GINT64_FORMAT,
1413             self->priv->latency_max));
1414     latency = self->priv->latency_max;
1415   }
1416
1417   self->latency = latency;
1418   GST_OBJECT_UNLOCK (self);
1419 }
1420
1421 /*
1422  * gst_aggregator_get_latency_property:
1423  * @agg: a #GstAggregator
1424  *
1425  * Gets the latency value. See gst_aggregator_set_latency for
1426  * more details.
1427  *
1428  * Returns: The time in nanoseconds to wait for data to arrive on a sink pad 
1429  * before a pad is deemed unresponsive. A value of -1 means an
1430  * unlimited time.
1431  */
1432 static gint64
1433 gst_aggregator_get_latency_property (GstAggregator * agg)
1434 {
1435   gint64 res;
1436
1437   g_return_val_if_fail (GST_IS_AGGREGATOR (agg), -1);
1438
1439   GST_OBJECT_LOCK (agg);
1440   res = agg->latency;
1441   GST_OBJECT_UNLOCK (agg);
1442
1443   return res;
1444 }
1445
1446 static void
1447 gst_aggregator_set_property (GObject * object, guint prop_id,
1448     const GValue * value, GParamSpec * pspec)
1449 {
1450   GstAggregator *agg = GST_AGGREGATOR (object);
1451
1452   switch (prop_id) {
1453     case PROP_LATENCY:
1454       gst_aggregator_set_latency_property (agg, g_value_get_int64 (value));
1455       break;
1456     default:
1457       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1458       break;
1459   }
1460 }
1461
1462 static void
1463 gst_aggregator_get_property (GObject * object, guint prop_id,
1464     GValue * value, GParamSpec * pspec)
1465 {
1466   GstAggregator *agg = GST_AGGREGATOR (object);
1467
1468   switch (prop_id) {
1469     case PROP_LATENCY:
1470       g_value_set_int64 (value, gst_aggregator_get_latency_property (agg));
1471       break;
1472     default:
1473       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1474       break;
1475   }
1476 }
1477
1478 /* GObject vmethods implementations */
1479 static void
1480 gst_aggregator_class_init (GstAggregatorClass * klass)
1481 {
1482   GObjectClass *gobject_class = (GObjectClass *) klass;
1483   GstElementClass *gstelement_class = (GstElementClass *) klass;
1484
1485   aggregator_parent_class = g_type_class_peek_parent (klass);
1486   g_type_class_add_private (klass, sizeof (GstAggregatorPrivate));
1487
1488   GST_DEBUG_CATEGORY_INIT (aggregator_debug, "aggregator",
1489       GST_DEBUG_FG_MAGENTA, "GstAggregator");
1490
1491   klass->sinkpads_type = GST_TYPE_AGGREGATOR_PAD;
1492   klass->start = _start;
1493   klass->stop = _stop;
1494
1495   klass->sink_event = _sink_event;
1496   klass->sink_query = _sink_query;
1497
1498   klass->src_event = _src_event;
1499   klass->src_query = _src_query;
1500
1501   gstelement_class->request_new_pad = GST_DEBUG_FUNCPTR (_request_new_pad);
1502   gstelement_class->send_event = GST_DEBUG_FUNCPTR (_send_event);
1503   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (_release_pad);
1504   gstelement_class->change_state = GST_DEBUG_FUNCPTR (_change_state);
1505
1506   gobject_class->set_property = gst_aggregator_set_property;
1507   gobject_class->get_property = gst_aggregator_get_property;
1508   gobject_class->finalize = gst_aggregator_finalize;
1509   gobject_class->dispose = gst_aggregator_dispose;
1510
1511   g_object_class_install_property (gobject_class, PROP_LATENCY,
1512       g_param_spec_int64 ("latency", "Buffer latency",
1513           "Number of nanoseconds to wait for a buffer to arrive on a sink pad"
1514           "before the pad is deemed unresponsive (-1 unlimited)", -1,
1515           (G_MAXLONG == G_MAXINT64) ? G_MAXINT64 : (G_MAXLONG * GST_SECOND - 1),
1516           DEFAULT_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1517 }
1518
1519 static void
1520 gst_aggregator_init (GstAggregator * self, GstAggregatorClass * klass)
1521 {
1522   GstPadTemplate *pad_template;
1523   GstAggregatorPrivate *priv;
1524
1525   g_return_if_fail (klass->aggregate != NULL);
1526
1527   self->priv =
1528       G_TYPE_INSTANCE_GET_PRIVATE (self, GST_TYPE_AGGREGATOR,
1529       GstAggregatorPrivate);
1530
1531   priv = self->priv;
1532
1533   pad_template =
1534       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
1535   g_return_if_fail (pad_template != NULL);
1536
1537   priv->padcount = -1;
1538   priv->tags_changed = FALSE;
1539
1540   self->priv->latency_live = FALSE;
1541   self->priv->latency_min = 0;
1542   self->priv->latency_max = GST_CLOCK_TIME_NONE;
1543   _reset_flow_values (self);
1544
1545   self->srcpad = gst_pad_new_from_template (pad_template, "src");
1546
1547   gst_pad_set_event_function (self->srcpad,
1548       GST_DEBUG_FUNCPTR ((GstPadEventFunction) src_event_func));
1549   gst_pad_set_query_function (self->srcpad,
1550       GST_DEBUG_FUNCPTR ((GstPadQueryFunction) src_query_func));
1551   gst_pad_set_activatemode_function (self->srcpad,
1552       GST_DEBUG_FUNCPTR ((GstPadActivateModeFunction) src_activate_mode));
1553
1554   gst_element_add_pad (GST_ELEMENT (self), self->srcpad);
1555
1556   self->clock = gst_system_clock_obtain ();
1557   self->latency = -1;
1558
1559   g_mutex_init (&self->priv->setcaps_lock);
1560   g_mutex_init (&self->priv->src_lock);
1561   g_cond_init (&self->priv->src_cond);
1562 }
1563
1564 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
1565  * method to get to the padtemplates */
1566 GType
1567 gst_aggregator_get_type (void)
1568 {
1569   static volatile gsize type = 0;
1570
1571   if (g_once_init_enter (&type)) {
1572     GType _type;
1573     static const GTypeInfo info = {
1574       sizeof (GstAggregatorClass),
1575       NULL,
1576       NULL,
1577       (GClassInitFunc) gst_aggregator_class_init,
1578       NULL,
1579       NULL,
1580       sizeof (GstAggregator),
1581       0,
1582       (GInstanceInitFunc) gst_aggregator_init,
1583     };
1584
1585     _type = g_type_register_static (GST_TYPE_ELEMENT,
1586         "GstAggregator", &info, G_TYPE_FLAG_ABSTRACT);
1587     g_once_init_leave (&type, _type);
1588   }
1589   return type;
1590 }
1591
1592 static GstFlowReturn
1593 _chain (GstPad * pad, GstObject * object, GstBuffer * buffer)
1594 {
1595   GstBuffer *actual_buf = buffer;
1596   GstAggregator *self = GST_AGGREGATOR (object);
1597   GstAggregatorPrivate *priv = self->priv;
1598   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1599   GstAggregatorClass *aggclass = GST_AGGREGATOR_GET_CLASS (object);
1600
1601   GST_DEBUG_OBJECT (aggpad, "Start chaining a buffer %" GST_PTR_FORMAT, buffer);
1602
1603   PAD_STREAM_LOCK (aggpad);
1604
1605   if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE)
1606     goto flushing;
1607
1608   if (g_atomic_int_get (&aggpad->priv->pending_eos) == TRUE)
1609     goto eos;
1610
1611   PAD_LOCK_EVENT (aggpad);
1612
1613   while (aggpad->buffer && g_atomic_int_get (&aggpad->priv->flushing) == FALSE) {
1614     GST_DEBUG_OBJECT (aggpad, "Waiting for buffer to be consumed");
1615     PAD_WAIT_EVENT (aggpad);
1616   }
1617   PAD_UNLOCK_EVENT (aggpad);
1618
1619   if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE)
1620     goto flushing;
1621
1622   if (aggclass->clip) {
1623     aggclass->clip (self, aggpad, buffer, &actual_buf);
1624   }
1625
1626   PAD_LOCK_EVENT (aggpad);
1627   if (aggpad->buffer)
1628     gst_buffer_unref (aggpad->buffer);
1629   aggpad->buffer = actual_buf;
1630   PAD_UNLOCK_EVENT (aggpad);
1631   PAD_STREAM_UNLOCK (aggpad);
1632
1633   if (gst_aggregator_iterate_sinkpads (self,
1634           (GstAggregatorPadForeachFunc) _check_all_pads_with_data_or_eos, NULL))
1635     KICK_SRC_THREAD (self);
1636
1637   GST_DEBUG_OBJECT (aggpad, "Done chaining");
1638
1639   return priv->flow_return;
1640
1641 flushing:
1642   PAD_STREAM_UNLOCK (aggpad);
1643
1644   gst_buffer_unref (buffer);
1645   GST_DEBUG_OBJECT (aggpad, "We are flushing");
1646
1647   return GST_FLOW_FLUSHING;
1648
1649 eos:
1650   PAD_STREAM_UNLOCK (aggpad);
1651
1652   gst_buffer_unref (buffer);
1653   GST_DEBUG_OBJECT (pad, "We are EOS already...");
1654
1655   return GST_FLOW_EOS;
1656 }
1657
1658 static gboolean
1659 pad_query_func (GstPad * pad, GstObject * parent, GstQuery * query)
1660 {
1661   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1662   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1663
1664   if (GST_QUERY_IS_SERIALIZED (query)) {
1665     PAD_LOCK_EVENT (aggpad);
1666
1667     if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE) {
1668       PAD_UNLOCK_EVENT (aggpad);
1669       goto flushing;
1670     }
1671
1672     while (aggpad->buffer
1673         && g_atomic_int_get (&aggpad->priv->flushing) == FALSE) {
1674       GST_DEBUG_OBJECT (aggpad, "Waiting for buffer to be consumed");
1675       PAD_WAIT_EVENT (aggpad);
1676     }
1677     PAD_UNLOCK_EVENT (aggpad);
1678
1679     if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE)
1680       goto flushing;
1681   }
1682
1683   return klass->sink_query (GST_AGGREGATOR (parent),
1684       GST_AGGREGATOR_PAD (pad), query);
1685
1686 flushing:
1687   GST_DEBUG_OBJECT (aggpad, "Pad is flushing, dropping query");
1688   return FALSE;
1689 }
1690
1691 static gboolean
1692 pad_event_func (GstPad * pad, GstObject * parent, GstEvent * event)
1693 {
1694   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1695   GstAggregatorClass *klass = GST_AGGREGATOR_GET_CLASS (parent);
1696
1697   if (GST_EVENT_IS_SERIALIZED (event) && GST_EVENT_TYPE (event) != GST_EVENT_EOS
1698       && GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT_DONE) {
1699     PAD_LOCK_EVENT (aggpad);
1700
1701     if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE
1702         && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
1703       PAD_UNLOCK_EVENT (aggpad);
1704       goto flushing;
1705     }
1706
1707     while (aggpad->buffer
1708         && g_atomic_int_get (&aggpad->priv->flushing) == FALSE) {
1709       GST_DEBUG_OBJECT (aggpad, "Waiting for buffer to be consumed");
1710       PAD_WAIT_EVENT (aggpad);
1711     }
1712     PAD_UNLOCK_EVENT (aggpad);
1713
1714     if (g_atomic_int_get (&aggpad->priv->flushing) == TRUE
1715         && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP)
1716       goto flushing;
1717   }
1718
1719   return klass->sink_event (GST_AGGREGATOR (parent),
1720       GST_AGGREGATOR_PAD (pad), event);
1721
1722 flushing:
1723   GST_DEBUG_OBJECT (aggpad, "Pad is flushing, dropping event");
1724   if (GST_EVENT_IS_STICKY (event))
1725     gst_pad_store_sticky_event (pad, event);
1726   gst_event_unref (event);
1727   return FALSE;
1728 }
1729
1730 static gboolean
1731 pad_activate_mode_func (GstPad * pad,
1732     GstObject * parent, GstPadMode mode, gboolean active)
1733 {
1734   GstAggregatorPad *aggpad = GST_AGGREGATOR_PAD (pad);
1735
1736   if (active == FALSE) {
1737     PAD_LOCK_EVENT (aggpad);
1738     g_atomic_int_set (&aggpad->priv->flushing, TRUE);
1739     gst_buffer_replace (&aggpad->buffer, NULL);
1740     PAD_BROADCAST_EVENT (aggpad);
1741     PAD_UNLOCK_EVENT (aggpad);
1742   } else {
1743     g_atomic_int_set (&aggpad->priv->flushing, FALSE);
1744     PAD_LOCK_EVENT (aggpad);
1745     PAD_BROADCAST_EVENT (aggpad);
1746     PAD_UNLOCK_EVENT (aggpad);
1747   }
1748
1749   return TRUE;
1750 }
1751
1752 /***********************************
1753  * GstAggregatorPad implementation  *
1754  ************************************/
1755 static GstPadClass *aggregator_pad_parent_class = NULL;
1756 G_DEFINE_TYPE (GstAggregatorPad, gst_aggregator_pad, GST_TYPE_PAD);
1757
1758 static void
1759 _pad_constructed (GObject * object)
1760 {
1761   GstPad *pad = GST_PAD (object);
1762
1763   gst_pad_set_chain_function (pad,
1764       GST_DEBUG_FUNCPTR ((GstPadChainFunction) _chain));
1765   gst_pad_set_event_function (pad,
1766       GST_DEBUG_FUNCPTR ((GstPadEventFunction) pad_event_func));
1767   gst_pad_set_query_function (pad,
1768       GST_DEBUG_FUNCPTR ((GstPadQueryFunction) pad_query_func));
1769   gst_pad_set_activatemode_function (pad,
1770       GST_DEBUG_FUNCPTR ((GstPadActivateModeFunction) pad_activate_mode_func));
1771 }
1772
1773 static void
1774 gst_aggregator_pad_finalize (GObject * object)
1775 {
1776   GstAggregatorPad *pad = (GstAggregatorPad *) object;
1777
1778   g_mutex_clear (&pad->priv->event_lock);
1779   g_cond_clear (&pad->priv->event_cond);
1780   g_mutex_clear (&pad->priv->stream_lock);
1781
1782   G_OBJECT_CLASS (aggregator_pad_parent_class)->finalize (object);
1783 }
1784
1785 static void
1786 gst_aggregator_pad_dispose (GObject * object)
1787 {
1788   GstAggregatorPad *pad = (GstAggregatorPad *) object;
1789   GstBuffer *buf;
1790
1791   buf = gst_aggregator_pad_steal_buffer (pad);
1792   if (buf)
1793     gst_buffer_unref (buf);
1794
1795   G_OBJECT_CLASS (aggregator_pad_parent_class)->dispose (object);
1796 }
1797
1798 static void
1799 gst_aggregator_pad_class_init (GstAggregatorPadClass * klass)
1800 {
1801   GObjectClass *gobject_class = (GObjectClass *) klass;
1802
1803   aggregator_pad_parent_class = g_type_class_peek_parent (klass);
1804   g_type_class_add_private (klass, sizeof (GstAggregatorPadPrivate));
1805
1806   gobject_class->constructed = GST_DEBUG_FUNCPTR (_pad_constructed);
1807   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_aggregator_pad_finalize);
1808   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_aggregator_pad_dispose);
1809 }
1810
1811 static void
1812 gst_aggregator_pad_init (GstAggregatorPad * pad)
1813 {
1814   pad->priv =
1815       G_TYPE_INSTANCE_GET_PRIVATE (pad, GST_TYPE_AGGREGATOR_PAD,
1816       GstAggregatorPadPrivate);
1817
1818   pad->buffer = NULL;
1819   g_mutex_init (&pad->priv->event_lock);
1820   g_cond_init (&pad->priv->event_cond);
1821
1822   g_mutex_init (&pad->priv->stream_lock);
1823 }
1824
1825 /**
1826  * gst_aggregator_pad_steal_buffer:
1827  * @pad: the pad to get buffer from
1828  *
1829  * Steal the ref to the buffer currently queued in @pad.
1830  *
1831  * Returns: (transfer full): The buffer in @pad or NULL if no buffer was
1832  *   queued. You should unref the buffer after usage.
1833  */
1834 GstBuffer *
1835 gst_aggregator_pad_steal_buffer (GstAggregatorPad * pad)
1836 {
1837   GstBuffer *buffer = NULL;
1838
1839   PAD_LOCK_EVENT (pad);
1840   if (pad->buffer) {
1841     GST_TRACE_OBJECT (pad, "Consuming buffer");
1842     buffer = pad->buffer;
1843     pad->buffer = NULL;
1844     if (pad->priv->pending_eos) {
1845       pad->priv->pending_eos = FALSE;
1846       pad->eos = TRUE;
1847     }
1848     PAD_BROADCAST_EVENT (pad);
1849     GST_DEBUG_OBJECT (pad, "Consumed: %" GST_PTR_FORMAT, buffer);
1850   }
1851   PAD_UNLOCK_EVENT (pad);
1852
1853   return buffer;
1854 }
1855
1856 /**
1857  * gst_aggregator_pad_get_buffer:
1858  * @pad: the pad to get buffer from
1859  *
1860  * Returns: (transfer full): A reference to the buffer in @pad or
1861  * NULL if no buffer was queued. You should unref the buffer after
1862  * usage.
1863  */
1864 GstBuffer *
1865 gst_aggregator_pad_get_buffer (GstAggregatorPad * pad)
1866 {
1867   GstBuffer *buffer = NULL;
1868
1869   PAD_LOCK_EVENT (pad);
1870   if (pad->buffer)
1871     buffer = gst_buffer_ref (pad->buffer);
1872   PAD_UNLOCK_EVENT (pad);
1873
1874   return buffer;
1875 }
1876
1877 /**
1878  * gst_aggregator_merge_tags:
1879  * @self: a #GstAggregator
1880  * @tags: a #GstTagList to merge
1881  * @mode: the #GstTagMergeMode to use
1882  *
1883  * Adds tags to so-called pending tags, which will be processed
1884  * before pushing out data downstream.
1885  *
1886  * Note that this is provided for convenience, and the subclass is
1887  * not required to use this and can still do tag handling on its own.
1888  *
1889  * MT safe.
1890  */
1891 void
1892 gst_aggregator_merge_tags (GstAggregator * self,
1893     const GstTagList * tags, GstTagMergeMode mode)
1894 {
1895   GstTagList *otags;
1896
1897   g_return_if_fail (GST_IS_AGGREGATOR (self));
1898   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
1899
1900   /* FIXME Check if we can use OBJECT lock here! */
1901   GST_OBJECT_LOCK (self);
1902   if (tags)
1903     GST_DEBUG_OBJECT (self, "merging tags %" GST_PTR_FORMAT, tags);
1904   otags = self->priv->tags;
1905   self->priv->tags = gst_tag_list_merge (self->priv->tags, tags, mode);
1906   if (otags)
1907     gst_tag_list_unref (otags);
1908   self->priv->tags_changed = TRUE;
1909   GST_OBJECT_UNLOCK (self);
1910 }