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