collectpads: Add negative DTS support
[platform/upstream/gstreamer.git] / libs / gst / base / gstcollectpads.c
1 /* GStreamer
2  * Copyright (C) 2005 Wim Taymans <wim@fluendo.com>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sourceforge.net>
4  * Copyright (C) 2010 Sebastian Dröge <sebastian.droege@collabora.co.uk>
5  *
6  * gstcollectpads.c:
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /**
24  * SECTION:gstcollectpads
25  * @short_description: manages a set of pads that operate in collect mode
26  * @see_also:
27  *
28  * Manages a set of pads that operate in collect mode. This means that control
29  * is given to the manager of this object when all pads have data.
30  * <itemizedlist>
31  *   <listitem><para>
32  *     Collectpads are created with gst_collect_pads_new(). A callback should then
33  *     be installed with gst_collect_pads_set_function ().
34  *   </para></listitem>
35  *   <listitem><para>
36  *     Pads are added to the collection with gst_collect_pads_add_pad()/
37  *     gst_collect_pads_remove_pad(). The pad
38  *     has to be a sinkpad. The chain and event functions of the pad are
39  *     overridden. The element_private of the pad is used to store
40  *     private information for the collectpads.
41  *   </para></listitem>
42  *   <listitem><para>
43  *     For each pad, data is queued in the _chain function or by
44  *     performing a pull_range.
45  *   </para></listitem>
46  *   <listitem><para>
47  *     When data is queued on all pads in waiting mode, the callback function is called.
48  *   </para></listitem>
49  *   <listitem><para>
50  *     Data can be dequeued from the pad with the gst_collect_pads_pop() method.
51  *     One can peek at the data with the gst_collect_pads_peek() function.
52  *     These functions will return %NULL if the pad received an EOS event. When all
53  *     pads return %NULL from a gst_collect_pads_peek(), the element can emit an EOS
54  *     event itself.
55  *   </para></listitem>
56  *   <listitem><para>
57  *     Data can also be dequeued in byte units using the gst_collect_pads_available(),
58  *     gst_collect_pads_read_buffer() and gst_collect_pads_flush() calls.
59  *   </para></listitem>
60  *   <listitem><para>
61  *     Elements should call gst_collect_pads_start() and gst_collect_pads_stop() in
62  *     their state change functions to start and stop the processing of the collectpads.
63  *     The gst_collect_pads_stop() call should be called before calling the parent
64  *     element state change function in the PAUSED_TO_READY state change to ensure
65  *     no pad is blocked and the element can finish streaming.
66  *   </para></listitem>
67  *   <listitem><para>
68  *     gst_collect_pads_set_waiting() sets a pad to waiting or non-waiting mode.
69  *     CollectPads element is not waiting for data to be collected on non-waiting pads.
70  *     Thus these pads may but need not have data when the callback is called.
71  *     All pads are in waiting mode by default.
72  *   </para></listitem>
73  * </itemizedlist>
74  */
75
76 #ifdef HAVE_CONFIG_H
77 #  include "config.h"
78 #endif
79
80 #include <gst/gst_private.h>
81
82 #include "gstcollectpads.h"
83
84 #include "../../../gst/glib-compat-private.h"
85
86 GST_DEBUG_CATEGORY_STATIC (collect_pads_debug);
87 #define GST_CAT_DEFAULT collect_pads_debug
88
89 #define parent_class gst_collect_pads_parent_class
90 G_DEFINE_TYPE (GstCollectPads, gst_collect_pads, GST_TYPE_OBJECT);
91
92 struct _GstCollectDataPrivate
93 {
94   /* refcounting for struct, and destroy callback */
95   GstCollectDataDestroyNotify destroy_notify;
96   gint refcount;
97 };
98
99 struct _GstCollectPadsPrivate
100 {
101   /* with LOCK and/or STREAM_LOCK */
102   gboolean started;
103
104   /* with STREAM_LOCK */
105   guint32 cookie;               /* @data list cookie */
106   guint numpads;                /* number of pads in @data */
107   guint queuedpads;             /* number of pads with a buffer */
108   guint eospads;                /* number of pads that are EOS */
109   GstClockTime earliest_time;   /* Current earliest time */
110   GstCollectData *earliest_data;        /* Pad data for current earliest time */
111
112   /* with LOCK */
113   GSList *pad_list;             /* updated pad list */
114   guint32 pad_cookie;           /* updated cookie */
115
116   GstCollectPadsFunction func;  /* function and user_data for callback */
117   gpointer user_data;
118   GstCollectPadsBufferFunction buffer_func;     /* function and user_data for buffer callback */
119   gpointer buffer_user_data;
120   GstCollectPadsCompareFunction compare_func;
121   gpointer compare_user_data;
122   GstCollectPadsEventFunction event_func;       /* function and data for event callback */
123   gpointer event_user_data;
124   GstCollectPadsQueryFunction query_func;
125   gpointer query_user_data;
126   GstCollectPadsClipFunction clip_func;
127   gpointer clip_user_data;
128   GstCollectPadsFlushFunction flush_func;
129   gpointer flush_user_data;
130
131   /* no other lock needed */
132   GMutex evt_lock;              /* these make up sort of poor man's event signaling */
133   GCond evt_cond;
134   guint32 evt_cookie;
135
136   gboolean seeking;
137   gboolean pending_flush_start;
138   gboolean pending_flush_stop;
139 };
140
141 static void gst_collect_pads_clear (GstCollectPads * pads,
142     GstCollectData * data);
143 static GstFlowReturn gst_collect_pads_chain (GstPad * pad, GstObject * parent,
144     GstBuffer * buffer);
145 static gboolean gst_collect_pads_event (GstPad * pad, GstObject * parent,
146     GstEvent * event);
147 static gboolean gst_collect_pads_query (GstPad * pad, GstObject * parent,
148     GstQuery * query);
149 static void gst_collect_pads_finalize (GObject * object);
150 static GstFlowReturn gst_collect_pads_default_collected (GstCollectPads *
151     pads, gpointer user_data);
152 static gint gst_collect_pads_default_compare_func (GstCollectPads * pads,
153     GstCollectData * data1, GstClockTime timestamp1, GstCollectData * data2,
154     GstClockTime timestamp2, gpointer user_data);
155 static gboolean gst_collect_pads_recalculate_full (GstCollectPads * pads);
156 static void ref_data (GstCollectData * data);
157 static void unref_data (GstCollectData * data);
158
159 static gboolean gst_collect_pads_event_default_internal (GstCollectPads *
160     pads, GstCollectData * data, GstEvent * event, gpointer user_data);
161 static gboolean gst_collect_pads_query_default_internal (GstCollectPads *
162     pads, GstCollectData * data, GstQuery * query, gpointer user_data);
163
164
165 /* Some properties are protected by LOCK, others by STREAM_LOCK
166  * However, manipulating either of these partitions may require
167  * to signal/wake a _WAIT, so use a separate (sort of) event to prevent races
168  * Alternative implementations are possible, e.g. some low-level re-implementing
169  * of the 2 above locks to drop both of them atomically when going into _WAIT.
170  */
171 #define GST_COLLECT_PADS_GET_EVT_COND(pads) (&((GstCollectPads *)pads)->priv->evt_cond)
172 #define GST_COLLECT_PADS_GET_EVT_LOCK(pads) (&((GstCollectPads *)pads)->priv->evt_lock)
173 #define GST_COLLECT_PADS_EVT_WAIT(pads, cookie) G_STMT_START {    \
174   g_mutex_lock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));            \
175   /* should work unless a lot of event'ing and thread starvation */\
176   while (cookie == ((GstCollectPads *) pads)->priv->evt_cookie)         \
177     g_cond_wait (GST_COLLECT_PADS_GET_EVT_COND (pads),            \
178         GST_COLLECT_PADS_GET_EVT_LOCK (pads));                    \
179   cookie = ((GstCollectPads *) pads)->priv->evt_cookie;                 \
180   g_mutex_unlock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));          \
181 } G_STMT_END
182 #define GST_COLLECT_PADS_EVT_WAIT_TIMED(pads, cookie, timeout) G_STMT_START { \
183   GTimeVal __tv; \
184   \
185   g_get_current_time (&tv); \
186   g_time_val_add (&tv, timeout); \
187   \
188   g_mutex_lock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));            \
189   /* should work unless a lot of event'ing and thread starvation */\
190   while (cookie == ((GstCollectPads *) pads)->priv->evt_cookie)         \
191     g_cond_timed_wait (GST_COLLECT_PADS_GET_EVT_COND (pads),            \
192         GST_COLLECT_PADS_GET_EVT_LOCK (pads), &tv);                    \
193   cookie = ((GstCollectPads *) pads)->priv->evt_cookie;                 \
194   g_mutex_unlock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));          \
195 } G_STMT_END
196 #define GST_COLLECT_PADS_EVT_BROADCAST(pads) G_STMT_START {       \
197   g_mutex_lock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));            \
198   /* never mind wrap-around */                                     \
199   ++(((GstCollectPads *) pads)->priv->evt_cookie);                      \
200   g_cond_broadcast (GST_COLLECT_PADS_GET_EVT_COND (pads));        \
201   g_mutex_unlock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));          \
202 } G_STMT_END
203 #define GST_COLLECT_PADS_EVT_INIT(cookie) G_STMT_START {          \
204   g_mutex_lock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));            \
205   cookie = ((GstCollectPads *) pads)->priv->evt_cookie;                 \
206   g_mutex_unlock (GST_COLLECT_PADS_GET_EVT_LOCK (pads));          \
207 } G_STMT_END
208
209 static void
210 gst_collect_pads_class_init (GstCollectPadsClass * klass)
211 {
212   GObjectClass *gobject_class = (GObjectClass *) klass;
213
214   g_type_class_add_private (klass, sizeof (GstCollectPadsPrivate));
215
216   GST_DEBUG_CATEGORY_INIT (collect_pads_debug, "collectpads", 0,
217       "GstCollectPads");
218
219   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_collect_pads_finalize);
220 }
221
222 static void
223 gst_collect_pads_init (GstCollectPads * pads)
224 {
225   pads->priv =
226       G_TYPE_INSTANCE_GET_PRIVATE (pads, GST_TYPE_COLLECT_PADS,
227       GstCollectPadsPrivate);
228
229   pads->data = NULL;
230   pads->priv->cookie = 0;
231   pads->priv->numpads = 0;
232   pads->priv->queuedpads = 0;
233   pads->priv->eospads = 0;
234   pads->priv->started = FALSE;
235
236   g_rec_mutex_init (&pads->stream_lock);
237
238   pads->priv->func = gst_collect_pads_default_collected;
239   pads->priv->user_data = NULL;
240   pads->priv->event_func = NULL;
241   pads->priv->event_user_data = NULL;
242
243   /* members for default muxing */
244   pads->priv->buffer_func = NULL;
245   pads->priv->buffer_user_data = NULL;
246   pads->priv->compare_func = gst_collect_pads_default_compare_func;
247   pads->priv->compare_user_data = NULL;
248   pads->priv->earliest_data = NULL;
249   pads->priv->earliest_time = GST_CLOCK_TIME_NONE;
250
251   pads->priv->event_func = gst_collect_pads_event_default_internal;
252   pads->priv->query_func = gst_collect_pads_query_default_internal;
253
254   /* members to manage the pad list */
255   pads->priv->pad_cookie = 0;
256   pads->priv->pad_list = NULL;
257
258   /* members for event */
259   g_mutex_init (&pads->priv->evt_lock);
260   g_cond_init (&pads->priv->evt_cond);
261   pads->priv->evt_cookie = 0;
262
263   pads->priv->seeking = FALSE;
264   pads->priv->pending_flush_start = FALSE;
265   pads->priv->pending_flush_stop = FALSE;
266
267   /* clear floating flag */
268   gst_object_ref_sink (pads);
269 }
270
271 static void
272 gst_collect_pads_finalize (GObject * object)
273 {
274   GstCollectPads *pads = GST_COLLECT_PADS (object);
275
276   GST_DEBUG_OBJECT (object, "finalize");
277
278   g_rec_mutex_clear (&pads->stream_lock);
279
280   g_cond_clear (&pads->priv->evt_cond);
281   g_mutex_clear (&pads->priv->evt_lock);
282
283   /* Remove pads and free pads list */
284   g_slist_foreach (pads->priv->pad_list, (GFunc) unref_data, NULL);
285   g_slist_foreach (pads->data, (GFunc) unref_data, NULL);
286   g_slist_free (pads->data);
287   g_slist_free (pads->priv->pad_list);
288
289   G_OBJECT_CLASS (parent_class)->finalize (object);
290 }
291
292 /**
293  * gst_collect_pads_new:
294  *
295  * Create a new instance of #GstCollectPads.
296  *
297  * MT safe.
298  *
299  * Returns: (transfer full): a new #GstCollectPads, or %NULL in case of an error.
300  */
301 GstCollectPads *
302 gst_collect_pads_new (void)
303 {
304   GstCollectPads *newcoll;
305
306   newcoll = g_object_new (GST_TYPE_COLLECT_PADS, NULL);
307
308   return newcoll;
309 }
310
311 /* Must be called with GstObject lock! */
312 static void
313 gst_collect_pads_set_buffer_function_locked (GstCollectPads * pads,
314     GstCollectPadsBufferFunction func, gpointer user_data)
315 {
316   pads->priv->buffer_func = func;
317   pads->priv->buffer_user_data = user_data;
318 }
319
320 /**
321  * gst_collect_pads_set_buffer_function:
322  * @pads: the collectpads to use
323  * @func: the function to set
324  * @user_data: (closure): user data passed to the function
325  *
326  * Set the callback function and user data that will be called with
327  * the oldest buffer when all pads have been collected, or %NULL on EOS.
328  * If a buffer is passed, the callback owns a reference and must unref
329  * it.
330  *
331  * MT safe.
332  */
333 void
334 gst_collect_pads_set_buffer_function (GstCollectPads * pads,
335     GstCollectPadsBufferFunction func, gpointer user_data)
336 {
337   g_return_if_fail (pads != NULL);
338   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
339
340   GST_OBJECT_LOCK (pads);
341   gst_collect_pads_set_buffer_function_locked (pads, func, user_data);
342   GST_OBJECT_UNLOCK (pads);
343 }
344
345 /**
346  * gst_collect_pads_set_compare_function:
347  * @pads: the pads to use
348  * @func: the function to set
349  * @user_data: (closure): user data passed to the function
350  *
351  * Set the timestamp comparison function.
352  *
353  * MT safe.
354  */
355 /* NOTE allowing to change comparison seems not advisable;
356 no known use-case, and collaboration with default algorithm is unpredictable.
357 If custom compairing/operation is needed, just use a collect function of
358 your own */
359 void
360 gst_collect_pads_set_compare_function (GstCollectPads * pads,
361     GstCollectPadsCompareFunction func, gpointer user_data)
362 {
363   g_return_if_fail (pads != NULL);
364   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
365
366   GST_OBJECT_LOCK (pads);
367   pads->priv->compare_func = func;
368   pads->priv->compare_user_data = user_data;
369   GST_OBJECT_UNLOCK (pads);
370 }
371
372 /**
373  * gst_collect_pads_set_function:
374  * @pads: the collectpads to use
375  * @func: the function to set
376  * @user_data: user data passed to the function
377  *
378  * CollectPads provides a default collection algorithm that will determine
379  * the oldest buffer available on all of its pads, and then delegate
380  * to a configured callback.
381  * However, if circumstances are more complicated and/or more control
382  * is desired, this sets a callback that will be invoked instead when
383  * all the pads added to the collection have buffers queued.
384  * Evidently, this callback is not compatible with
385  * gst_collect_pads_set_buffer_function() callback.
386  * If this callback is set, the former will be unset.
387  *
388  * MT safe.
389  */
390 void
391 gst_collect_pads_set_function (GstCollectPads * pads,
392     GstCollectPadsFunction func, gpointer user_data)
393 {
394   g_return_if_fail (pads != NULL);
395   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
396
397   GST_OBJECT_LOCK (pads);
398   pads->priv->func = func;
399   pads->priv->user_data = user_data;
400   gst_collect_pads_set_buffer_function_locked (pads, NULL, NULL);
401   GST_OBJECT_UNLOCK (pads);
402 }
403
404 static void
405 ref_data (GstCollectData * data)
406 {
407   g_assert (data != NULL);
408
409   g_atomic_int_inc (&(data->priv->refcount));
410 }
411
412 static void
413 unref_data (GstCollectData * data)
414 {
415   g_assert (data != NULL);
416   g_assert (data->priv->refcount > 0);
417
418   if (!g_atomic_int_dec_and_test (&(data->priv->refcount)))
419     return;
420
421   if (data->priv->destroy_notify)
422     data->priv->destroy_notify (data);
423
424   g_object_unref (data->pad);
425   if (data->buffer) {
426     gst_buffer_unref (data->buffer);
427   }
428   g_free (data->priv);
429   g_free (data);
430 }
431
432 /**
433  * gst_collect_pads_set_event_function:
434  * @pads: the collectpads to use
435  * @func: the function to set
436  * @user_data: user data passed to the function
437  *
438  * Set the event callback function and user data that will be called when
439  * collectpads has received an event originating from one of the collected
440  * pads.  If the event being processed is a serialized one, this callback is
441  * called with @pads STREAM_LOCK held, otherwise not.  As this lock should be
442  * held when calling a number of CollectPads functions, it should be acquired
443  * if so (unusually) needed.
444  *
445  * MT safe.
446  */
447 void
448 gst_collect_pads_set_event_function (GstCollectPads * pads,
449     GstCollectPadsEventFunction func, gpointer user_data)
450 {
451   g_return_if_fail (pads != NULL);
452   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
453
454   GST_OBJECT_LOCK (pads);
455   pads->priv->event_func = func;
456   pads->priv->event_user_data = user_data;
457   GST_OBJECT_UNLOCK (pads);
458 }
459
460 /**
461  * gst_collect_pads_set_query_function:
462  * @pads: the collectpads to use
463  * @func: the function to set
464  * @user_data: user data passed to the function
465  *
466  * Set the query callback function and user data that will be called after
467  * collectpads has received a query originating from one of the collected
468  * pads.  If the query being processed is a serialized one, this callback is
469  * called with @pads STREAM_LOCK held, otherwise not.  As this lock should be
470  * held when calling a number of CollectPads functions, it should be acquired
471  * if so (unusually) needed.
472  *
473  * MT safe.
474  */
475 void
476 gst_collect_pads_set_query_function (GstCollectPads * pads,
477     GstCollectPadsQueryFunction func, gpointer user_data)
478 {
479   g_return_if_fail (pads != NULL);
480   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
481
482   GST_OBJECT_LOCK (pads);
483   pads->priv->query_func = func;
484   pads->priv->query_user_data = user_data;
485   GST_OBJECT_UNLOCK (pads);
486 }
487
488 /**
489 * gst_collect_pads_clip_running_time:
490 * @pads: the collectpads to use
491 * @cdata: collect data of corresponding pad
492 * @buf: buffer being clipped
493 * @outbuf: (allow-none): output buffer with running time, or NULL if clipped
494 * @user_data: user data (unused)
495 *
496 * Convenience clipping function that converts incoming buffer's timestamp
497 * to running time, or clips the buffer if outside configured segment.
498 *
499 * Since 1.6, this clipping function also sets the DTS parameter of the
500 * GstCollectData structure. This version of the running time DTS can be
501 * negative. G_MININT64 is used to indicate invalid value.
502 */
503 GstFlowReturn
504 gst_collect_pads_clip_running_time (GstCollectPads * pads,
505     GstCollectData * cdata, GstBuffer * buf, GstBuffer ** outbuf,
506     gpointer user_data)
507 {
508   GstClockTime time;
509
510   *outbuf = buf;
511   time = GST_BUFFER_PTS (buf);
512
513   /* invalid left alone and passed */
514   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (time))) {
515     time = gst_segment_to_running_time (&cdata->segment, GST_FORMAT_TIME, time);
516     if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time))) {
517       GST_DEBUG_OBJECT (cdata->pad, "clipping buffer on pad outside segment %"
518           GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
519       gst_buffer_unref (buf);
520       *outbuf = NULL;
521     } else {
522       GstClockTime buf_dts, abs_dts;
523       gint dts_sign;
524
525       GST_LOG_OBJECT (cdata->pad, "buffer pts %" GST_TIME_FORMAT " -> %"
526           GST_TIME_FORMAT " running time",
527           GST_TIME_ARGS (GST_BUFFER_PTS (buf)), GST_TIME_ARGS (time));
528       *outbuf = gst_buffer_make_writable (buf);
529       GST_BUFFER_PTS (*outbuf) = time;
530
531       dts_sign = gst_segment_to_running_time_full (&cdata->segment,
532           GST_FORMAT_TIME, GST_BUFFER_DTS (*outbuf), &abs_dts);
533       buf_dts = GST_BUFFER_DTS (*outbuf);
534       if (dts_sign > 0) {
535         GST_BUFFER_DTS (*outbuf) = abs_dts;
536         GST_COLLECT_PADS_DTS (cdata) = abs_dts;
537       } else if (dts_sign < 0) {
538         GST_BUFFER_DTS (*outbuf) = GST_CLOCK_TIME_NONE;
539         GST_COLLECT_PADS_DTS (cdata) = -((gint64) abs_dts);
540       } else {
541         GST_BUFFER_DTS (*outbuf) = GST_CLOCK_TIME_NONE;
542         GST_COLLECT_PADS_DTS (cdata) = GST_CLOCK_STIME_NONE;
543       }
544
545       GST_LOG_OBJECT (cdata->pad, "buffer dts %" GST_TIME_FORMAT " -> %"
546           GST_STIME_FORMAT " running time", GST_TIME_ARGS (buf_dts),
547           GST_STIME_ARGS (GST_COLLECT_PADS_DTS (cdata)));
548     }
549   }
550
551   return GST_FLOW_OK;
552 }
553
554 /**
555  * gst_collect_pads_set_clip_function:
556  * @pads: the collectpads to use
557  * @clipfunc: clip function to install
558  * @user_data: user data to pass to @clip_func
559  *
560  * Install a clipping function that is called right after a buffer is received
561  * on a pad managed by @pads. See #GstCollectPadsClipFunction for more info.
562  */
563 void
564 gst_collect_pads_set_clip_function (GstCollectPads * pads,
565     GstCollectPadsClipFunction clipfunc, gpointer user_data)
566 {
567   g_return_if_fail (pads != NULL);
568   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
569
570   pads->priv->clip_func = clipfunc;
571   pads->priv->clip_user_data = user_data;
572 }
573
574 /**
575  * gst_collect_pads_set_flush_function:
576  * @pads: the collectpads to use
577  * @func: flush function to install
578  * @user_data: user data to pass to @func
579  *
580  * Install a flush function that is called when the internal
581  * state of all pads should be flushed as part of flushing seek
582  * handling. See #GstCollectPadsFlushFunction for more info.
583  *
584  * Since: 1.4
585  */
586 void
587 gst_collect_pads_set_flush_function (GstCollectPads * pads,
588     GstCollectPadsFlushFunction func, gpointer user_data)
589 {
590   g_return_if_fail (pads != NULL);
591   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
592
593   pads->priv->flush_func = func;
594   pads->priv->flush_user_data = user_data;
595 }
596
597 /**
598  * gst_collect_pads_add_pad:
599  * @pads: the collectpads to use
600  * @pad: (transfer none): the pad to add
601  * @size: the size of the returned #GstCollectData structure
602  * @destroy_notify: (scope async): function to be called before the returned
603  *   #GstCollectData structure is freed
604  * @lock: whether to lock this pad in usual waiting state
605  *
606  * Add a pad to the collection of collect pads. The pad has to be
607  * a sinkpad. The refcount of the pad is incremented. Use
608  * gst_collect_pads_remove_pad() to remove the pad from the collection
609  * again.
610  *
611  * You specify a size for the returned #GstCollectData structure
612  * so that you can use it to store additional information.
613  *
614  * You can also specify a #GstCollectDataDestroyNotify that will be called
615  * just before the #GstCollectData structure is freed. It is passed the
616  * pointer to the structure and should free any custom memory and resources
617  * allocated for it.
618  *
619  * Keeping a pad locked in waiting state is only relevant when using
620  * the default collection algorithm (providing the oldest buffer).
621  * It ensures a buffer must be available on this pad for a collection
622  * to take place.  This is of typical use to a muxer element where
623  * non-subtitle streams should always be in waiting state,
624  * e.g. to assure that caps information is available on all these streams
625  * when initial headers have to be written.
626  *
627  * The pad will be automatically activated in push mode when @pads is
628  * started.
629  *
630  * MT safe.
631  *
632  * Returns: (nullable) (transfer none): a new #GstCollectData to identify the
633  *   new pad. Or %NULL if wrong parameters are supplied.
634  */
635 GstCollectData *
636 gst_collect_pads_add_pad (GstCollectPads * pads, GstPad * pad, guint size,
637     GstCollectDataDestroyNotify destroy_notify, gboolean lock)
638 {
639   GstCollectData *data;
640
641   g_return_val_if_fail (pads != NULL, NULL);
642   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), NULL);
643   g_return_val_if_fail (pad != NULL, NULL);
644   g_return_val_if_fail (GST_PAD_IS_SINK (pad), NULL);
645   g_return_val_if_fail (size >= sizeof (GstCollectData), NULL);
646
647   GST_DEBUG_OBJECT (pads, "adding pad %s:%s", GST_DEBUG_PAD_NAME (pad));
648
649   data = g_malloc0 (size);
650   data->priv = g_new0 (GstCollectDataPrivate, 1);
651   data->collect = pads;
652   data->pad = gst_object_ref (pad);
653   data->buffer = NULL;
654   data->pos = 0;
655   gst_segment_init (&data->segment, GST_FORMAT_UNDEFINED);
656   data->state = GST_COLLECT_PADS_STATE_WAITING;
657   data->state |= lock ? GST_COLLECT_PADS_STATE_LOCKED : 0;
658   data->priv->refcount = 1;
659   data->priv->destroy_notify = destroy_notify;
660   data->ABI.abi.dts = G_MININT64;
661
662   GST_OBJECT_LOCK (pads);
663   GST_OBJECT_LOCK (pad);
664   gst_pad_set_element_private (pad, data);
665   GST_OBJECT_UNLOCK (pad);
666   pads->priv->pad_list = g_slist_append (pads->priv->pad_list, data);
667   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_collect_pads_chain));
668   gst_pad_set_event_function (pad, GST_DEBUG_FUNCPTR (gst_collect_pads_event));
669   gst_pad_set_query_function (pad, GST_DEBUG_FUNCPTR (gst_collect_pads_query));
670   /* backward compat, also add to data if stopped, so that the element already
671    * has this in the public data list before going PAUSED (typically)
672    * this can only be done when we are stopped because we don't take the
673    * STREAM_LOCK to protect the pads->data list. */
674   if (!pads->priv->started) {
675     pads->data = g_slist_append (pads->data, data);
676     ref_data (data);
677   }
678   /* activate the pad when needed */
679   if (pads->priv->started)
680     gst_pad_set_active (pad, TRUE);
681   pads->priv->pad_cookie++;
682   GST_OBJECT_UNLOCK (pads);
683
684   return data;
685 }
686
687 static gint
688 find_pad (GstCollectData * data, GstPad * pad)
689 {
690   if (data->pad == pad)
691     return 0;
692   return 1;
693 }
694
695 /**
696  * gst_collect_pads_remove_pad:
697  * @pads: the collectpads to use
698  * @pad: (transfer none): the pad to remove
699  *
700  * Remove a pad from the collection of collect pads. This function will also
701  * free the #GstCollectData and all the resources that were allocated with
702  * gst_collect_pads_add_pad().
703  *
704  * The pad will be deactivated automatically when @pads is stopped.
705  *
706  * MT safe.
707  *
708  * Returns: %TRUE if the pad could be removed.
709  */
710 gboolean
711 gst_collect_pads_remove_pad (GstCollectPads * pads, GstPad * pad)
712 {
713   GstCollectData *data;
714   GSList *list;
715
716   g_return_val_if_fail (pads != NULL, FALSE);
717   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), FALSE);
718   g_return_val_if_fail (pad != NULL, FALSE);
719   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
720
721   GST_DEBUG_OBJECT (pads, "removing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
722
723   GST_OBJECT_LOCK (pads);
724   list =
725       g_slist_find_custom (pads->priv->pad_list, pad, (GCompareFunc) find_pad);
726   if (!list)
727     goto unknown_pad;
728
729   data = (GstCollectData *) list->data;
730
731   GST_DEBUG_OBJECT (pads, "found pad %s:%s at %p", GST_DEBUG_PAD_NAME (pad),
732       data);
733
734   /* clear the stuff we configured */
735   gst_pad_set_chain_function (pad, NULL);
736   gst_pad_set_event_function (pad, NULL);
737   GST_OBJECT_LOCK (pad);
738   gst_pad_set_element_private (pad, NULL);
739   GST_OBJECT_UNLOCK (pad);
740
741   /* backward compat, also remove from data if stopped, note that this function
742    * can only be called when we are stopped because we don't take the
743    * STREAM_LOCK to protect the pads->data list. */
744   if (!pads->priv->started) {
745     GSList *dlist;
746
747     dlist = g_slist_find_custom (pads->data, pad, (GCompareFunc) find_pad);
748     if (dlist) {
749       GstCollectData *pdata = dlist->data;
750
751       pads->data = g_slist_delete_link (pads->data, dlist);
752       unref_data (pdata);
753     }
754   }
755   /* remove from the pad list */
756   pads->priv->pad_list = g_slist_delete_link (pads->priv->pad_list, list);
757   pads->priv->pad_cookie++;
758
759   /* signal waiters because something changed */
760   GST_COLLECT_PADS_EVT_BROADCAST (pads);
761
762   /* deactivate the pad when needed */
763   if (!pads->priv->started)
764     gst_pad_set_active (pad, FALSE);
765
766   /* clean and free the collect data */
767   unref_data (data);
768
769   GST_OBJECT_UNLOCK (pads);
770
771   return TRUE;
772
773 unknown_pad:
774   {
775     GST_WARNING_OBJECT (pads, "cannot remove unknown pad %s:%s",
776         GST_DEBUG_PAD_NAME (pad));
777     GST_OBJECT_UNLOCK (pads);
778     return FALSE;
779   }
780 }
781
782 /*
783  * Must be called with STREAM_LOCK and OBJECT_LOCK.
784  */
785 static void
786 gst_collect_pads_set_flushing_unlocked (GstCollectPads * pads,
787     gboolean flushing)
788 {
789   GSList *walk = NULL;
790
791   /* Update the pads flushing flag */
792   for (walk = pads->priv->pad_list; walk; walk = g_slist_next (walk)) {
793     GstCollectData *cdata = walk->data;
794
795     if (GST_IS_PAD (cdata->pad)) {
796       GST_OBJECT_LOCK (cdata->pad);
797       if (flushing)
798         GST_PAD_SET_FLUSHING (cdata->pad);
799       else
800         GST_PAD_UNSET_FLUSHING (cdata->pad);
801       if (flushing)
802         GST_COLLECT_PADS_STATE_SET (cdata, GST_COLLECT_PADS_STATE_FLUSHING);
803       else
804         GST_COLLECT_PADS_STATE_UNSET (cdata, GST_COLLECT_PADS_STATE_FLUSHING);
805       gst_collect_pads_clear (pads, cdata);
806       GST_OBJECT_UNLOCK (cdata->pad);
807     }
808   }
809
810   /* inform _chain of changes */
811   GST_COLLECT_PADS_EVT_BROADCAST (pads);
812 }
813
814 /**
815  * gst_collect_pads_set_flushing:
816  * @pads: the collectpads to use
817  * @flushing: desired state of the pads
818  *
819  * Change the flushing state of all the pads in the collection. No pad
820  * is able to accept anymore data when @flushing is %TRUE. Calling this
821  * function with @flushing %FALSE makes @pads accept data again.
822  * Caller must ensure that downstream streaming (thread) is not blocked,
823  * e.g. by sending a FLUSH_START downstream.
824  *
825  * MT safe.
826  */
827 void
828 gst_collect_pads_set_flushing (GstCollectPads * pads, gboolean flushing)
829 {
830   g_return_if_fail (pads != NULL);
831   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
832
833   /* NOTE since this eventually calls _pop, some (STREAM_)LOCK is needed here */
834   GST_COLLECT_PADS_STREAM_LOCK (pads);
835   GST_OBJECT_LOCK (pads);
836   gst_collect_pads_set_flushing_unlocked (pads, flushing);
837   GST_OBJECT_UNLOCK (pads);
838   GST_COLLECT_PADS_STREAM_UNLOCK (pads);
839 }
840
841 /**
842  * gst_collect_pads_start:
843  * @pads: the collectpads to use
844  *
845  * Starts the processing of data in the collect_pads.
846  *
847  * MT safe.
848  */
849 void
850 gst_collect_pads_start (GstCollectPads * pads)
851 {
852   GSList *collected;
853
854   g_return_if_fail (pads != NULL);
855   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
856
857   GST_DEBUG_OBJECT (pads, "starting collect pads");
858
859   /* make sure stop and collect cannot be called anymore */
860   GST_COLLECT_PADS_STREAM_LOCK (pads);
861
862   /* make pads streamable */
863   GST_OBJECT_LOCK (pads);
864
865   /* loop over the master pad list and reset the segment */
866   collected = pads->priv->pad_list;
867   for (; collected; collected = g_slist_next (collected)) {
868     GstCollectData *data;
869
870     data = collected->data;
871     gst_segment_init (&data->segment, GST_FORMAT_UNDEFINED);
872   }
873
874   gst_collect_pads_set_flushing_unlocked (pads, FALSE);
875
876   /* Start collect pads */
877   pads->priv->started = TRUE;
878   GST_OBJECT_UNLOCK (pads);
879   GST_COLLECT_PADS_STREAM_UNLOCK (pads);
880 }
881
882 /**
883  * gst_collect_pads_stop:
884  * @pads: the collectpads to use
885  *
886  * Stops the processing of data in the collect_pads. this function
887  * will also unblock any blocking operations.
888  *
889  * MT safe.
890  */
891 void
892 gst_collect_pads_stop (GstCollectPads * pads)
893 {
894   GSList *collected;
895
896   g_return_if_fail (pads != NULL);
897   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
898
899   GST_DEBUG_OBJECT (pads, "stopping collect pads");
900
901   /* make sure collect and start cannot be called anymore */
902   GST_COLLECT_PADS_STREAM_LOCK (pads);
903
904   /* make pads not accept data anymore */
905   GST_OBJECT_LOCK (pads);
906   gst_collect_pads_set_flushing_unlocked (pads, TRUE);
907
908   /* Stop collect pads */
909   pads->priv->started = FALSE;
910   pads->priv->eospads = 0;
911   pads->priv->queuedpads = 0;
912
913   /* loop over the master pad list and flush buffers */
914   collected = pads->priv->pad_list;
915   for (; collected; collected = g_slist_next (collected)) {
916     GstCollectData *data;
917     GstBuffer **buffer_p;
918
919     data = collected->data;
920     if (data->buffer) {
921       buffer_p = &data->buffer;
922       gst_buffer_replace (buffer_p, NULL);
923       data->pos = 0;
924     }
925     GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_EOS);
926   }
927
928   if (pads->priv->earliest_data)
929     unref_data (pads->priv->earliest_data);
930   pads->priv->earliest_data = NULL;
931   pads->priv->earliest_time = GST_CLOCK_TIME_NONE;
932
933   GST_OBJECT_UNLOCK (pads);
934   /* Wake them up so they can end the chain functions. */
935   GST_COLLECT_PADS_EVT_BROADCAST (pads);
936
937   GST_COLLECT_PADS_STREAM_UNLOCK (pads);
938 }
939
940 /**
941  * gst_collect_pads_peek:
942  * @pads: the collectpads to peek
943  * @data: the data to use
944  *
945  * Peek at the buffer currently queued in @data. This function
946  * should be called with the @pads STREAM_LOCK held, such as in the callback
947  * handler.
948  *
949  * MT safe.
950  *
951  * Returns: The buffer in @data or %NULL if no buffer is queued.
952  *  should unref the buffer after usage.
953  */
954 GstBuffer *
955 gst_collect_pads_peek (GstCollectPads * pads, GstCollectData * data)
956 {
957   GstBuffer *result;
958
959   g_return_val_if_fail (pads != NULL, NULL);
960   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), NULL);
961   g_return_val_if_fail (data != NULL, NULL);
962
963   if ((result = data->buffer))
964     gst_buffer_ref (result);
965
966   GST_DEBUG_OBJECT (pads, "Peeking at pad %s:%s: buffer=%" GST_PTR_FORMAT,
967       GST_DEBUG_PAD_NAME (data->pad), result);
968
969   return result;
970 }
971
972 /**
973  * gst_collect_pads_pop:
974  * @pads: the collectpads to pop
975  * @data: the data to use
976  *
977  * Pop the buffer currently queued in @data. This function
978  * should be called with the @pads STREAM_LOCK held, such as in the callback
979  * handler.
980  *
981  * MT safe.
982  *
983  * Returns: (transfer full): The buffer in @data or %NULL if no buffer was
984  *   queued. You should unref the buffer after usage.
985  */
986 GstBuffer *
987 gst_collect_pads_pop (GstCollectPads * pads, GstCollectData * data)
988 {
989   GstBuffer *result;
990
991   g_return_val_if_fail (pads != NULL, NULL);
992   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), NULL);
993   g_return_val_if_fail (data != NULL, NULL);
994
995   if ((result = data->buffer)) {
996     data->buffer = NULL;
997     data->pos = 0;
998     /* one less pad with queued data now */
999     if (GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_WAITING))
1000       pads->priv->queuedpads--;
1001   }
1002
1003   GST_COLLECT_PADS_EVT_BROADCAST (pads);
1004
1005   GST_DEBUG_OBJECT (pads, "Pop buffer on pad %s:%s: buffer=%" GST_PTR_FORMAT,
1006       GST_DEBUG_PAD_NAME (data->pad), result);
1007
1008   return result;
1009 }
1010
1011 /* pop and unref the currently queued buffer, should be called with STREAM_LOCK
1012  * held */
1013 static void
1014 gst_collect_pads_clear (GstCollectPads * pads, GstCollectData * data)
1015 {
1016   GstBuffer *buf;
1017
1018   if ((buf = gst_collect_pads_pop (pads, data)))
1019     gst_buffer_unref (buf);
1020 }
1021
1022 /**
1023  * gst_collect_pads_available:
1024  * @pads: the collectpads to query
1025  *
1026  * Query how much bytes can be read from each queued buffer. This means
1027  * that the result of this call is the maximum number of bytes that can
1028  * be read from each of the pads.
1029  *
1030  * This function should be called with @pads STREAM_LOCK held, such as
1031  * in the callback.
1032  *
1033  * MT safe.
1034  *
1035  * Returns: The maximum number of bytes queued on all pads. This function
1036  * returns 0 if a pad has no queued buffer.
1037  */
1038 /* we might pre-calculate this in some struct field,
1039  * but would then have to maintain this in _chain and particularly _pop, etc,
1040  * even if element is never interested in this information */
1041 guint
1042 gst_collect_pads_available (GstCollectPads * pads)
1043 {
1044   GSList *collected;
1045   guint result = G_MAXUINT;
1046
1047   g_return_val_if_fail (pads != NULL, 0);
1048   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), 0);
1049
1050   collected = pads->data;
1051   for (; collected; collected = g_slist_next (collected)) {
1052     GstCollectData *pdata;
1053     GstBuffer *buffer;
1054     gint size;
1055
1056     pdata = (GstCollectData *) collected->data;
1057
1058     /* ignore pad with EOS */
1059     if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (pdata,
1060                 GST_COLLECT_PADS_STATE_EOS))) {
1061       GST_DEBUG_OBJECT (pads, "pad %p is EOS", pdata);
1062       continue;
1063     }
1064
1065     /* an empty buffer without EOS is weird when we get here.. */
1066     if (G_UNLIKELY ((buffer = pdata->buffer) == NULL)) {
1067       GST_WARNING_OBJECT (pads, "pad %p has no buffer", pdata);
1068       goto not_filled;
1069     }
1070
1071     /* this is the size left of the buffer */
1072     size = gst_buffer_get_size (buffer) - pdata->pos;
1073     GST_DEBUG_OBJECT (pads, "pad %p has %d bytes left", pdata, size);
1074
1075     /* need to return the min of all available data */
1076     if (size < result)
1077       result = size;
1078   }
1079   /* nothing changed, all must be EOS then, return 0 */
1080   if (G_UNLIKELY (result == G_MAXUINT))
1081     result = 0;
1082
1083   return result;
1084
1085 not_filled:
1086   {
1087     return 0;
1088   }
1089 }
1090
1091 /**
1092  * gst_collect_pads_flush:
1093  * @pads: the collectpads to query
1094  * @data: the data to use
1095  * @size: the number of bytes to flush
1096  *
1097  * Flush @size bytes from the pad @data.
1098  *
1099  * This function should be called with @pads STREAM_LOCK held, such as
1100  * in the callback.
1101  *
1102  * MT safe.
1103  *
1104  * Returns: The number of bytes flushed This can be less than @size and
1105  * is 0 if the pad was end-of-stream.
1106  */
1107 guint
1108 gst_collect_pads_flush (GstCollectPads * pads, GstCollectData * data,
1109     guint size)
1110 {
1111   guint flushsize;
1112   gsize bsize;
1113   GstBuffer *buffer;
1114
1115   g_return_val_if_fail (pads != NULL, 0);
1116   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), 0);
1117   g_return_val_if_fail (data != NULL, 0);
1118
1119   /* no buffer, must be EOS */
1120   if ((buffer = data->buffer) == NULL)
1121     return 0;
1122
1123   bsize = gst_buffer_get_size (buffer);
1124
1125   /* this is what we can flush at max */
1126   flushsize = MIN (size, bsize - data->pos);
1127
1128   data->pos += size;
1129
1130   if (data->pos >= bsize)
1131     /* _clear will also reset data->pos to 0 */
1132     gst_collect_pads_clear (pads, data);
1133
1134   return flushsize;
1135 }
1136
1137 /**
1138  * gst_collect_pads_read_buffer:
1139  * @pads: the collectpads to query
1140  * @data: the data to use
1141  * @size: the number of bytes to read
1142  *
1143  * Get a subbuffer of @size bytes from the given pad @data.
1144  *
1145  * This function should be called with @pads STREAM_LOCK held, such as in the
1146  * callback.
1147  *
1148  * MT safe.
1149  *
1150  * Returns: (transfer full): A sub buffer. The size of the buffer can be less that requested.
1151  * A return of %NULL signals that the pad is end-of-stream.
1152  * Unref the buffer after use.
1153  */
1154 GstBuffer *
1155 gst_collect_pads_read_buffer (GstCollectPads * pads, GstCollectData * data,
1156     guint size)
1157 {
1158   guint readsize, buf_size;
1159   GstBuffer *buffer;
1160
1161   g_return_val_if_fail (pads != NULL, NULL);
1162   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), NULL);
1163   g_return_val_if_fail (data != NULL, NULL);
1164
1165   /* no buffer, must be EOS */
1166   if ((buffer = data->buffer) == NULL)
1167     return NULL;
1168
1169   buf_size = gst_buffer_get_size (buffer);
1170   readsize = MIN (size, buf_size - data->pos);
1171
1172   return gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, data->pos,
1173       readsize);
1174 }
1175
1176 /**
1177  * gst_collect_pads_take_buffer:
1178  * @pads: the collectpads to query
1179  * @data: the data to use
1180  * @size: the number of bytes to read
1181  *
1182  * Get a subbuffer of @size bytes from the given pad @data. Flushes the amount
1183  * of read bytes.
1184  *
1185  * This function should be called with @pads STREAM_LOCK held, such as in the
1186  * callback.
1187  *
1188  * MT safe.
1189  *
1190  * Returns: A sub buffer. The size of the buffer can be less that requested.
1191  * A return of %NULL signals that the pad is end-of-stream.
1192  * Unref the buffer after use.
1193  */
1194 GstBuffer *
1195 gst_collect_pads_take_buffer (GstCollectPads * pads, GstCollectData * data,
1196     guint size)
1197 {
1198   GstBuffer *buffer = gst_collect_pads_read_buffer (pads, data, size);
1199
1200   if (buffer) {
1201     gst_collect_pads_flush (pads, data, gst_buffer_get_size (buffer));
1202   }
1203   return buffer;
1204 }
1205
1206 /**
1207  * gst_collect_pads_set_waiting:
1208  * @pads: the collectpads
1209  * @data: the data to use
1210  * @waiting: boolean indicating whether this pad should operate
1211  *           in waiting or non-waiting mode
1212  *
1213  * Sets a pad to waiting or non-waiting mode, if at least this pad
1214  * has not been created with locked waiting state,
1215  * in which case nothing happens.
1216  *
1217  * This function should be called with @pads STREAM_LOCK held, such as
1218  * in the callback.
1219  *
1220  * MT safe.
1221  */
1222 void
1223 gst_collect_pads_set_waiting (GstCollectPads * pads, GstCollectData * data,
1224     gboolean waiting)
1225 {
1226   g_return_if_fail (pads != NULL);
1227   g_return_if_fail (GST_IS_COLLECT_PADS (pads));
1228   g_return_if_fail (data != NULL);
1229
1230   GST_DEBUG_OBJECT (pads, "Setting pad %s to waiting %d, locked %d",
1231       GST_PAD_NAME (data->pad), waiting,
1232       GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_LOCKED));
1233
1234   /* Do something only on a change and if not locked */
1235   if (!GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_LOCKED) &&
1236       (GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_WAITING) !=
1237           ! !waiting)) {
1238     /* Set waiting state for this pad */
1239     if (waiting)
1240       GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_WAITING);
1241     else
1242       GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_WAITING);
1243     /* Update number of queued pads if needed */
1244     if (!data->buffer &&
1245         !GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_EOS)) {
1246       if (waiting)
1247         pads->priv->queuedpads--;
1248       else
1249         pads->priv->queuedpads++;
1250     }
1251
1252     /* signal waiters because something changed */
1253     GST_COLLECT_PADS_EVT_BROADCAST (pads);
1254   }
1255 }
1256
1257 /* see if pads were added or removed and update our stats. Any pad
1258  * added after releasing the LOCK will get collected in the next
1259  * round.
1260  *
1261  * We can do a quick check by checking the cookies, that get changed
1262  * whenever the pad list is updated.
1263  *
1264  * Must be called with STREAM_LOCK.
1265  */
1266 static void
1267 gst_collect_pads_check_pads (GstCollectPads * pads)
1268 {
1269   /* the master list and cookie are protected with LOCK */
1270   GST_OBJECT_LOCK (pads);
1271   if (G_UNLIKELY (pads->priv->pad_cookie != pads->priv->cookie)) {
1272     GSList *collected;
1273
1274     /* clear list and stats */
1275     g_slist_foreach (pads->data, (GFunc) unref_data, NULL);
1276     g_slist_free (pads->data);
1277     pads->data = NULL;
1278     pads->priv->numpads = 0;
1279     pads->priv->queuedpads = 0;
1280     pads->priv->eospads = 0;
1281     if (pads->priv->earliest_data)
1282       unref_data (pads->priv->earliest_data);
1283     pads->priv->earliest_data = NULL;
1284     pads->priv->earliest_time = GST_CLOCK_TIME_NONE;
1285
1286     /* loop over the master pad list */
1287     collected = pads->priv->pad_list;
1288     for (; collected; collected = g_slist_next (collected)) {
1289       GstCollectData *data;
1290
1291       /* update the stats */
1292       pads->priv->numpads++;
1293       data = collected->data;
1294       if (GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_EOS))
1295         pads->priv->eospads++;
1296       else if (data->buffer || !GST_COLLECT_PADS_STATE_IS_SET (data,
1297               GST_COLLECT_PADS_STATE_WAITING))
1298         pads->priv->queuedpads++;
1299
1300       /* add to the list of pads to collect */
1301       ref_data (data);
1302       /* preserve order of adding/requesting pads */
1303       pads->data = g_slist_append (pads->data, data);
1304     }
1305     /* and update the cookie */
1306     pads->priv->cookie = pads->priv->pad_cookie;
1307   }
1308   GST_OBJECT_UNLOCK (pads);
1309 }
1310
1311 /* checks if all the pads are collected and call the collectfunction
1312  *
1313  * Should be called with STREAM_LOCK.
1314  *
1315  * Returns: The #GstFlowReturn of collection.
1316  */
1317 static GstFlowReturn
1318 gst_collect_pads_check_collected (GstCollectPads * pads)
1319 {
1320   GstFlowReturn flow_ret = GST_FLOW_OK;
1321   GstCollectPadsFunction func;
1322   gpointer user_data;
1323
1324   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), GST_FLOW_ERROR);
1325
1326   GST_OBJECT_LOCK (pads);
1327   func = pads->priv->func;
1328   user_data = pads->priv->user_data;
1329   GST_OBJECT_UNLOCK (pads);
1330
1331   g_return_val_if_fail (pads->priv->func != NULL, GST_FLOW_NOT_SUPPORTED);
1332
1333   /* check for new pads, update stats etc.. */
1334   gst_collect_pads_check_pads (pads);
1335
1336   if (G_UNLIKELY (pads->priv->eospads == pads->priv->numpads)) {
1337     /* If all our pads are EOS just collect once to let the element
1338      * do its final EOS handling. */
1339     GST_DEBUG_OBJECT (pads, "All active pads (%d) are EOS, calling %s",
1340         pads->priv->numpads, GST_DEBUG_FUNCPTR_NAME (func));
1341
1342     if (G_UNLIKELY (g_atomic_int_compare_and_exchange (&pads->priv->seeking,
1343                 TRUE, FALSE))) {
1344       GST_INFO_OBJECT (pads, "finished seeking");
1345     }
1346     do {
1347       flow_ret = func (pads, user_data);
1348     } while (flow_ret == GST_FLOW_OK);
1349   } else {
1350     gboolean collected = FALSE;
1351
1352     /* We call the collected function as long as our condition matches. */
1353     while (((pads->priv->queuedpads + pads->priv->eospads) >=
1354             pads->priv->numpads)) {
1355       GST_DEBUG_OBJECT (pads,
1356           "All active pads (%d + %d >= %d) have data, " "calling %s",
1357           pads->priv->queuedpads, pads->priv->eospads, pads->priv->numpads,
1358           GST_DEBUG_FUNCPTR_NAME (func));
1359
1360       if (G_UNLIKELY (g_atomic_int_compare_and_exchange (&pads->priv->seeking,
1361                   TRUE, FALSE))) {
1362         GST_INFO_OBJECT (pads, "finished seeking");
1363       }
1364       flow_ret = func (pads, user_data);
1365       collected = TRUE;
1366
1367       /* break on error */
1368       if (flow_ret != GST_FLOW_OK)
1369         break;
1370       /* Don't keep looping after telling the element EOS or flushing */
1371       if (pads->priv->queuedpads == 0)
1372         break;
1373     }
1374     if (!collected)
1375       GST_DEBUG_OBJECT (pads, "Not all active pads (%d) have data, continuing",
1376           pads->priv->numpads);
1377   }
1378   return flow_ret;
1379 }
1380
1381
1382 /* General overview:
1383  * - only pad with a buffer can determine earliest_data (and earliest_time)
1384  * - only segment info determines (non-)waiting state
1385  * - ? perhaps use _stream_time for comparison
1386  *   (which muxers might have use as well ?)
1387  */
1388
1389 /*
1390  * Function to recalculate the waiting state of all pads.
1391  *
1392  * Must be called with STREAM_LOCK.
1393  *
1394  * Returns %TRUE if a pad was set to waiting
1395  * (from non-waiting state).
1396  */
1397 static gboolean
1398 gst_collect_pads_recalculate_waiting (GstCollectPads * pads)
1399 {
1400   GSList *collected;
1401   gboolean result = FALSE;
1402
1403   /* If earliest time is not known, there is nothing to do. */
1404   if (pads->priv->earliest_data == NULL)
1405     return FALSE;
1406
1407   for (collected = pads->data; collected; collected = g_slist_next (collected)) {
1408     GstCollectData *data = (GstCollectData *) collected->data;
1409     int cmp_res;
1410     GstClockTime comp_time;
1411
1412     /* check if pad has a segment */
1413     if (data->segment.format == GST_FORMAT_UNDEFINED) {
1414       GST_WARNING_OBJECT (pads,
1415           "GstCollectPads has no time segment, assuming 0 based.");
1416       gst_segment_init (&data->segment, GST_FORMAT_TIME);
1417       GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_NEW_SEGMENT);
1418     }
1419
1420     /* check segment format */
1421     if (data->segment.format != GST_FORMAT_TIME) {
1422       GST_ERROR_OBJECT (pads, "GstCollectPads can handle only time segments.");
1423       continue;
1424     }
1425
1426     /* check if the waiting state should be changed */
1427     comp_time = data->segment.position;
1428     cmp_res = pads->priv->compare_func (pads, data, comp_time,
1429         pads->priv->earliest_data, pads->priv->earliest_time,
1430         pads->priv->compare_user_data);
1431     if (cmp_res > 0)
1432       /* stop waiting */
1433       gst_collect_pads_set_waiting (pads, data, FALSE);
1434     else {
1435       if (!GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_WAITING)) {
1436         /* start waiting */
1437         gst_collect_pads_set_waiting (pads, data, TRUE);
1438         result = TRUE;
1439       }
1440     }
1441   }
1442
1443   return result;
1444 }
1445
1446 /**
1447  * gst_collect_pads_find_best_pad:
1448  * @pads: the collectpads to use
1449  * @data: returns the collectdata for earliest data
1450  * @time: returns the earliest available buffertime
1451  *
1452  * Find the oldest/best pad, i.e. pad holding the oldest buffer and
1453  * and return the corresponding #GstCollectData and buffertime.
1454  *
1455  * This function should be called with STREAM_LOCK held,
1456  * such as in the callback.
1457  */
1458 static void
1459 gst_collect_pads_find_best_pad (GstCollectPads * pads,
1460     GstCollectData ** data, GstClockTime * time)
1461 {
1462   GSList *collected;
1463   GstCollectData *best = NULL;
1464   GstClockTime best_time = GST_CLOCK_TIME_NONE;
1465
1466   g_return_if_fail (data != NULL);
1467   g_return_if_fail (time != NULL);
1468
1469   for (collected = pads->data; collected; collected = g_slist_next (collected)) {
1470     GstBuffer *buffer;
1471     GstCollectData *data = (GstCollectData *) collected->data;
1472     GstClockTime timestamp;
1473
1474     buffer = gst_collect_pads_peek (pads, data);
1475     /* if we have a buffer check if it is better then the current best one */
1476     if (buffer != NULL) {
1477       timestamp = GST_BUFFER_DTS (buffer);
1478       if (!GST_CLOCK_TIME_IS_VALID (timestamp)) {
1479         timestamp = GST_BUFFER_PTS (buffer);
1480       }
1481       gst_buffer_unref (buffer);
1482       if (best == NULL || pads->priv->compare_func (pads, data, timestamp,
1483               best, best_time, pads->priv->compare_user_data) < 0) {
1484         best = data;
1485         best_time = timestamp;
1486       }
1487     }
1488   }
1489
1490   /* set earliest time */
1491   *data = best;
1492   *time = best_time;
1493
1494   GST_DEBUG_OBJECT (pads, "best pad %s, best time %" GST_TIME_FORMAT,
1495       best ? GST_PAD_NAME (((GstCollectData *) best)->pad) : "(nil)",
1496       GST_TIME_ARGS (best_time));
1497 }
1498
1499 /*
1500  * Function to recalculate earliest_data and earliest_timestamp. This also calls
1501  * gst_collect_pads_recalculate_waiting
1502  *
1503  * Must be called with STREAM_LOCK.
1504  */
1505 static gboolean
1506 gst_collect_pads_recalculate_full (GstCollectPads * pads)
1507 {
1508   if (pads->priv->earliest_data)
1509     unref_data (pads->priv->earliest_data);
1510   gst_collect_pads_find_best_pad (pads, &pads->priv->earliest_data,
1511       &pads->priv->earliest_time);
1512   if (pads->priv->earliest_data)
1513     ref_data (pads->priv->earliest_data);
1514   return gst_collect_pads_recalculate_waiting (pads);
1515 }
1516
1517 /*
1518  * Default collect callback triggered when #GstCollectPads gathered all data.
1519  *
1520  * Called with STREAM_LOCK.
1521  */
1522 static GstFlowReturn
1523 gst_collect_pads_default_collected (GstCollectPads * pads, gpointer user_data)
1524 {
1525   GstCollectData *best = NULL;
1526   GstBuffer *buffer;
1527   GstFlowReturn ret = GST_FLOW_OK;
1528   GstCollectPadsBufferFunction func;
1529   gpointer buffer_user_data;
1530
1531   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), GST_FLOW_ERROR);
1532
1533   GST_OBJECT_LOCK (pads);
1534   func = pads->priv->buffer_func;
1535   buffer_user_data = pads->priv->buffer_user_data;
1536   GST_OBJECT_UNLOCK (pads);
1537
1538   g_return_val_if_fail (func != NULL, GST_FLOW_NOT_SUPPORTED);
1539
1540   /* Find the oldest pad at all cost */
1541   if (gst_collect_pads_recalculate_full (pads)) {
1542     /* waiting was switched on,
1543      * so give another thread a chance to deliver a possibly
1544      * older buffer; don't charge on yet with the current oldest */
1545     ret = GST_FLOW_OK;
1546     goto done;
1547   }
1548
1549   best = pads->priv->earliest_data;
1550
1551   /* No data collected means EOS. */
1552   if (G_UNLIKELY (best == NULL)) {
1553     ret = func (pads, best, NULL, buffer_user_data);
1554     if (ret == GST_FLOW_OK)
1555       ret = GST_FLOW_EOS;
1556     goto done;
1557   }
1558
1559   /* make sure that the pad we take a buffer from is waiting;
1560    * otherwise popping a buffer will seem not to have happened
1561    * and collectpads can get into a busy loop */
1562   gst_collect_pads_set_waiting (pads, best, TRUE);
1563
1564   /* Send buffer */
1565   buffer = gst_collect_pads_pop (pads, best);
1566   ret = func (pads, best, buffer, buffer_user_data);
1567
1568   /* maybe non-waiting was forced to waiting above due to
1569    * newsegment events coming too sparsely,
1570    * so re-check to restore state to avoid hanging/waiting */
1571   gst_collect_pads_recalculate_full (pads);
1572
1573 done:
1574   return ret;
1575 }
1576
1577 /*
1578  * Default timestamp compare function.
1579  */
1580 static gint
1581 gst_collect_pads_default_compare_func (GstCollectPads * pads,
1582     GstCollectData * data1, GstClockTime timestamp1,
1583     GstCollectData * data2, GstClockTime timestamp2, gpointer user_data)
1584 {
1585
1586   GST_LOG_OBJECT (pads, "comparing %" GST_TIME_FORMAT
1587       " and %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp1),
1588       GST_TIME_ARGS (timestamp2));
1589   /* non-valid timestamps go first as they are probably headers or so */
1590   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (timestamp1)))
1591     return GST_CLOCK_TIME_IS_VALID (timestamp2) ? -1 : 0;
1592
1593   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (timestamp2)))
1594     return 1;
1595
1596   /* compare timestamp */
1597   if (timestamp1 < timestamp2)
1598     return -1;
1599
1600   if (timestamp1 > timestamp2)
1601     return 1;
1602
1603   return 0;
1604 }
1605
1606 /* called with STREAM_LOCK */
1607 static void
1608 gst_collect_pads_handle_position_update (GstCollectPads * pads,
1609     GstCollectData * data, GstClockTime new_pos)
1610 {
1611   gint cmp_res;
1612
1613   /* If oldest time is not known, or current pad got newsegment;
1614    * recalculate the state */
1615   if (!pads->priv->earliest_data || pads->priv->earliest_data == data) {
1616     gst_collect_pads_recalculate_full (pads);
1617     goto exit;
1618   }
1619
1620   /* Check if the waiting state of the pad should change. */
1621   cmp_res =
1622       pads->priv->compare_func (pads, data, new_pos,
1623       pads->priv->earliest_data, pads->priv->earliest_time,
1624       pads->priv->compare_user_data);
1625
1626   if (cmp_res > 0)
1627     /* Stop waiting */
1628     gst_collect_pads_set_waiting (pads, data, FALSE);
1629
1630 exit:
1631   return;
1632
1633 }
1634
1635 static GstClockTime
1636 gst_collect_pads_clip_time (GstCollectPads * pads, GstCollectData * data,
1637     GstClockTime time)
1638 {
1639   GstClockTime otime = time;
1640   GstBuffer *in, *out = NULL;
1641
1642   if (pads->priv->clip_func) {
1643     in = gst_buffer_new ();
1644     GST_BUFFER_PTS (in) = time;
1645     GST_BUFFER_DTS (in) = time;
1646     pads->priv->clip_func (pads, data, in, &out, pads->priv->clip_user_data);
1647     if (out) {
1648       otime = GST_BUFFER_PTS (out);
1649       gst_buffer_unref (out);
1650     } else {
1651       /* FIXME should distinguish between ahead or after segment,
1652        * let's assume after segment and use some large time ... */
1653       otime = G_MAXINT64 / 2;
1654     }
1655   }
1656
1657   return otime;
1658 }
1659
1660 /**
1661  * gst_collect_pads_event_default:
1662  * @pads: the collectpads to use
1663  * @data: collect data of corresponding pad
1664  * @event: event being processed
1665  * @discard: process but do not send event downstream
1666  *
1667  * Default #GstCollectPads event handling that elements should always
1668  * chain up to to ensure proper operation.  Element might however indicate
1669  * event should not be forwarded downstream.
1670  */
1671 gboolean
1672 gst_collect_pads_event_default (GstCollectPads * pads, GstCollectData * data,
1673     GstEvent * event, gboolean discard)
1674 {
1675   gboolean res = TRUE;
1676   GstCollectPadsBufferFunction buffer_func;
1677   GstObject *parent;
1678   GstPad *pad;
1679
1680   GST_OBJECT_LOCK (pads);
1681   buffer_func = pads->priv->buffer_func;
1682   GST_OBJECT_UNLOCK (pads);
1683
1684   pad = data->pad;
1685   parent = GST_OBJECT_PARENT (pad);
1686
1687   switch (GST_EVENT_TYPE (event)) {
1688     case GST_EVENT_FLUSH_START:
1689     {
1690       if (g_atomic_int_get (&pads->priv->seeking)) {
1691         /* drop all but the first FLUSH_STARTs when seeking */
1692         if (!g_atomic_int_compare_and_exchange (&pads->
1693                 priv->pending_flush_start, TRUE, FALSE))
1694           goto eat;
1695
1696         /* unblock collect pads */
1697         gst_pad_event_default (pad, parent, event);
1698         event = NULL;
1699
1700         GST_COLLECT_PADS_STREAM_LOCK (pads);
1701         /* Start flushing. We never call gst_collect_pads_set_flushing (FALSE), we
1702          * instead wait until each pad gets its FLUSH_STOP and let that reset the pad to
1703          * non-flushing (which happens in gst_collect_pads_event_default).
1704          */
1705         gst_collect_pads_set_flushing (pads, TRUE);
1706
1707         if (pads->priv->flush_func)
1708           pads->priv->flush_func (pads, pads->priv->flush_user_data);
1709
1710         g_atomic_int_set (&pads->priv->pending_flush_stop, TRUE);
1711         GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1712
1713         goto eat;
1714       } else {
1715         /* forward event to unblock check_collected */
1716         GST_DEBUG_OBJECT (pad, "forwarding flush start");
1717         res = gst_pad_event_default (pad, parent, event);
1718         event = NULL;
1719
1720         /* now unblock the chain function.
1721          * no cond per pad, so they all unblock,
1722          * non-flushing block again */
1723         GST_COLLECT_PADS_STREAM_LOCK (pads);
1724         GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_FLUSHING);
1725         gst_collect_pads_clear (pads, data);
1726
1727         /* cater for possible default muxing functionality */
1728         if (buffer_func) {
1729           /* restore to initial state */
1730           gst_collect_pads_set_waiting (pads, data, TRUE);
1731           /* if the current pad is affected, reset state, recalculate later */
1732           if (pads->priv->earliest_data == data) {
1733             unref_data (data);
1734             pads->priv->earliest_data = NULL;
1735             pads->priv->earliest_time = GST_CLOCK_TIME_NONE;
1736           }
1737         }
1738
1739         GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1740
1741         goto eat;
1742       }
1743     }
1744     case GST_EVENT_FLUSH_STOP:
1745     {
1746       /* flush the 1 buffer queue */
1747       GST_COLLECT_PADS_STREAM_LOCK (pads);
1748       GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_FLUSHING);
1749       gst_collect_pads_clear (pads, data);
1750       /* we need new segment info after the flush */
1751       gst_segment_init (&data->segment, GST_FORMAT_UNDEFINED);
1752       GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_NEW_SEGMENT);
1753       /* if the pad was EOS, remove the EOS flag and
1754        * decrement the number of eospads */
1755       if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
1756                   GST_COLLECT_PADS_STATE_EOS))) {
1757         if (!GST_COLLECT_PADS_STATE_IS_SET (data,
1758                 GST_COLLECT_PADS_STATE_WAITING))
1759           pads->priv->queuedpads++;
1760         if (!g_atomic_int_get (&pads->priv->seeking)) {
1761           pads->priv->eospads--;
1762         }
1763         GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_EOS);
1764       }
1765       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1766
1767       if (g_atomic_int_get (&pads->priv->seeking)) {
1768         if (g_atomic_int_compare_and_exchange (&pads->priv->pending_flush_stop,
1769                 TRUE, FALSE))
1770           goto forward;
1771         else
1772           goto eat;
1773       } else {
1774         goto forward;
1775       }
1776     }
1777     case GST_EVENT_EOS:
1778     {
1779       GST_COLLECT_PADS_STREAM_LOCK (pads);
1780       /* if the pad was not EOS, make it EOS and so we
1781        * have one more eospad */
1782       if (G_LIKELY (!GST_COLLECT_PADS_STATE_IS_SET (data,
1783                   GST_COLLECT_PADS_STATE_EOS))) {
1784         GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_EOS);
1785         if (!GST_COLLECT_PADS_STATE_IS_SET (data,
1786                 GST_COLLECT_PADS_STATE_WAITING))
1787           pads->priv->queuedpads--;
1788         pads->priv->eospads++;
1789       }
1790       /* check if we need collecting anything, we ignore the result. */
1791       gst_collect_pads_check_collected (pads);
1792       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1793
1794       goto eat;
1795     }
1796     case GST_EVENT_SEGMENT:
1797     {
1798       GstSegment seg;
1799
1800       GST_COLLECT_PADS_STREAM_LOCK (pads);
1801
1802       gst_event_copy_segment (event, &seg);
1803
1804       GST_DEBUG_OBJECT (data->pad, "got segment %" GST_SEGMENT_FORMAT, &seg);
1805
1806       /* default collection can not handle other segment formats than time */
1807       if (buffer_func && seg.format != GST_FORMAT_TIME) {
1808         GST_WARNING_OBJECT (pads, "GstCollectPads default collecting "
1809             "can only handle time segments. Non time segment ignored.");
1810         goto newsegment_done;
1811       }
1812
1813       /* need to update segment first */
1814       data->segment = seg;
1815       GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_NEW_SEGMENT);
1816
1817       /* now we can use for e.g. running time */
1818       seg.position =
1819           gst_collect_pads_clip_time (pads, data, seg.start + seg.offset);
1820       /* update again */
1821       data->segment = seg;
1822
1823       /* default muxing functionality */
1824       if (!buffer_func)
1825         goto newsegment_done;
1826
1827       gst_collect_pads_handle_position_update (pads, data, seg.position);
1828
1829     newsegment_done:
1830       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1831       /* we must not forward this event since multiple segments will be
1832        * accumulated and this is certainly not what we want. */
1833       goto eat;
1834     }
1835     case GST_EVENT_GAP:
1836     {
1837       GstClockTime start, duration;
1838
1839       GST_COLLECT_PADS_STREAM_LOCK (pads);
1840
1841       gst_event_parse_gap (event, &start, &duration);
1842       /* FIXME, handle reverse playback case */
1843       if (GST_CLOCK_TIME_IS_VALID (duration))
1844         start += duration;
1845       /* we do not expect another buffer until after gap,
1846        * so that is our position now */
1847       data->segment.position = gst_collect_pads_clip_time (pads, data, start);
1848
1849       gst_collect_pads_handle_position_update (pads, data,
1850           data->segment.position);
1851
1852       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1853       goto eat;
1854     }
1855     case GST_EVENT_STREAM_START:
1856       /* drop stream start events, element must create its own start event,
1857        * we can't just forward the first random stream start event we get */
1858       goto eat;
1859     case GST_EVENT_CAPS:
1860       goto eat;
1861     default:
1862       /* forward other events */
1863       goto forward;
1864   }
1865
1866 eat:
1867   if (event)
1868     gst_event_unref (event);
1869   return res;
1870
1871 forward:
1872   if (discard)
1873     goto eat;
1874   else
1875     return gst_pad_event_default (pad, parent, event);
1876 }
1877
1878 typedef struct
1879 {
1880   GstEvent *event;
1881   gboolean result;
1882 } EventData;
1883
1884 static gboolean
1885 event_forward_func (GstPad * pad, EventData * data)
1886 {
1887   gboolean ret = TRUE;
1888   GstPad *peer = gst_pad_get_peer (pad);
1889
1890   if (peer) {
1891     ret = gst_pad_send_event (peer, gst_event_ref (data->event));
1892     gst_object_unref (peer);
1893   }
1894
1895   data->result &= ret;
1896   /* Always send to all pads */
1897   return FALSE;
1898 }
1899
1900 static gboolean
1901 forward_event_to_all_sinkpads (GstPad * srcpad, GstEvent * event)
1902 {
1903   EventData data;
1904
1905   data.event = event;
1906   data.result = TRUE;
1907
1908   gst_pad_forward (srcpad, (GstPadForwardFunction) event_forward_func, &data);
1909
1910   gst_event_unref (event);
1911
1912   return data.result;
1913 }
1914
1915 /**
1916  * gst_collect_pads_src_event_default:
1917  * @pads: the #GstCollectPads to use
1918  * @pad: src #GstPad that received the event
1919  * @event: event being processed
1920  *
1921  * Default #GstCollectPads event handling for the src pad of elements.
1922  * Elements can chain up to this to let flushing seek event handling
1923  * be done by #GstCollectPads.
1924  *
1925  * Since: 1.4
1926  */
1927 gboolean
1928 gst_collect_pads_src_event_default (GstCollectPads * pads, GstPad * pad,
1929     GstEvent * event)
1930 {
1931   GstObject *parent;
1932   gboolean res = TRUE;
1933
1934   parent = GST_OBJECT_PARENT (pad);
1935
1936   switch (GST_EVENT_TYPE (event)) {
1937     case GST_EVENT_SEEK:{
1938       GstSeekFlags flags;
1939
1940       pads->priv->eospads = 0;
1941
1942       GST_INFO_OBJECT (pads, "starting seek");
1943
1944       gst_event_parse_seek (event, NULL, NULL, &flags, NULL, NULL, NULL, NULL);
1945       if (flags & GST_SEEK_FLAG_FLUSH) {
1946         g_atomic_int_set (&pads->priv->seeking, TRUE);
1947         g_atomic_int_set (&pads->priv->pending_flush_start, TRUE);
1948         /* forward the seek upstream */
1949         res = forward_event_to_all_sinkpads (pad, event);
1950         event = NULL;
1951         if (!res) {
1952           g_atomic_int_set (&pads->priv->seeking, FALSE);
1953           g_atomic_int_set (&pads->priv->pending_flush_start, FALSE);
1954         }
1955       }
1956
1957       GST_INFO_OBJECT (pads, "seek done, result: %d", res);
1958
1959       break;
1960     }
1961     default:
1962       break;
1963   }
1964
1965   if (event)
1966     res = gst_pad_event_default (pad, parent, event);
1967
1968   return res;
1969 }
1970
1971 static gboolean
1972 gst_collect_pads_event_default_internal (GstCollectPads * pads,
1973     GstCollectData * data, GstEvent * event, gpointer user_data)
1974 {
1975   return gst_collect_pads_event_default (pads, data, event, FALSE);
1976 }
1977
1978 static gboolean
1979 gst_collect_pads_event (GstPad * pad, GstObject * parent, GstEvent * event)
1980 {
1981   gboolean res = FALSE, need_unlock = FALSE;
1982   GstCollectData *data;
1983   GstCollectPads *pads;
1984   GstCollectPadsEventFunction event_func;
1985   gpointer event_user_data;
1986
1987   /* some magic to get the managing collect_pads */
1988   GST_OBJECT_LOCK (pad);
1989   data = (GstCollectData *) gst_pad_get_element_private (pad);
1990   if (G_UNLIKELY (data == NULL))
1991     goto pad_removed;
1992   ref_data (data);
1993   GST_OBJECT_UNLOCK (pad);
1994
1995   res = FALSE;
1996
1997   pads = data->collect;
1998
1999   GST_DEBUG_OBJECT (data->pad, "Got %s event on sink pad",
2000       GST_EVENT_TYPE_NAME (event));
2001
2002   GST_OBJECT_LOCK (pads);
2003   event_func = pads->priv->event_func;
2004   event_user_data = pads->priv->event_user_data;
2005   GST_OBJECT_UNLOCK (pads);
2006
2007   if (GST_EVENT_IS_SERIALIZED (event)) {
2008     GST_COLLECT_PADS_STREAM_LOCK (pads);
2009     need_unlock = TRUE;
2010   }
2011
2012   if (G_LIKELY (event_func)) {
2013     res = event_func (pads, data, event, event_user_data);
2014   }
2015
2016   if (need_unlock)
2017     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2018
2019   unref_data (data);
2020   return res;
2021
2022   /* ERRORS */
2023 pad_removed:
2024   {
2025     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2026     GST_OBJECT_UNLOCK (pad);
2027     return FALSE;
2028   }
2029 }
2030
2031 /**
2032  * gst_collect_pads_query_default:
2033  * @pads: the collectpads to use
2034  * @data: collect data of corresponding pad
2035  * @query: query being processed
2036  * @discard: process but do not send event downstream
2037  *
2038  * Default #GstCollectPads query handling that elements should always
2039  * chain up to to ensure proper operation.  Element might however indicate
2040  * query should not be forwarded downstream.
2041  */
2042 gboolean
2043 gst_collect_pads_query_default (GstCollectPads * pads, GstCollectData * data,
2044     GstQuery * query, gboolean discard)
2045 {
2046   gboolean res = TRUE;
2047   GstObject *parent;
2048   GstPad *pad;
2049
2050   pad = data->pad;
2051   parent = GST_OBJECT_PARENT (pad);
2052
2053   switch (GST_QUERY_TYPE (query)) {
2054     case GST_QUERY_SEEKING:
2055     {
2056       GstFormat format;
2057
2058       /* don't pass it along as some (file)sink might claim it does
2059        * whereas with a collectpads in between that will not likely work */
2060       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2061       gst_query_set_seeking (query, format, FALSE, 0, -1);
2062       res = TRUE;
2063       discard = TRUE;
2064       break;
2065     }
2066     default:
2067       break;
2068   }
2069
2070   if (!discard)
2071     return gst_pad_query_default (pad, parent, query);
2072   else
2073     return res;
2074 }
2075
2076 static gboolean
2077 gst_collect_pads_query_default_internal (GstCollectPads * pads,
2078     GstCollectData * data, GstQuery * query, gpointer user_data)
2079 {
2080   return gst_collect_pads_query_default (pads, data, query, FALSE);
2081 }
2082
2083 static gboolean
2084 gst_collect_pads_query (GstPad * pad, GstObject * parent, GstQuery * query)
2085 {
2086   gboolean res = FALSE, need_unlock = FALSE;
2087   GstCollectData *data;
2088   GstCollectPads *pads;
2089   GstCollectPadsQueryFunction query_func;
2090   gpointer query_user_data;
2091
2092   GST_DEBUG_OBJECT (pad, "Got %s query on sink pad",
2093       GST_QUERY_TYPE_NAME (query));
2094
2095   /* some magic to get the managing collect_pads */
2096   GST_OBJECT_LOCK (pad);
2097   data = (GstCollectData *) gst_pad_get_element_private (pad);
2098   if (G_UNLIKELY (data == NULL))
2099     goto pad_removed;
2100   ref_data (data);
2101   GST_OBJECT_UNLOCK (pad);
2102
2103   pads = data->collect;
2104
2105   GST_OBJECT_LOCK (pads);
2106   query_func = pads->priv->query_func;
2107   query_user_data = pads->priv->query_user_data;
2108   GST_OBJECT_UNLOCK (pads);
2109
2110   if (GST_QUERY_IS_SERIALIZED (query)) {
2111     GST_COLLECT_PADS_STREAM_LOCK (pads);
2112     need_unlock = TRUE;
2113   }
2114
2115   if (G_LIKELY (query_func)) {
2116     res = query_func (pads, data, query, query_user_data);
2117   }
2118
2119   if (need_unlock)
2120     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2121
2122   unref_data (data);
2123   return res;
2124
2125   /* ERRORS */
2126 pad_removed:
2127   {
2128     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2129     GST_OBJECT_UNLOCK (pad);
2130     return FALSE;
2131   }
2132 }
2133
2134
2135 /* For each buffer we receive we check if our collected condition is reached
2136  * and if so we call the collected function. When this is done we check if
2137  * data has been unqueued. If data is still queued we wait holding the stream
2138  * lock to make sure no EOS event can happen while we are ready to be
2139  * collected 
2140  */
2141 static GstFlowReturn
2142 gst_collect_pads_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2143 {
2144   GstCollectData *data;
2145   GstCollectPads *pads;
2146   GstFlowReturn ret;
2147   GstBuffer **buffer_p;
2148   guint32 cookie;
2149
2150   GST_DEBUG ("Got buffer for pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2151
2152   /* some magic to get the managing collect_pads */
2153   GST_OBJECT_LOCK (pad);
2154   data = (GstCollectData *) gst_pad_get_element_private (pad);
2155   if (G_UNLIKELY (data == NULL))
2156     goto no_data;
2157   ref_data (data);
2158   GST_OBJECT_UNLOCK (pad);
2159
2160   pads = data->collect;
2161
2162   GST_COLLECT_PADS_STREAM_LOCK (pads);
2163   /* if not started, bail out */
2164   if (G_UNLIKELY (!pads->priv->started))
2165     goto not_started;
2166   /* check if this pad is flushing */
2167   if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2168               GST_COLLECT_PADS_STATE_FLUSHING)))
2169     goto flushing;
2170   /* pad was EOS, we can refuse this data */
2171   if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2172               GST_COLLECT_PADS_STATE_EOS)))
2173     goto eos;
2174
2175   /* see if we need to clip */
2176   if (pads->priv->clip_func) {
2177     GstBuffer *outbuf = NULL;
2178     ret =
2179         pads->priv->clip_func (pads, data, buffer, &outbuf,
2180         pads->priv->clip_user_data);
2181     buffer = outbuf;
2182
2183     if (G_UNLIKELY (outbuf == NULL))
2184       goto clipped;
2185
2186     if (G_UNLIKELY (ret == GST_FLOW_EOS))
2187       goto eos;
2188     else if (G_UNLIKELY (ret != GST_FLOW_OK))
2189       goto error;
2190   }
2191
2192   GST_DEBUG_OBJECT (pads, "Queuing buffer %p for pad %s:%s", buffer,
2193       GST_DEBUG_PAD_NAME (pad));
2194
2195   /* One more pad has data queued */
2196   if (GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_WAITING))
2197     pads->priv->queuedpads++;
2198   buffer_p = &data->buffer;
2199   gst_buffer_replace (buffer_p, buffer);
2200
2201   /* update segment last position if in TIME */
2202   if (G_LIKELY (data->segment.format == GST_FORMAT_TIME)) {
2203     GstClockTime timestamp;
2204
2205     timestamp = GST_BUFFER_DTS (buffer);
2206     if (!GST_CLOCK_TIME_IS_VALID (timestamp))
2207       timestamp = GST_BUFFER_PTS (buffer);
2208
2209     if (GST_CLOCK_TIME_IS_VALID (timestamp))
2210       data->segment.position = timestamp;
2211   }
2212
2213   /* While we have data queued on this pad try to collect stuff */
2214   do {
2215     /* Check if our collected condition is matched and call the collected
2216      * function if it is */
2217     ret = gst_collect_pads_check_collected (pads);
2218     /* when an error occurs, we want to report this back to the caller ASAP
2219      * without having to block if the buffer was not popped */
2220     if (G_UNLIKELY (ret != GST_FLOW_OK))
2221       goto error;
2222
2223     /* data was consumed, we can exit and accept new data */
2224     if (data->buffer == NULL)
2225       break;
2226
2227     /* Having the _INIT here means we don't care about any broadcast up to here
2228      * (most of which occur with STREAM_LOCK held, so could not have happened
2229      * anyway).  We do care about e.g. a remove initiated broadcast as of this
2230      * point.  Putting it here also makes this thread ignores any evt it raised
2231      * itself (as is a usual WAIT semantic).
2232      */
2233     GST_COLLECT_PADS_EVT_INIT (cookie);
2234
2235     /* pad could be removed and re-added */
2236     unref_data (data);
2237     GST_OBJECT_LOCK (pad);
2238     if (G_UNLIKELY ((data = gst_pad_get_element_private (pad)) == NULL))
2239       goto pad_removed;
2240     ref_data (data);
2241     GST_OBJECT_UNLOCK (pad);
2242
2243     GST_DEBUG_OBJECT (pads, "Pad %s:%s has a buffer queued, waiting",
2244         GST_DEBUG_PAD_NAME (pad));
2245
2246     /* wait to be collected, this must happen from another thread triggered
2247      * by the _chain function of another pad. We release the lock so we
2248      * can get stopped or flushed as well. We can however not get EOS
2249      * because we still hold the STREAM_LOCK.
2250      */
2251     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2252     GST_COLLECT_PADS_EVT_WAIT (pads, cookie);
2253     GST_COLLECT_PADS_STREAM_LOCK (pads);
2254
2255     GST_DEBUG_OBJECT (pads, "Pad %s:%s resuming", GST_DEBUG_PAD_NAME (pad));
2256
2257     /* after a signal, we could be stopped */
2258     if (G_UNLIKELY (!pads->priv->started))
2259       goto not_started;
2260     /* check if this pad is flushing */
2261     if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2262                 GST_COLLECT_PADS_STATE_FLUSHING)))
2263       goto flushing;
2264   }
2265   while (data->buffer != NULL);
2266
2267 unlock_done:
2268   GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2269   /* data is definitely NULL if pad_removed goto was run. */
2270   if (data)
2271     unref_data (data);
2272   if (buffer)
2273     gst_buffer_unref (buffer);
2274   return ret;
2275
2276 pad_removed:
2277   {
2278     GST_WARNING ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2279     GST_OBJECT_UNLOCK (pad);
2280     ret = GST_FLOW_NOT_LINKED;
2281     goto unlock_done;
2282   }
2283   /* ERRORS */
2284 no_data:
2285   {
2286     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2287     GST_OBJECT_UNLOCK (pad);
2288     gst_buffer_unref (buffer);
2289     return GST_FLOW_NOT_LINKED;
2290   }
2291 not_started:
2292   {
2293     GST_DEBUG ("not started");
2294     gst_collect_pads_clear (pads, data);
2295     ret = GST_FLOW_FLUSHING;
2296     goto unlock_done;
2297   }
2298 flushing:
2299   {
2300     GST_DEBUG ("pad %s:%s is flushing", GST_DEBUG_PAD_NAME (pad));
2301     gst_collect_pads_clear (pads, data);
2302     ret = GST_FLOW_FLUSHING;
2303     goto unlock_done;
2304   }
2305 eos:
2306   {
2307     /* we should not post an error for this, just inform upstream that
2308      * we don't expect anything anymore */
2309     GST_DEBUG ("pad %s:%s is eos", GST_DEBUG_PAD_NAME (pad));
2310     ret = GST_FLOW_EOS;
2311     goto unlock_done;
2312   }
2313 clipped:
2314   {
2315     GST_DEBUG ("clipped buffer on pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2316     ret = GST_FLOW_OK;
2317     goto unlock_done;
2318   }
2319 error:
2320   {
2321     /* we print the error, the element should post a reasonable error
2322      * message for fatal errors */
2323     GST_DEBUG ("collect failed, reason %d (%s)", ret, gst_flow_get_name (ret));
2324     gst_collect_pads_clear (pads, data);
2325     goto unlock_done;
2326   }
2327 }