collectpads: Use GST_BUFFER_DTS_OR_PTS
[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: (scope call): 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: (scope call): 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: (scope call): 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: (scope call): 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: (scope call): 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: (scope call): 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: (scope call): 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_OR_PTS (buffer);
1478       gst_buffer_unref (buffer);
1479       if (best == NULL || pads->priv->compare_func (pads, data, timestamp,
1480               best, best_time, pads->priv->compare_user_data) < 0) {
1481         best = data;
1482         best_time = timestamp;
1483       }
1484     }
1485   }
1486
1487   /* set earliest time */
1488   *data = best;
1489   *time = best_time;
1490
1491   GST_DEBUG_OBJECT (pads, "best pad %s, best time %" GST_TIME_FORMAT,
1492       best ? GST_PAD_NAME (((GstCollectData *) best)->pad) : "(nil)",
1493       GST_TIME_ARGS (best_time));
1494 }
1495
1496 /*
1497  * Function to recalculate earliest_data and earliest_timestamp. This also calls
1498  * gst_collect_pads_recalculate_waiting
1499  *
1500  * Must be called with STREAM_LOCK.
1501  */
1502 static gboolean
1503 gst_collect_pads_recalculate_full (GstCollectPads * pads)
1504 {
1505   if (pads->priv->earliest_data)
1506     unref_data (pads->priv->earliest_data);
1507   gst_collect_pads_find_best_pad (pads, &pads->priv->earliest_data,
1508       &pads->priv->earliest_time);
1509   if (pads->priv->earliest_data)
1510     ref_data (pads->priv->earliest_data);
1511   return gst_collect_pads_recalculate_waiting (pads);
1512 }
1513
1514 /*
1515  * Default collect callback triggered when #GstCollectPads gathered all data.
1516  *
1517  * Called with STREAM_LOCK.
1518  */
1519 static GstFlowReturn
1520 gst_collect_pads_default_collected (GstCollectPads * pads, gpointer user_data)
1521 {
1522   GstCollectData *best = NULL;
1523   GstBuffer *buffer;
1524   GstFlowReturn ret = GST_FLOW_OK;
1525   GstCollectPadsBufferFunction func;
1526   gpointer buffer_user_data;
1527
1528   g_return_val_if_fail (GST_IS_COLLECT_PADS (pads), GST_FLOW_ERROR);
1529
1530   GST_OBJECT_LOCK (pads);
1531   func = pads->priv->buffer_func;
1532   buffer_user_data = pads->priv->buffer_user_data;
1533   GST_OBJECT_UNLOCK (pads);
1534
1535   g_return_val_if_fail (func != NULL, GST_FLOW_NOT_SUPPORTED);
1536
1537   /* Find the oldest pad at all cost */
1538   if (gst_collect_pads_recalculate_full (pads)) {
1539     /* waiting was switched on,
1540      * so give another thread a chance to deliver a possibly
1541      * older buffer; don't charge on yet with the current oldest */
1542     ret = GST_FLOW_OK;
1543     goto done;
1544   }
1545
1546   best = pads->priv->earliest_data;
1547
1548   /* No data collected means EOS. */
1549   if (G_UNLIKELY (best == NULL)) {
1550     ret = func (pads, best, NULL, buffer_user_data);
1551     if (ret == GST_FLOW_OK)
1552       ret = GST_FLOW_EOS;
1553     goto done;
1554   }
1555
1556   /* make sure that the pad we take a buffer from is waiting;
1557    * otherwise popping a buffer will seem not to have happened
1558    * and collectpads can get into a busy loop */
1559   gst_collect_pads_set_waiting (pads, best, TRUE);
1560
1561   /* Send buffer */
1562   buffer = gst_collect_pads_pop (pads, best);
1563   ret = func (pads, best, buffer, buffer_user_data);
1564
1565   /* maybe non-waiting was forced to waiting above due to
1566    * newsegment events coming too sparsely,
1567    * so re-check to restore state to avoid hanging/waiting */
1568   gst_collect_pads_recalculate_full (pads);
1569
1570 done:
1571   return ret;
1572 }
1573
1574 /*
1575  * Default timestamp compare function.
1576  */
1577 static gint
1578 gst_collect_pads_default_compare_func (GstCollectPads * pads,
1579     GstCollectData * data1, GstClockTime timestamp1,
1580     GstCollectData * data2, GstClockTime timestamp2, gpointer user_data)
1581 {
1582
1583   GST_LOG_OBJECT (pads, "comparing %" GST_TIME_FORMAT
1584       " and %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp1),
1585       GST_TIME_ARGS (timestamp2));
1586   /* non-valid timestamps go first as they are probably headers or so */
1587   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (timestamp1)))
1588     return GST_CLOCK_TIME_IS_VALID (timestamp2) ? -1 : 0;
1589
1590   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (timestamp2)))
1591     return 1;
1592
1593   /* compare timestamp */
1594   if (timestamp1 < timestamp2)
1595     return -1;
1596
1597   if (timestamp1 > timestamp2)
1598     return 1;
1599
1600   return 0;
1601 }
1602
1603 /* called with STREAM_LOCK */
1604 static void
1605 gst_collect_pads_handle_position_update (GstCollectPads * pads,
1606     GstCollectData * data, GstClockTime new_pos)
1607 {
1608   gint cmp_res;
1609
1610   /* If oldest time is not known, or current pad got newsegment;
1611    * recalculate the state */
1612   if (!pads->priv->earliest_data || pads->priv->earliest_data == data) {
1613     gst_collect_pads_recalculate_full (pads);
1614     goto exit;
1615   }
1616
1617   /* Check if the waiting state of the pad should change. */
1618   cmp_res =
1619       pads->priv->compare_func (pads, data, new_pos,
1620       pads->priv->earliest_data, pads->priv->earliest_time,
1621       pads->priv->compare_user_data);
1622
1623   if (cmp_res > 0)
1624     /* Stop waiting */
1625     gst_collect_pads_set_waiting (pads, data, FALSE);
1626
1627 exit:
1628   return;
1629
1630 }
1631
1632 static GstClockTime
1633 gst_collect_pads_clip_time (GstCollectPads * pads, GstCollectData * data,
1634     GstClockTime time)
1635 {
1636   GstClockTime otime = time;
1637   GstBuffer *in, *out = NULL;
1638
1639   if (pads->priv->clip_func) {
1640     in = gst_buffer_new ();
1641     GST_BUFFER_PTS (in) = time;
1642     GST_BUFFER_DTS (in) = GST_CLOCK_TIME_NONE;
1643     pads->priv->clip_func (pads, data, in, &out, pads->priv->clip_user_data);
1644     if (out) {
1645       otime = GST_BUFFER_PTS (out);
1646       gst_buffer_unref (out);
1647     } else {
1648       /* FIXME should distinguish between ahead or after segment,
1649        * let's assume after segment and use some large time ... */
1650       otime = G_MAXINT64 / 2;
1651     }
1652   }
1653
1654   return otime;
1655 }
1656
1657 /**
1658  * gst_collect_pads_event_default:
1659  * @pads: the collectpads to use
1660  * @data: collect data of corresponding pad
1661  * @event: event being processed
1662  * @discard: process but do not send event downstream
1663  *
1664  * Default #GstCollectPads event handling that elements should always
1665  * chain up to to ensure proper operation.  Element might however indicate
1666  * event should not be forwarded downstream.
1667  */
1668 gboolean
1669 gst_collect_pads_event_default (GstCollectPads * pads, GstCollectData * data,
1670     GstEvent * event, gboolean discard)
1671 {
1672   gboolean res = TRUE;
1673   GstCollectPadsBufferFunction buffer_func;
1674   GstObject *parent;
1675   GstPad *pad;
1676
1677   GST_OBJECT_LOCK (pads);
1678   buffer_func = pads->priv->buffer_func;
1679   GST_OBJECT_UNLOCK (pads);
1680
1681   pad = data->pad;
1682   parent = GST_OBJECT_PARENT (pad);
1683
1684   switch (GST_EVENT_TYPE (event)) {
1685     case GST_EVENT_FLUSH_START:
1686     {
1687       if (g_atomic_int_get (&pads->priv->seeking)) {
1688         /* drop all but the first FLUSH_STARTs when seeking */
1689         if (!g_atomic_int_compare_and_exchange (&pads->
1690                 priv->pending_flush_start, TRUE, FALSE))
1691           goto eat;
1692
1693         /* unblock collect pads */
1694         gst_pad_event_default (pad, parent, event);
1695         event = NULL;
1696
1697         GST_COLLECT_PADS_STREAM_LOCK (pads);
1698         /* Start flushing. We never call gst_collect_pads_set_flushing (FALSE), we
1699          * instead wait until each pad gets its FLUSH_STOP and let that reset the pad to
1700          * non-flushing (which happens in gst_collect_pads_event_default).
1701          */
1702         gst_collect_pads_set_flushing (pads, TRUE);
1703
1704         if (pads->priv->flush_func)
1705           pads->priv->flush_func (pads, pads->priv->flush_user_data);
1706
1707         g_atomic_int_set (&pads->priv->pending_flush_stop, TRUE);
1708         GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1709
1710         goto eat;
1711       } else {
1712         /* forward event to unblock check_collected */
1713         GST_DEBUG_OBJECT (pad, "forwarding flush start");
1714         res = gst_pad_event_default (pad, parent, event);
1715         event = NULL;
1716
1717         /* now unblock the chain function.
1718          * no cond per pad, so they all unblock,
1719          * non-flushing block again */
1720         GST_COLLECT_PADS_STREAM_LOCK (pads);
1721         GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_FLUSHING);
1722         gst_collect_pads_clear (pads, data);
1723
1724         /* cater for possible default muxing functionality */
1725         if (buffer_func) {
1726           /* restore to initial state */
1727           gst_collect_pads_set_waiting (pads, data, TRUE);
1728           /* if the current pad is affected, reset state, recalculate later */
1729           if (pads->priv->earliest_data == data) {
1730             unref_data (data);
1731             pads->priv->earliest_data = NULL;
1732             pads->priv->earliest_time = GST_CLOCK_TIME_NONE;
1733           }
1734         }
1735
1736         GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1737
1738         goto eat;
1739       }
1740     }
1741     case GST_EVENT_FLUSH_STOP:
1742     {
1743       /* flush the 1 buffer queue */
1744       GST_COLLECT_PADS_STREAM_LOCK (pads);
1745       GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_FLUSHING);
1746       gst_collect_pads_clear (pads, data);
1747       /* we need new segment info after the flush */
1748       gst_segment_init (&data->segment, GST_FORMAT_UNDEFINED);
1749       GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_NEW_SEGMENT);
1750       /* if the pad was EOS, remove the EOS flag and
1751        * decrement the number of eospads */
1752       if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
1753                   GST_COLLECT_PADS_STATE_EOS))) {
1754         if (!GST_COLLECT_PADS_STATE_IS_SET (data,
1755                 GST_COLLECT_PADS_STATE_WAITING))
1756           pads->priv->queuedpads++;
1757         if (!g_atomic_int_get (&pads->priv->seeking)) {
1758           pads->priv->eospads--;
1759         }
1760         GST_COLLECT_PADS_STATE_UNSET (data, GST_COLLECT_PADS_STATE_EOS);
1761       }
1762       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1763
1764       if (g_atomic_int_get (&pads->priv->seeking)) {
1765         if (g_atomic_int_compare_and_exchange (&pads->priv->pending_flush_stop,
1766                 TRUE, FALSE))
1767           goto forward;
1768         else
1769           goto eat;
1770       } else {
1771         goto forward;
1772       }
1773     }
1774     case GST_EVENT_EOS:
1775     {
1776       GST_COLLECT_PADS_STREAM_LOCK (pads);
1777       /* if the pad was not EOS, make it EOS and so we
1778        * have one more eospad */
1779       if (G_LIKELY (!GST_COLLECT_PADS_STATE_IS_SET (data,
1780                   GST_COLLECT_PADS_STATE_EOS))) {
1781         GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_EOS);
1782         if (!GST_COLLECT_PADS_STATE_IS_SET (data,
1783                 GST_COLLECT_PADS_STATE_WAITING))
1784           pads->priv->queuedpads--;
1785         pads->priv->eospads++;
1786       }
1787       /* check if we need collecting anything, we ignore the result. */
1788       gst_collect_pads_check_collected (pads);
1789       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1790
1791       goto eat;
1792     }
1793     case GST_EVENT_SEGMENT:
1794     {
1795       GstSegment seg;
1796
1797       GST_COLLECT_PADS_STREAM_LOCK (pads);
1798
1799       gst_event_copy_segment (event, &seg);
1800
1801       GST_DEBUG_OBJECT (data->pad, "got segment %" GST_SEGMENT_FORMAT, &seg);
1802
1803       /* default collection can not handle other segment formats than time */
1804       if (buffer_func && seg.format != GST_FORMAT_TIME) {
1805         GST_WARNING_OBJECT (pads, "GstCollectPads default collecting "
1806             "can only handle time segments. Non time segment ignored.");
1807         goto newsegment_done;
1808       }
1809
1810       /* need to update segment first */
1811       data->segment = seg;
1812       GST_COLLECT_PADS_STATE_SET (data, GST_COLLECT_PADS_STATE_NEW_SEGMENT);
1813
1814       /* now we can use for e.g. running time */
1815       seg.position =
1816           gst_collect_pads_clip_time (pads, data, seg.start + seg.offset);
1817       /* update again */
1818       data->segment = seg;
1819
1820       /* default muxing functionality */
1821       if (!buffer_func)
1822         goto newsegment_done;
1823
1824       gst_collect_pads_handle_position_update (pads, data, seg.position);
1825
1826     newsegment_done:
1827       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1828       /* we must not forward this event since multiple segments will be
1829        * accumulated and this is certainly not what we want. */
1830       goto eat;
1831     }
1832     case GST_EVENT_GAP:
1833     {
1834       GstClockTime start, duration;
1835
1836       GST_COLLECT_PADS_STREAM_LOCK (pads);
1837
1838       gst_event_parse_gap (event, &start, &duration);
1839       /* FIXME, handle reverse playback case */
1840       if (GST_CLOCK_TIME_IS_VALID (duration))
1841         start += duration;
1842       /* we do not expect another buffer until after gap,
1843        * so that is our position now */
1844       data->segment.position = gst_collect_pads_clip_time (pads, data, start);
1845
1846       gst_collect_pads_handle_position_update (pads, data,
1847           data->segment.position);
1848
1849       GST_COLLECT_PADS_STREAM_UNLOCK (pads);
1850       goto eat;
1851     }
1852     case GST_EVENT_STREAM_START:
1853       /* drop stream start events, element must create its own start event,
1854        * we can't just forward the first random stream start event we get */
1855       goto eat;
1856     case GST_EVENT_CAPS:
1857       goto eat;
1858     default:
1859       /* forward other events */
1860       goto forward;
1861   }
1862
1863 eat:
1864   if (event)
1865     gst_event_unref (event);
1866   return res;
1867
1868 forward:
1869   if (discard)
1870     goto eat;
1871   else
1872     return gst_pad_event_default (pad, parent, event);
1873 }
1874
1875 typedef struct
1876 {
1877   GstEvent *event;
1878   gboolean result;
1879 } EventData;
1880
1881 static gboolean
1882 event_forward_func (GstPad * pad, EventData * data)
1883 {
1884   gboolean ret = TRUE;
1885   GstPad *peer = gst_pad_get_peer (pad);
1886
1887   if (peer) {
1888     ret = gst_pad_send_event (peer, gst_event_ref (data->event));
1889     gst_object_unref (peer);
1890   }
1891
1892   data->result &= ret;
1893   /* Always send to all pads */
1894   return FALSE;
1895 }
1896
1897 static gboolean
1898 forward_event_to_all_sinkpads (GstPad * srcpad, GstEvent * event)
1899 {
1900   EventData data;
1901
1902   data.event = event;
1903   data.result = TRUE;
1904
1905   gst_pad_forward (srcpad, (GstPadForwardFunction) event_forward_func, &data);
1906
1907   gst_event_unref (event);
1908
1909   return data.result;
1910 }
1911
1912 /**
1913  * gst_collect_pads_src_event_default:
1914  * @pads: the #GstCollectPads to use
1915  * @pad: src #GstPad that received the event
1916  * @event: event being processed
1917  *
1918  * Default #GstCollectPads event handling for the src pad of elements.
1919  * Elements can chain up to this to let flushing seek event handling
1920  * be done by #GstCollectPads.
1921  *
1922  * Since: 1.4
1923  */
1924 gboolean
1925 gst_collect_pads_src_event_default (GstCollectPads * pads, GstPad * pad,
1926     GstEvent * event)
1927 {
1928   GstObject *parent;
1929   gboolean res = TRUE;
1930
1931   parent = GST_OBJECT_PARENT (pad);
1932
1933   switch (GST_EVENT_TYPE (event)) {
1934     case GST_EVENT_SEEK:{
1935       GstSeekFlags flags;
1936
1937       pads->priv->eospads = 0;
1938
1939       GST_INFO_OBJECT (pads, "starting seek");
1940
1941       gst_event_parse_seek (event, NULL, NULL, &flags, NULL, NULL, NULL, NULL);
1942       if (flags & GST_SEEK_FLAG_FLUSH) {
1943         g_atomic_int_set (&pads->priv->seeking, TRUE);
1944         g_atomic_int_set (&pads->priv->pending_flush_start, TRUE);
1945         /* forward the seek upstream */
1946         res = forward_event_to_all_sinkpads (pad, event);
1947         event = NULL;
1948         if (!res) {
1949           g_atomic_int_set (&pads->priv->seeking, FALSE);
1950           g_atomic_int_set (&pads->priv->pending_flush_start, FALSE);
1951         }
1952       }
1953
1954       GST_INFO_OBJECT (pads, "seek done, result: %d", res);
1955
1956       break;
1957     }
1958     default:
1959       break;
1960   }
1961
1962   if (event)
1963     res = gst_pad_event_default (pad, parent, event);
1964
1965   return res;
1966 }
1967
1968 static gboolean
1969 gst_collect_pads_event_default_internal (GstCollectPads * pads,
1970     GstCollectData * data, GstEvent * event, gpointer user_data)
1971 {
1972   return gst_collect_pads_event_default (pads, data, event, FALSE);
1973 }
1974
1975 static gboolean
1976 gst_collect_pads_event (GstPad * pad, GstObject * parent, GstEvent * event)
1977 {
1978   gboolean res = FALSE, need_unlock = FALSE;
1979   GstCollectData *data;
1980   GstCollectPads *pads;
1981   GstCollectPadsEventFunction event_func;
1982   gpointer event_user_data;
1983
1984   /* some magic to get the managing collect_pads */
1985   GST_OBJECT_LOCK (pad);
1986   data = (GstCollectData *) gst_pad_get_element_private (pad);
1987   if (G_UNLIKELY (data == NULL))
1988     goto pad_removed;
1989   ref_data (data);
1990   GST_OBJECT_UNLOCK (pad);
1991
1992   res = FALSE;
1993
1994   pads = data->collect;
1995
1996   GST_DEBUG_OBJECT (data->pad, "Got %s event on sink pad",
1997       GST_EVENT_TYPE_NAME (event));
1998
1999   GST_OBJECT_LOCK (pads);
2000   event_func = pads->priv->event_func;
2001   event_user_data = pads->priv->event_user_data;
2002   GST_OBJECT_UNLOCK (pads);
2003
2004   if (GST_EVENT_IS_SERIALIZED (event)) {
2005     GST_COLLECT_PADS_STREAM_LOCK (pads);
2006     need_unlock = TRUE;
2007   }
2008
2009   if (G_LIKELY (event_func)) {
2010     res = event_func (pads, data, event, event_user_data);
2011   }
2012
2013   if (need_unlock)
2014     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2015
2016   unref_data (data);
2017   return res;
2018
2019   /* ERRORS */
2020 pad_removed:
2021   {
2022     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2023     GST_OBJECT_UNLOCK (pad);
2024     return FALSE;
2025   }
2026 }
2027
2028 /**
2029  * gst_collect_pads_query_default:
2030  * @pads: the collectpads to use
2031  * @data: collect data of corresponding pad
2032  * @query: query being processed
2033  * @discard: process but do not send event downstream
2034  *
2035  * Default #GstCollectPads query handling that elements should always
2036  * chain up to to ensure proper operation.  Element might however indicate
2037  * query should not be forwarded downstream.
2038  */
2039 gboolean
2040 gst_collect_pads_query_default (GstCollectPads * pads, GstCollectData * data,
2041     GstQuery * query, gboolean discard)
2042 {
2043   gboolean res = TRUE;
2044   GstObject *parent;
2045   GstPad *pad;
2046
2047   pad = data->pad;
2048   parent = GST_OBJECT_PARENT (pad);
2049
2050   switch (GST_QUERY_TYPE (query)) {
2051     case GST_QUERY_SEEKING:
2052     {
2053       GstFormat format;
2054
2055       /* don't pass it along as some (file)sink might claim it does
2056        * whereas with a collectpads in between that will not likely work */
2057       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2058       gst_query_set_seeking (query, format, FALSE, 0, -1);
2059       res = TRUE;
2060       discard = TRUE;
2061       break;
2062     }
2063     default:
2064       break;
2065   }
2066
2067   if (!discard)
2068     return gst_pad_query_default (pad, parent, query);
2069   else
2070     return res;
2071 }
2072
2073 static gboolean
2074 gst_collect_pads_query_default_internal (GstCollectPads * pads,
2075     GstCollectData * data, GstQuery * query, gpointer user_data)
2076 {
2077   return gst_collect_pads_query_default (pads, data, query, FALSE);
2078 }
2079
2080 static gboolean
2081 gst_collect_pads_query (GstPad * pad, GstObject * parent, GstQuery * query)
2082 {
2083   gboolean res = FALSE, need_unlock = FALSE;
2084   GstCollectData *data;
2085   GstCollectPads *pads;
2086   GstCollectPadsQueryFunction query_func;
2087   gpointer query_user_data;
2088
2089   GST_DEBUG_OBJECT (pad, "Got %s query on sink pad",
2090       GST_QUERY_TYPE_NAME (query));
2091
2092   /* some magic to get the managing collect_pads */
2093   GST_OBJECT_LOCK (pad);
2094   data = (GstCollectData *) gst_pad_get_element_private (pad);
2095   if (G_UNLIKELY (data == NULL))
2096     goto pad_removed;
2097   ref_data (data);
2098   GST_OBJECT_UNLOCK (pad);
2099
2100   pads = data->collect;
2101
2102   GST_OBJECT_LOCK (pads);
2103   query_func = pads->priv->query_func;
2104   query_user_data = pads->priv->query_user_data;
2105   GST_OBJECT_UNLOCK (pads);
2106
2107   if (GST_QUERY_IS_SERIALIZED (query)) {
2108     GST_COLLECT_PADS_STREAM_LOCK (pads);
2109     need_unlock = TRUE;
2110   }
2111
2112   if (G_LIKELY (query_func)) {
2113     res = query_func (pads, data, query, query_user_data);
2114   }
2115
2116   if (need_unlock)
2117     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2118
2119   unref_data (data);
2120   return res;
2121
2122   /* ERRORS */
2123 pad_removed:
2124   {
2125     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2126     GST_OBJECT_UNLOCK (pad);
2127     return FALSE;
2128   }
2129 }
2130
2131
2132 /* For each buffer we receive we check if our collected condition is reached
2133  * and if so we call the collected function. When this is done we check if
2134  * data has been unqueued. If data is still queued we wait holding the stream
2135  * lock to make sure no EOS event can happen while we are ready to be
2136  * collected 
2137  */
2138 static GstFlowReturn
2139 gst_collect_pads_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2140 {
2141   GstCollectData *data;
2142   GstCollectPads *pads;
2143   GstFlowReturn ret;
2144   GstBuffer **buffer_p;
2145   guint32 cookie;
2146
2147   GST_DEBUG ("Got buffer for pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2148
2149   /* some magic to get the managing collect_pads */
2150   GST_OBJECT_LOCK (pad);
2151   data = (GstCollectData *) gst_pad_get_element_private (pad);
2152   if (G_UNLIKELY (data == NULL))
2153     goto no_data;
2154   ref_data (data);
2155   GST_OBJECT_UNLOCK (pad);
2156
2157   pads = data->collect;
2158
2159   GST_COLLECT_PADS_STREAM_LOCK (pads);
2160   /* if not started, bail out */
2161   if (G_UNLIKELY (!pads->priv->started))
2162     goto not_started;
2163   /* check if this pad is flushing */
2164   if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2165               GST_COLLECT_PADS_STATE_FLUSHING)))
2166     goto flushing;
2167   /* pad was EOS, we can refuse this data */
2168   if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2169               GST_COLLECT_PADS_STATE_EOS)))
2170     goto eos;
2171
2172   /* see if we need to clip */
2173   if (pads->priv->clip_func) {
2174     GstBuffer *outbuf = NULL;
2175     ret =
2176         pads->priv->clip_func (pads, data, buffer, &outbuf,
2177         pads->priv->clip_user_data);
2178     buffer = outbuf;
2179
2180     if (G_UNLIKELY (outbuf == NULL))
2181       goto clipped;
2182
2183     if (G_UNLIKELY (ret == GST_FLOW_EOS))
2184       goto eos;
2185     else if (G_UNLIKELY (ret != GST_FLOW_OK))
2186       goto error;
2187   }
2188
2189   GST_DEBUG_OBJECT (pads, "Queuing buffer %p for pad %s:%s", buffer,
2190       GST_DEBUG_PAD_NAME (pad));
2191
2192   /* One more pad has data queued */
2193   if (GST_COLLECT_PADS_STATE_IS_SET (data, GST_COLLECT_PADS_STATE_WAITING))
2194     pads->priv->queuedpads++;
2195   buffer_p = &data->buffer;
2196   gst_buffer_replace (buffer_p, buffer);
2197
2198   /* update segment last position if in TIME */
2199   if (G_LIKELY (data->segment.format == GST_FORMAT_TIME)) {
2200     GstClockTime timestamp;
2201
2202     timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
2203
2204     if (GST_CLOCK_TIME_IS_VALID (timestamp))
2205       data->segment.position = timestamp;
2206   }
2207
2208   /* While we have data queued on this pad try to collect stuff */
2209   do {
2210     /* Check if our collected condition is matched and call the collected
2211      * function if it is */
2212     ret = gst_collect_pads_check_collected (pads);
2213     /* when an error occurs, we want to report this back to the caller ASAP
2214      * without having to block if the buffer was not popped */
2215     if (G_UNLIKELY (ret != GST_FLOW_OK))
2216       goto error;
2217
2218     /* data was consumed, we can exit and accept new data */
2219     if (data->buffer == NULL)
2220       break;
2221
2222     /* Having the _INIT here means we don't care about any broadcast up to here
2223      * (most of which occur with STREAM_LOCK held, so could not have happened
2224      * anyway).  We do care about e.g. a remove initiated broadcast as of this
2225      * point.  Putting it here also makes this thread ignores any evt it raised
2226      * itself (as is a usual WAIT semantic).
2227      */
2228     GST_COLLECT_PADS_EVT_INIT (cookie);
2229
2230     /* pad could be removed and re-added */
2231     unref_data (data);
2232     GST_OBJECT_LOCK (pad);
2233     if (G_UNLIKELY ((data = gst_pad_get_element_private (pad)) == NULL))
2234       goto pad_removed;
2235     ref_data (data);
2236     GST_OBJECT_UNLOCK (pad);
2237
2238     GST_DEBUG_OBJECT (pads, "Pad %s:%s has a buffer queued, waiting",
2239         GST_DEBUG_PAD_NAME (pad));
2240
2241     /* wait to be collected, this must happen from another thread triggered
2242      * by the _chain function of another pad. We release the lock so we
2243      * can get stopped or flushed as well. We can however not get EOS
2244      * because we still hold the STREAM_LOCK.
2245      */
2246     GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2247     GST_COLLECT_PADS_EVT_WAIT (pads, cookie);
2248     GST_COLLECT_PADS_STREAM_LOCK (pads);
2249
2250     GST_DEBUG_OBJECT (pads, "Pad %s:%s resuming", GST_DEBUG_PAD_NAME (pad));
2251
2252     /* after a signal, we could be stopped */
2253     if (G_UNLIKELY (!pads->priv->started))
2254       goto not_started;
2255     /* check if this pad is flushing */
2256     if (G_UNLIKELY (GST_COLLECT_PADS_STATE_IS_SET (data,
2257                 GST_COLLECT_PADS_STATE_FLUSHING)))
2258       goto flushing;
2259   }
2260   while (data->buffer != NULL);
2261
2262 unlock_done:
2263   GST_COLLECT_PADS_STREAM_UNLOCK (pads);
2264   /* data is definitely NULL if pad_removed goto was run. */
2265   if (data)
2266     unref_data (data);
2267   if (buffer)
2268     gst_buffer_unref (buffer);
2269   return ret;
2270
2271 pad_removed:
2272   {
2273     GST_WARNING ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2274     GST_OBJECT_UNLOCK (pad);
2275     ret = GST_FLOW_NOT_LINKED;
2276     goto unlock_done;
2277   }
2278   /* ERRORS */
2279 no_data:
2280   {
2281     GST_DEBUG ("%s got removed from collectpads", GST_OBJECT_NAME (pad));
2282     GST_OBJECT_UNLOCK (pad);
2283     gst_buffer_unref (buffer);
2284     return GST_FLOW_NOT_LINKED;
2285   }
2286 not_started:
2287   {
2288     GST_DEBUG ("not started");
2289     gst_collect_pads_clear (pads, data);
2290     ret = GST_FLOW_FLUSHING;
2291     goto unlock_done;
2292   }
2293 flushing:
2294   {
2295     GST_DEBUG ("pad %s:%s is flushing", GST_DEBUG_PAD_NAME (pad));
2296     gst_collect_pads_clear (pads, data);
2297     ret = GST_FLOW_FLUSHING;
2298     goto unlock_done;
2299   }
2300 eos:
2301   {
2302     /* we should not post an error for this, just inform upstream that
2303      * we don't expect anything anymore */
2304     GST_DEBUG ("pad %s:%s is eos", GST_DEBUG_PAD_NAME (pad));
2305     ret = GST_FLOW_EOS;
2306     goto unlock_done;
2307   }
2308 clipped:
2309   {
2310     GST_DEBUG ("clipped buffer on pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2311     ret = GST_FLOW_OK;
2312     goto unlock_done;
2313   }
2314 error:
2315   {
2316     /* we print the error, the element should post a reasonable error
2317      * message for fatal errors */
2318     GST_DEBUG ("collect failed, reason %d (%s)", ret, gst_flow_get_name (ret));
2319     gst_collect_pads_clear (pads, data);
2320     goto unlock_done;
2321   }
2322 }