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