typefind: Do typefinding from a separate thread and not from the state change function
[platform/upstream/gstreamer.git] / plugins / elements / gsttypefindelement.c
1 /* GStreamer
2  * Copyright (C) 2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
3  *
4  * gsttypefindelement.c: element that detects type of stream
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21 /**
22  * SECTION:element-typefind
23  *
24  * Determines the media-type of a stream. It applies typefind functions in the
25  * order of their rank. One the type has been deteted it sets its src pad caps
26  * to the found media type.
27  *
28  * Whenever a type is found the #GstTypeFindElement::have-type signal is
29  * emitted, either from the streaming thread or the application thread
30  * (the latter may happen when typefinding is done pull-based from the
31  * state change function).
32  *
33  * Plugins can register custom typefinders by using #GstTypeFindFactory.
34  */
35
36 /* FIXME: need a better solution for non-seekable streams */
37
38 /* way of operation:
39  * 1) get a list of all typefind functions sorted best to worst
40  * 2) if all elements have been called with all requested data goto 8
41  * 3) call all functions once with all available data
42  * 4) if a function returns a value >= PROP_MAXIMUM goto 8
43  * 5) all functions with a result > PROP_MINIMUM or functions that did not get
44  *    all requested data (where peek returned NULL) stay in list
45  * 6) seek to requested offset of best function that still has open data
46  *    requests
47  * 7) goto 2
48  * 8) take best available result and use its caps
49  *
50  * The element has two scheduling modes:
51  *
52  * 1) chain based, it will collect buffers and run the typefind function on
53  *    the buffer until something is found.
54  * 2) getrange based, it will proxy the getrange function to the sinkpad. It
55  *    is assumed that the peer element is happy with whatever format we
56  *    eventually read.
57  *
58  * By default it tries to do pull based typefinding (this avoids joining
59  * received buffers and holding them back in store.)
60  *
61  * When the element has no connected srcpad, and the sinkpad can operate in
62  * getrange based mode, the element starts its own task to figure out the
63  * type of the stream.
64  *
65  * Most of the actual implementation is in libs/gst/base/gsttypefindhelper.c.
66  */
67
68 #ifdef HAVE_CONFIG_H
69 #  include "config.h"
70 #endif
71
72 #include "gst/gst_private.h"
73
74 #include "gsttypefindelement.h"
75 #include "gst/gst-i18n-lib.h"
76 #include "gst/base/gsttypefindhelper.h"
77
78 #include <gst/gsttypefind.h>
79 #include <gst/gstutils.h>
80 #include <gst/gsterror.h>
81
82 GST_DEBUG_CATEGORY_STATIC (gst_type_find_element_debug);
83 #define GST_CAT_DEFAULT gst_type_find_element_debug
84
85 /* generic templates */
86 static GstStaticPadTemplate type_find_element_sink_template =
87 GST_STATIC_PAD_TEMPLATE ("sink",
88     GST_PAD_SINK,
89     GST_PAD_ALWAYS,
90     GST_STATIC_CAPS_ANY);
91
92 static GstStaticPadTemplate type_find_element_src_template =
93 GST_STATIC_PAD_TEMPLATE ("src",
94     GST_PAD_SRC,
95     GST_PAD_ALWAYS,
96     GST_STATIC_CAPS_ANY);
97
98 /* Require at least 2kB of data before we attempt typefinding in chain-mode.
99  * 128kB is massive overkill for the maximum, but doesn't do any harm */
100 #define TYPE_FIND_MIN_SIZE   (2*1024)
101 #define TYPE_FIND_MAX_SIZE (128*1024)
102
103 /* TypeFind signals and args */
104 enum
105 {
106   HAVE_TYPE,
107   LAST_SIGNAL
108 };
109 enum
110 {
111   PROP_0,
112   PROP_CAPS,
113   PROP_MINIMUM,
114   PROP_MAXIMUM,
115   PROP_FORCE_CAPS,
116   PROP_LAST
117 };
118 enum
119 {
120   MODE_NORMAL,                  /* act as identity */
121   MODE_TYPEFIND,                /* do typefinding  */
122   MODE_ERROR                    /* had fatal error */
123 };
124
125
126 #define _do_init \
127     GST_DEBUG_CATEGORY_INIT (gst_type_find_element_debug, "typefind",           \
128         GST_DEBUG_BG_YELLOW | GST_DEBUG_FG_GREEN, "type finding element");
129 #define gst_type_find_element_parent_class parent_class
130 G_DEFINE_TYPE_WITH_CODE (GstTypeFindElement, gst_type_find_element,
131     GST_TYPE_ELEMENT, _do_init);
132
133 static void gst_type_find_element_dispose (GObject * object);
134 static void gst_type_find_element_set_property (GObject * object,
135     guint prop_id, const GValue * value, GParamSpec * pspec);
136 static void gst_type_find_element_get_property (GObject * object,
137     guint prop_id, GValue * value, GParamSpec * pspec);
138
139 #if 0
140 static const GstEventMask *gst_type_find_element_src_event_mask (GstPad * pad);
141 #endif
142
143 static gboolean gst_type_find_element_src_event (GstPad * pad,
144     GstObject * parent, GstEvent * event);
145 static gboolean gst_type_find_handle_src_query (GstPad * pad,
146     GstObject * parent, GstQuery * query);
147
148 static gboolean gst_type_find_element_sink_event (GstPad * pad,
149     GstObject * parent, GstEvent * event);
150 static gboolean gst_type_find_element_setcaps (GstTypeFindElement * typefind,
151     GstCaps * caps);
152 static GstFlowReturn gst_type_find_element_chain (GstPad * sinkpad,
153     GstObject * parent, GstBuffer * buffer);
154 static GstFlowReturn gst_type_find_element_getrange (GstPad * srcpad,
155     GstObject * parent, guint64 offset, guint length, GstBuffer ** buffer);
156
157 static GstStateChangeReturn
158 gst_type_find_element_change_state (GstElement * element,
159     GstStateChange transition);
160 static gboolean gst_type_find_element_activate_sink (GstPad * pad,
161     GstObject * parent);
162 static gboolean gst_type_find_element_activate_sink_mode (GstPad * pad,
163     GstObject * parent, GstPadMode mode, gboolean active);
164 static gboolean gst_type_find_element_activate_src_mode (GstPad * pad,
165     GstObject * parent, GstPadMode mode, gboolean active);
166 static GstFlowReturn
167 gst_type_find_element_chain_do_typefinding (GstTypeFindElement * typefind,
168     gboolean check_avail);
169 static void gst_type_find_element_send_cached_events (GstTypeFindElement *
170     typefind);
171
172 static void gst_type_find_element_loop (GstPad * pad);
173
174 static guint gst_type_find_element_signals[LAST_SIGNAL] = { 0 };
175
176 static void
177 gst_type_find_element_have_type (GstTypeFindElement * typefind,
178     guint probability, const GstCaps * caps)
179 {
180   GstCaps *copy;
181
182   g_assert (caps != NULL);
183
184   GST_INFO_OBJECT (typefind, "found caps %" GST_PTR_FORMAT ", probability=%u",
185       caps, probability);
186
187   GST_OBJECT_LOCK (typefind);
188   if (typefind->caps)
189     gst_caps_unref (typefind->caps);
190   typefind->caps = gst_caps_copy (caps);
191   copy = gst_caps_ref (typefind->caps);
192   GST_OBJECT_UNLOCK (typefind);
193
194   gst_pad_push_event (typefind->src, gst_event_new_caps (copy));
195   gst_caps_unref (copy);
196 }
197
198 static void
199 gst_type_find_element_class_init (GstTypeFindElementClass * typefind_class)
200 {
201   GObjectClass *gobject_class = G_OBJECT_CLASS (typefind_class);
202   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (typefind_class);
203
204   gobject_class->set_property = gst_type_find_element_set_property;
205   gobject_class->get_property = gst_type_find_element_get_property;
206   gobject_class->dispose = gst_type_find_element_dispose;
207
208   g_object_class_install_property (gobject_class, PROP_CAPS,
209       g_param_spec_boxed ("caps", _("caps"),
210           _("detected capabilities in stream"), GST_TYPE_CAPS,
211           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
212   g_object_class_install_property (gobject_class, PROP_MINIMUM,
213       g_param_spec_uint ("minimum", _("minimum"),
214           "minimum probability required to accept caps", GST_TYPE_FIND_MINIMUM,
215           GST_TYPE_FIND_MAXIMUM, GST_TYPE_FIND_MINIMUM,
216           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
217   g_object_class_install_property (gobject_class, PROP_MAXIMUM,
218       g_param_spec_uint ("maximum", _("maximum"),
219           "probability to stop typefinding (deprecated; non-functional)",
220           GST_TYPE_FIND_MINIMUM, GST_TYPE_FIND_MAXIMUM, GST_TYPE_FIND_MAXIMUM,
221           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
222   g_object_class_install_property (gobject_class, PROP_FORCE_CAPS,
223       g_param_spec_boxed ("force-caps", _("force caps"),
224           _("force caps without doing a typefind"), GST_TYPE_CAPS,
225           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
226   /**
227    * GstTypeFindElement::have-type:
228    * @typefind: the typefind instance
229    * @probability: the probability of the type found
230    * @caps: the caps of the type found
231    *
232    * This signal gets emitted when the type and its probability has
233    * been found.
234    */
235   gst_type_find_element_signals[HAVE_TYPE] = g_signal_new ("have-type",
236       G_TYPE_FROM_CLASS (typefind_class), G_SIGNAL_RUN_FIRST,
237       G_STRUCT_OFFSET (GstTypeFindElementClass, have_type), NULL, NULL,
238       gst_marshal_VOID__UINT_BOXED, G_TYPE_NONE, 2,
239       G_TYPE_UINT, GST_TYPE_CAPS | G_SIGNAL_TYPE_STATIC_SCOPE);
240
241   typefind_class->have_type =
242       GST_DEBUG_FUNCPTR (gst_type_find_element_have_type);
243
244   gst_element_class_set_details_simple (gstelement_class,
245       "TypeFind",
246       "Generic",
247       "Finds the media type of a stream",
248       "Benjamin Otte <in7y118@public.uni-hamburg.de>");
249   gst_element_class_add_pad_template (gstelement_class,
250       gst_static_pad_template_get (&type_find_element_src_template));
251   gst_element_class_add_pad_template (gstelement_class,
252       gst_static_pad_template_get (&type_find_element_sink_template));
253
254   gstelement_class->change_state =
255       GST_DEBUG_FUNCPTR (gst_type_find_element_change_state);
256 }
257
258 static void
259 gst_type_find_element_init (GstTypeFindElement * typefind)
260 {
261   /* sinkpad */
262   typefind->sink =
263       gst_pad_new_from_static_template (&type_find_element_sink_template,
264       "sink");
265
266   gst_pad_set_activate_function (typefind->sink,
267       GST_DEBUG_FUNCPTR (gst_type_find_element_activate_sink));
268   gst_pad_set_activatemode_function (typefind->sink,
269       GST_DEBUG_FUNCPTR (gst_type_find_element_activate_sink_mode));
270   gst_pad_set_chain_function (typefind->sink,
271       GST_DEBUG_FUNCPTR (gst_type_find_element_chain));
272   gst_pad_set_event_function (typefind->sink,
273       GST_DEBUG_FUNCPTR (gst_type_find_element_sink_event));
274   gst_element_add_pad (GST_ELEMENT (typefind), typefind->sink);
275
276   /* srcpad */
277   typefind->src =
278       gst_pad_new_from_static_template (&type_find_element_src_template, "src");
279
280   gst_pad_set_activatemode_function (typefind->src,
281       GST_DEBUG_FUNCPTR (gst_type_find_element_activate_src_mode));
282   gst_pad_set_getrange_function (typefind->src,
283       GST_DEBUG_FUNCPTR (gst_type_find_element_getrange));
284   gst_pad_set_event_function (typefind->src,
285       GST_DEBUG_FUNCPTR (gst_type_find_element_src_event));
286   gst_pad_set_query_function (typefind->src,
287       GST_DEBUG_FUNCPTR (gst_type_find_handle_src_query));
288   gst_pad_use_fixed_caps (typefind->src);
289   gst_element_add_pad (GST_ELEMENT (typefind), typefind->src);
290
291   typefind->mode = MODE_TYPEFIND;
292   typefind->caps = NULL;
293   typefind->min_probability = 1;
294   typefind->max_probability = GST_TYPE_FIND_MAXIMUM;
295
296   typefind->adapter = gst_adapter_new ();
297 }
298
299 static void
300 gst_type_find_element_dispose (GObject * object)
301 {
302   GstTypeFindElement *typefind = GST_TYPE_FIND_ELEMENT (object);
303
304   if (typefind->adapter) {
305     g_object_unref (typefind->adapter);
306     typefind->adapter = NULL;
307   }
308
309   if (typefind->force_caps) {
310     gst_caps_unref (typefind->force_caps);
311     typefind->force_caps = NULL;
312   }
313
314   G_OBJECT_CLASS (parent_class)->dispose (object);
315 }
316
317 static void
318 gst_type_find_element_set_property (GObject * object, guint prop_id,
319     const GValue * value, GParamSpec * pspec)
320 {
321   GstTypeFindElement *typefind;
322
323   typefind = GST_TYPE_FIND_ELEMENT (object);
324
325   switch (prop_id) {
326     case PROP_MINIMUM:
327       typefind->min_probability = g_value_get_uint (value);
328       break;
329     case PROP_MAXIMUM:
330       typefind->max_probability = g_value_get_uint (value);
331       break;
332     case PROP_FORCE_CAPS:
333       GST_OBJECT_LOCK (typefind);
334       if (typefind->force_caps)
335         gst_caps_unref (typefind->force_caps);
336       typefind->force_caps = g_value_dup_boxed (value);
337       GST_OBJECT_UNLOCK (typefind);
338       break;
339     default:
340       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
341       break;
342   }
343 }
344
345 static void
346 gst_type_find_element_get_property (GObject * object, guint prop_id,
347     GValue * value, GParamSpec * pspec)
348 {
349   GstTypeFindElement *typefind;
350
351   typefind = GST_TYPE_FIND_ELEMENT (object);
352
353   switch (prop_id) {
354     case PROP_CAPS:
355       GST_OBJECT_LOCK (typefind);
356       g_value_set_boxed (value, typefind->caps);
357       GST_OBJECT_UNLOCK (typefind);
358       break;
359     case PROP_MINIMUM:
360       g_value_set_uint (value, typefind->min_probability);
361       break;
362     case PROP_MAXIMUM:
363       g_value_set_uint (value, typefind->max_probability);
364       break;
365     case PROP_FORCE_CAPS:
366       GST_OBJECT_LOCK (typefind);
367       g_value_set_boxed (value, typefind->force_caps);
368       GST_OBJECT_UNLOCK (typefind);
369       break;
370     default:
371       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
372       break;
373   }
374 }
375
376 static gboolean
377 gst_type_find_handle_src_query (GstPad * pad, GstObject * parent,
378     GstQuery * query)
379 {
380   GstTypeFindElement *typefind;
381   gboolean res = FALSE;
382
383   typefind = GST_TYPE_FIND_ELEMENT (parent);
384
385   res = gst_pad_peer_query (typefind->sink, query);
386   if (!res)
387     goto out;
388
389   switch (GST_QUERY_TYPE (query)) {
390     case GST_QUERY_POSITION:
391     {
392       gint64 peer_pos;
393       GstFormat format;
394
395       gst_query_parse_position (query, &format, &peer_pos);
396
397       GST_OBJECT_LOCK (typefind);
398       /* FIXME: this code assumes that there's no discont in the queue */
399       switch (format) {
400         case GST_FORMAT_BYTES:
401           peer_pos -= gst_adapter_available (typefind->adapter);
402           break;
403         default:
404           /* FIXME */
405           break;
406       }
407       GST_OBJECT_UNLOCK (typefind);
408       gst_query_set_position (query, format, peer_pos);
409       break;
410     }
411     default:
412       break;
413   }
414
415 out:
416   return res;
417 }
418
419 static gboolean
420 gst_type_find_element_seek (GstTypeFindElement * typefind, GstEvent * event)
421 {
422   GstSeekFlags flags;
423   GstSeekType cur_type, stop_type;
424   GstFormat format;
425   gboolean flush;
426   gdouble rate;
427   gint64 cur, stop;
428   GstSegment seeksegment = { 0, };
429
430   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
431       &stop_type, &stop);
432
433   /* we can only seek on bytes */
434   if (format != GST_FORMAT_BYTES) {
435     GST_DEBUG_OBJECT (typefind, "Can only seek on BYTES");
436     return FALSE;
437   }
438
439   /* copy segment, we need this because we still need the old
440    * segment when we close the current segment. */
441   memcpy (&seeksegment, &typefind->segment, sizeof (GstSegment));
442
443   GST_DEBUG_OBJECT (typefind, "configuring seek");
444   gst_segment_do_seek (&seeksegment, rate, format, flags,
445       cur_type, cur, stop_type, stop, NULL);
446
447   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
448
449   GST_DEBUG_OBJECT (typefind, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
450
451   if (flush) {
452     GST_DEBUG_OBJECT (typefind, "Starting flush");
453     gst_pad_push_event (typefind->sink, gst_event_new_flush_start ());
454     gst_pad_push_event (typefind->src, gst_event_new_flush_start ());
455   } else {
456     GST_DEBUG_OBJECT (typefind, "Non-flushing seek, pausing task");
457     gst_pad_pause_task (typefind->sink);
458   }
459
460   /* now grab the stream lock so that streaming cannot continue, for
461    * non flushing seeks when the element is in PAUSED this could block
462    * forever. */
463   GST_DEBUG_OBJECT (typefind, "Waiting for streaming to stop");
464   GST_PAD_STREAM_LOCK (typefind->sink);
465
466   if (flush) {
467     GST_DEBUG_OBJECT (typefind, "Stopping flush");
468     gst_pad_push_event (typefind->sink, gst_event_new_flush_stop (TRUE));
469     gst_pad_push_event (typefind->src, gst_event_new_flush_stop (TRUE));
470   }
471
472   /* now update the real segment info */
473   GST_DEBUG_OBJECT (typefind, "Committing new seek segment");
474   memcpy (&typefind->segment, &seeksegment, sizeof (GstSegment));
475   typefind->offset = typefind->segment.start;
476
477   /* notify start of new segment */
478   if (typefind->segment.flags & GST_SEEK_FLAG_SEGMENT) {
479     GstMessage *msg;
480
481     msg = gst_message_new_segment_start (GST_OBJECT (typefind),
482         GST_FORMAT_BYTES, typefind->segment.start);
483     gst_element_post_message (GST_ELEMENT (typefind), msg);
484   }
485
486   typefind->need_segment = TRUE;
487
488   /* restart our task since it might have been stopped when we did the
489    * flush. */
490   gst_pad_start_task (typefind->sink,
491       (GstTaskFunction) gst_type_find_element_loop, typefind->sink);
492
493   /* streaming can continue now */
494   GST_PAD_STREAM_UNLOCK (typefind->sink);
495
496   return TRUE;
497 }
498
499 static gboolean
500 gst_type_find_element_src_event (GstPad * pad, GstObject * parent,
501     GstEvent * event)
502 {
503   GstTypeFindElement *typefind = GST_TYPE_FIND_ELEMENT (parent);
504
505   if (typefind->mode != MODE_NORMAL) {
506     /* need to do more? */
507     gst_mini_object_unref (GST_MINI_OBJECT_CAST (event));
508     return FALSE;
509   }
510
511   /* Only handle seeks here if driving the pipeline */
512   if (typefind->segment.format != GST_FORMAT_UNDEFINED &&
513       GST_EVENT_TYPE (event) == GST_EVENT_SEEK) {
514     return gst_type_find_element_seek (typefind, event);
515   } else {
516     return gst_pad_push_event (typefind->sink, event);
517   }
518 }
519
520 static void
521 start_typefinding (GstTypeFindElement * typefind)
522 {
523   GST_DEBUG_OBJECT (typefind, "starting typefinding");
524
525   GST_OBJECT_LOCK (typefind);
526   if (typefind->caps)
527     gst_caps_replace (&typefind->caps, NULL);
528   GST_OBJECT_UNLOCK (typefind);
529
530   typefind->mode = MODE_TYPEFIND;
531 }
532
533 static void
534 stop_typefinding (GstTypeFindElement * typefind)
535 {
536   GstState state;
537   gboolean push_cached_buffers;
538   gsize avail;
539   GstBuffer *buffer;
540
541   gst_element_get_state (GST_ELEMENT (typefind), &state, NULL, 0);
542
543   push_cached_buffers = (state >= GST_STATE_PAUSED);
544
545   GST_DEBUG_OBJECT (typefind, "stopping typefinding%s",
546       push_cached_buffers ? " and pushing cached buffers" : "");
547
548   GST_OBJECT_LOCK (typefind);
549   avail = gst_adapter_available (typefind->adapter);
550   if (avail == 0)
551     goto no_data;
552
553   buffer = gst_adapter_take_buffer (typefind->adapter, avail);
554   GST_OBJECT_UNLOCK (typefind);
555
556   if (!push_cached_buffers) {
557     gst_buffer_unref (buffer);
558   } else {
559     GstPad *peer = gst_pad_get_peer (typefind->src);
560
561     typefind->mode = MODE_NORMAL;
562
563     /* make sure the user gets a meaningful error message in this case,
564      * which is not a core bug or bug of any kind (as the default error
565      * message emitted by gstpad.c otherwise would make you think) */
566     if (peer && GST_PAD_CHAINFUNC (peer) == NULL) {
567       GST_DEBUG_OBJECT (typefind, "upstream only supports push mode, while "
568           "downstream element only works in pull mode, erroring out");
569       GST_ELEMENT_ERROR (typefind, STREAM, FAILED,
570           ("%s cannot work in push mode. The operation is not supported "
571               "with this source element or protocol.",
572               G_OBJECT_TYPE_NAME (GST_PAD_PARENT (peer))),
573           ("Downstream pad %s:%s has no chainfunction, and the upstream "
574               "element does not support pull mode", GST_DEBUG_PAD_NAME (peer)));
575       typefind->mode = MODE_ERROR;      /* make the chain function error out */
576       gst_buffer_unref (buffer);
577     } else {
578       gst_type_find_element_send_cached_events (typefind);
579       gst_pad_push (typefind->src, buffer);
580     }
581     if (peer)
582       gst_object_unref (peer);
583   }
584   return;
585
586   /* ERRORS */
587 no_data:
588   {
589     GST_DEBUG_OBJECT (typefind, "we have no data to typefind");
590     GST_OBJECT_UNLOCK (typefind);
591     return;
592   }
593 }
594
595 static gboolean
596 gst_type_find_element_sink_event (GstPad * pad, GstObject * parent,
597     GstEvent * event)
598 {
599   gboolean res = FALSE;
600   GstTypeFindElement *typefind = GST_TYPE_FIND_ELEMENT (parent);
601
602   GST_DEBUG_OBJECT (typefind, "got %s event in mode %d",
603       GST_EVENT_TYPE_NAME (event), typefind->mode);
604
605   switch (typefind->mode) {
606     case MODE_TYPEFIND:
607       switch (GST_EVENT_TYPE (event)) {
608         case GST_EVENT_CAPS:
609         {
610           GstCaps *caps;
611
612           /* first pass the caps event downstream */
613           res = gst_pad_push_event (typefind->src, gst_event_ref (event));
614
615           /* then parse and push out our data */
616           gst_event_parse_caps (event, &caps);
617           res = gst_type_find_element_setcaps (typefind, caps);
618
619           gst_event_unref (event);
620           break;
621         }
622         case GST_EVENT_EOS:
623         {
624           GST_INFO_OBJECT (typefind, "Got EOS and no type found yet");
625           gst_type_find_element_chain_do_typefinding (typefind, FALSE);
626
627           res = gst_pad_push_event (typefind->src, event);
628           break;
629         }
630         case GST_EVENT_FLUSH_STOP:
631           GST_OBJECT_LOCK (typefind);
632           g_list_foreach (typefind->cached_events,
633               (GFunc) gst_mini_object_unref, NULL);
634           g_list_free (typefind->cached_events);
635           typefind->cached_events = NULL;
636           gst_adapter_clear (typefind->adapter);
637           GST_OBJECT_UNLOCK (typefind);
638           /* fall through */
639         case GST_EVENT_FLUSH_START:
640           res = gst_pad_push_event (typefind->src, event);
641           break;
642         default:
643           GST_DEBUG_OBJECT (typefind, "Saving %s event to send later",
644               GST_EVENT_TYPE_NAME (event));
645           GST_OBJECT_LOCK (typefind);
646           typefind->cached_events =
647               g_list_append (typefind->cached_events, event);
648           GST_OBJECT_UNLOCK (typefind);
649           res = TRUE;
650           break;
651       }
652       break;
653     case MODE_NORMAL:
654       res = gst_pad_push_event (typefind->src, event);
655       break;
656     case MODE_ERROR:
657       break;
658     default:
659       g_assert_not_reached ();
660   }
661   return res;
662 }
663
664 static void
665 gst_type_find_element_send_cached_events (GstTypeFindElement * typefind)
666 {
667   GList *l, *cached_events;
668
669   GST_OBJECT_LOCK (typefind);
670   cached_events = typefind->cached_events;
671   typefind->cached_events = NULL;
672   GST_OBJECT_UNLOCK (typefind);
673
674   for (l = cached_events; l != NULL; l = l->next) {
675     GstEvent *event = GST_EVENT (l->data);
676
677     GST_DEBUG_OBJECT (typefind, "sending cached %s event",
678         GST_EVENT_TYPE_NAME (event));
679     gst_pad_push_event (typefind->src, event);
680   }
681   g_list_free (cached_events);
682 }
683
684 static gboolean
685 gst_type_find_element_setcaps (GstTypeFindElement * typefind, GstCaps * caps)
686 {
687   /* don't operate on ANY caps */
688   if (gst_caps_is_any (caps))
689     return TRUE;
690
691   g_signal_emit (typefind, gst_type_find_element_signals[HAVE_TYPE], 0,
692       GST_TYPE_FIND_MAXIMUM, caps);
693
694   /* Shortcircuit typefinding if we get caps */
695   if (typefind->mode == MODE_TYPEFIND) {
696     GstBuffer *buffer;
697     gsize avail;
698
699     GST_DEBUG_OBJECT (typefind, "Skipping typefinding, using caps from "
700         "upstream buffer: %" GST_PTR_FORMAT, caps);
701     typefind->mode = MODE_NORMAL;
702
703     gst_type_find_element_send_cached_events (typefind);
704     GST_OBJECT_LOCK (typefind);
705     avail = gst_adapter_available (typefind->adapter);
706     if (avail == 0)
707       goto no_data;
708
709     buffer = gst_adapter_take_buffer (typefind->adapter, avail);
710     GST_OBJECT_UNLOCK (typefind);
711
712     GST_DEBUG_OBJECT (typefind, "Pushing buffer: %" G_GSIZE_FORMAT, avail);
713     gst_pad_push (typefind->src, buffer);
714   }
715
716   return TRUE;
717
718 no_data:
719   {
720     GST_DEBUG_OBJECT (typefind, "no data to push");
721     GST_OBJECT_UNLOCK (typefind);
722     return TRUE;
723   }
724 }
725
726 static gchar *
727 gst_type_find_get_extension (GstTypeFindElement * typefind, GstPad * pad)
728 {
729   GstQuery *query;
730   gchar *uri, *result;
731   size_t len;
732   gint find;
733
734   query = gst_query_new_uri ();
735
736   /* try getting the caps with an uri query and from the extension */
737   if (!gst_pad_peer_query (pad, query))
738     goto peer_query_failed;
739
740   gst_query_parse_uri (query, &uri);
741   if (uri == NULL)
742     goto no_uri;
743
744   GST_DEBUG_OBJECT (typefind, "finding extension of %s", uri);
745
746   /* find the extension on the uri, this is everything after a '.' */
747   len = strlen (uri);
748   find = len - 1;
749
750   while (find >= 0) {
751     if (uri[find] == '.')
752       break;
753     find--;
754   }
755   if (find < 0)
756     goto no_extension;
757
758   result = g_strdup (&uri[find + 1]);
759
760   GST_DEBUG_OBJECT (typefind, "found extension %s", result);
761   gst_query_unref (query);
762   g_free (uri);
763
764   return result;
765
766   /* ERRORS */
767 peer_query_failed:
768   {
769     GST_WARNING_OBJECT (typefind, "failed to query peer uri");
770     gst_query_unref (query);
771     return NULL;
772   }
773 no_uri:
774   {
775     GST_WARNING_OBJECT (typefind, "could not parse the peer uri");
776     gst_query_unref (query);
777     return NULL;
778   }
779 no_extension:
780   {
781     GST_WARNING_OBJECT (typefind, "could not find uri extension in %s", uri);
782     gst_query_unref (query);
783     g_free (uri);
784     return NULL;
785   }
786 }
787
788 static GstCaps *
789 gst_type_find_guess_by_extension (GstTypeFindElement * typefind, GstPad * pad,
790     GstTypeFindProbability * probability)
791 {
792   gchar *ext;
793   GstCaps *caps;
794
795   ext = gst_type_find_get_extension (typefind, pad);
796   if (!ext)
797     return NULL;
798
799   caps = gst_type_find_helper_for_extension (GST_OBJECT_CAST (typefind), ext);
800   if (caps)
801     *probability = GST_TYPE_FIND_MAXIMUM;
802
803   g_free (ext);
804
805   return caps;
806 }
807
808 static GstFlowReturn
809 gst_type_find_element_chain (GstPad * pad, GstObject * parent,
810     GstBuffer * buffer)
811 {
812   GstTypeFindElement *typefind;
813   GstFlowReturn res = GST_FLOW_OK;
814
815   typefind = GST_TYPE_FIND_ELEMENT (parent);
816
817   GST_LOG_OBJECT (typefind, "handling buffer in mode %d", typefind->mode);
818
819   switch (typefind->mode) {
820     case MODE_ERROR:
821       /* we should already have called GST_ELEMENT_ERROR */
822       return GST_FLOW_ERROR;
823     case MODE_NORMAL:
824       /* don't take object lock as typefind->caps should not change anymore */
825       return gst_pad_push (typefind->src, buffer);
826     case MODE_TYPEFIND:
827     {
828       GST_OBJECT_LOCK (typefind);
829       gst_adapter_push (typefind->adapter, buffer);
830       GST_OBJECT_UNLOCK (typefind);
831
832       res = gst_type_find_element_chain_do_typefinding (typefind, TRUE);
833
834       if (typefind->mode == MODE_ERROR)
835         res = GST_FLOW_ERROR;
836
837       break;
838     }
839     default:
840       g_assert_not_reached ();
841       return GST_FLOW_ERROR;
842   }
843
844   return res;
845 }
846
847 static GstFlowReturn
848 gst_type_find_element_chain_do_typefinding (GstTypeFindElement * typefind,
849     gboolean check_avail)
850 {
851   GstTypeFindProbability probability;
852   GstCaps *caps;
853   gsize avail;
854   const guint8 *data;
855   gboolean have_min, have_max;
856
857   GST_OBJECT_LOCK (typefind);
858   avail = gst_adapter_available (typefind->adapter);
859
860   if (check_avail) {
861     have_min = avail >= TYPE_FIND_MIN_SIZE;
862     have_max = avail >= TYPE_FIND_MAX_SIZE;
863   } else {
864     have_min = TRUE;
865     have_max = TRUE;
866   }
867
868   if (!have_min)
869     goto not_enough_data;
870
871   /* map all available data */
872   data = gst_adapter_map (typefind->adapter, avail);
873   caps = gst_type_find_helper_for_data (GST_OBJECT (typefind),
874       data, avail, &probability);
875   gst_adapter_unmap (typefind->adapter);
876
877   if (caps == NULL && have_max)
878     goto no_type_found;
879   else if (caps == NULL)
880     goto wait_for_data;
881
882   /* found a type */
883   if (probability < typefind->min_probability)
884     goto low_probability;
885   GST_OBJECT_UNLOCK (typefind);
886
887   /* probability is good enough too, so let's make it known ... emiting this
888    * signal calls our object handler which sets the caps. */
889   g_signal_emit (typefind, gst_type_find_element_signals[HAVE_TYPE], 0,
890       probability, caps);
891
892   /* .. and send out the accumulated data */
893   stop_typefinding (typefind);
894   gst_caps_unref (caps);
895
896   return GST_FLOW_OK;
897
898 not_enough_data:
899   {
900     GST_DEBUG_OBJECT (typefind, "not enough data for typefinding yet "
901         "(%" G_GSIZE_FORMAT " bytes)", avail);
902     GST_OBJECT_UNLOCK (typefind);
903     return GST_FLOW_OK;
904   }
905 no_type_found:
906   {
907     GST_OBJECT_UNLOCK (typefind);
908     GST_ELEMENT_ERROR (typefind, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
909     stop_typefinding (typefind);
910     return GST_FLOW_ERROR;
911   }
912 wait_for_data:
913   {
914     GST_DEBUG_OBJECT (typefind,
915         "no caps found with %" G_GSIZE_FORMAT " bytes of data, "
916         "waiting for more data", avail);
917     GST_OBJECT_UNLOCK (typefind);
918     return GST_FLOW_OK;
919   }
920 low_probability:
921   {
922     GST_DEBUG_OBJECT (typefind, "found caps %" GST_PTR_FORMAT ", but "
923         "probability is %u which is lower than the required minimum of %u",
924         caps, probability, typefind->min_probability);
925
926     gst_caps_unref (caps);
927
928     if (have_max)
929       goto no_type_found;
930
931     GST_OBJECT_UNLOCK (typefind);
932     GST_DEBUG_OBJECT (typefind, "waiting for more data to try again");
933     return GST_FLOW_OK;
934   }
935 }
936
937 static GstFlowReturn
938 gst_type_find_element_getrange (GstPad * srcpad, GstObject * parent,
939     guint64 offset, guint length, GstBuffer ** buffer)
940 {
941   GstTypeFindElement *typefind;
942   GstFlowReturn ret;
943
944   typefind = GST_TYPE_FIND_ELEMENT (parent);
945
946   ret = gst_pad_pull_range (typefind->sink, offset, length, buffer);
947
948   return ret;
949 }
950
951 static gboolean
952 gst_type_find_element_activate_src_mode (GstPad * pad, GstObject * parent,
953     GstPadMode mode, gboolean active)
954 {
955   gboolean res;
956   GstTypeFindElement *typefind;
957
958   typefind = GST_TYPE_FIND_ELEMENT (parent);
959
960   switch (mode) {
961     case GST_PAD_MODE_PULL:
962       res = gst_pad_activate_mode (typefind->sink, mode, active);
963       if (typefind->caps) {
964         GstCaps *caps;
965         GST_OBJECT_LOCK (typefind);
966         caps = gst_caps_ref (typefind->caps);
967         GST_OBJECT_UNLOCK (typefind);
968         gst_pad_push_event (typefind->src, gst_event_new_caps (caps));
969         gst_caps_unref (caps);
970       }
971       break;
972     default:
973       res = TRUE;
974       break;
975   }
976   return res;
977 }
978
979 static void
980 gst_type_find_element_loop (GstPad * pad)
981 {
982   GstTypeFindElement *typefind;
983   GstFlowReturn ret = GST_FLOW_OK;
984
985   typefind = GST_TYPE_FIND_ELEMENT (GST_PAD_PARENT (pad));
986
987   if (typefind->mode == MODE_TYPEFIND) {
988     GstPad *peer;
989     GstCaps *found_caps = NULL;
990     GstTypeFindProbability probability = GST_TYPE_FIND_NONE;
991
992     GST_DEBUG_OBJECT (typefind, "find type in pull mode");
993
994     peer = gst_pad_get_peer (pad);
995     if (peer) {
996       gint64 size;
997       gchar *ext;
998
999       if (!gst_pad_query_duration (peer, GST_FORMAT_BYTES, &size)) {
1000         GST_WARNING_OBJECT (typefind, "Could not query upstream length!");
1001         gst_object_unref (peer);
1002
1003         ret = GST_FLOW_ERROR;
1004         goto pause;
1005       }
1006
1007       /* the size if 0, we cannot continue */
1008       if (size == 0) {
1009         /* keep message in sync with message in sink event handler */
1010         GST_ELEMENT_ERROR (typefind, STREAM, TYPE_NOT_FOUND,
1011             (_("Stream contains no data.")), ("Can't typefind empty stream"));
1012         gst_object_unref (peer);
1013         ret = GST_FLOW_ERROR;
1014         goto pause;
1015       }
1016       ext = gst_type_find_get_extension (typefind, pad);
1017
1018       found_caps =
1019           gst_type_find_helper_get_range (GST_OBJECT_CAST (peer),
1020           GST_OBJECT_PARENT (peer),
1021           (GstTypeFindHelperGetRangeFunction) (GST_PAD_GETRANGEFUNC (peer)),
1022           (guint64) size, ext, &probability);
1023       g_free (ext);
1024
1025       GST_DEBUG ("Found caps %" GST_PTR_FORMAT, found_caps);
1026
1027       gst_object_unref (peer);
1028     }
1029
1030     if (!found_caps || probability < typefind->min_probability) {
1031       GST_DEBUG ("Trying to guess using extension");
1032       found_caps =
1033           gst_type_find_guess_by_extension (typefind, pad, &probability);
1034     }
1035
1036     if (!found_caps || probability < typefind->min_probability) {
1037       GST_ELEMENT_ERROR (typefind, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
1038       gst_caps_replace (&found_caps, NULL);
1039       ret = GST_FLOW_ERROR;
1040       goto pause;
1041     }
1042
1043     GST_DEBUG ("Emiting found caps %" GST_PTR_FORMAT, found_caps);
1044     g_signal_emit (typefind, gst_type_find_element_signals[HAVE_TYPE],
1045         0, probability, found_caps);
1046     typefind->mode = MODE_NORMAL;
1047   } else if (typefind->mode == MODE_NORMAL) {
1048     GstBuffer *outbuf;
1049
1050     if (typefind->need_segment) {
1051       typefind->need_segment = FALSE;
1052       gst_pad_push_event (typefind->src,
1053           gst_event_new_segment (&typefind->segment));
1054     }
1055
1056     /* Pull 4k blocks and send downstream */
1057     ret = gst_pad_pull_range (typefind->sink, typefind->offset, 4096, &outbuf);
1058     if (ret != GST_FLOW_OK)
1059       goto pause;
1060
1061     typefind->offset += 4096;
1062
1063     ret = gst_pad_push (typefind->src, outbuf);
1064     if (ret != GST_FLOW_OK)
1065       goto pause;
1066   } else {
1067     /* Error out */
1068     ret = GST_FLOW_ERROR;
1069     goto pause;
1070   }
1071
1072   return;
1073
1074 pause:
1075   {
1076     const gchar *reason = gst_flow_get_name (ret);
1077     gboolean push_eos = FALSE;
1078
1079     GST_LOG_OBJECT (typefind, "pausing task, reason %s", reason);
1080     gst_pad_pause_task (typefind->sink);
1081
1082     if (ret == GST_FLOW_EOS) {
1083       /* perform EOS logic */
1084
1085       if (typefind->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1086         gint64 stop;
1087
1088         /* for segment playback we need to post when (in stream time)
1089          * we stopped, this is either stop (when set) or the duration. */
1090         if ((stop = typefind->segment.stop) == -1)
1091           stop = typefind->offset;
1092
1093         GST_LOG_OBJECT (typefind, "Sending segment done, at end of segment");
1094         gst_element_post_message (GST_ELEMENT (typefind),
1095             gst_message_new_segment_done (GST_OBJECT (typefind),
1096                 GST_FORMAT_BYTES, stop));
1097       } else {
1098         push_eos = TRUE;
1099       }
1100     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
1101       /* for fatal errors we post an error message */
1102       GST_ELEMENT_ERROR (typefind, STREAM, FAILED, (NULL),
1103           ("stream stopped, reason %s", reason));
1104       push_eos = TRUE;
1105     }
1106     if (push_eos) {
1107       /* send EOS, and prevent hanging if no streams yet */
1108       GST_LOG_OBJECT (typefind, "Sending EOS, at end of stream");
1109       gst_pad_push_event (typefind->src, gst_event_new_eos ());
1110     }
1111     return;
1112   }
1113 }
1114
1115 static gboolean
1116 gst_type_find_element_activate_sink_mode (GstPad * pad, GstObject * parent,
1117     GstPadMode mode, gboolean active)
1118 {
1119   GstTypeFindElement *typefind;
1120
1121   typefind = GST_TYPE_FIND_ELEMENT (parent);
1122
1123   switch (mode) {
1124     case GST_PAD_MODE_PULL:
1125       if (active) {
1126         gst_segment_init (&typefind->segment, GST_FORMAT_BYTES);
1127         typefind->need_segment = TRUE;
1128         typefind->offset = 0;
1129         gst_pad_start_task (pad, (GstTaskFunction) gst_type_find_element_loop,
1130             pad);
1131       } else {
1132         gst_pad_stop_task (pad);
1133       }
1134       return TRUE;
1135       break;
1136     case GST_PAD_MODE_PUSH:
1137       if (active)
1138         start_typefinding (typefind);
1139       else
1140         stop_typefinding (typefind);
1141
1142       return TRUE;
1143       break;
1144     default:
1145       return FALSE;
1146   }
1147 }
1148
1149 static gboolean
1150 gst_type_find_element_activate_sink (GstPad * pad, GstObject * parent)
1151 {
1152   GstTypeFindElement *typefind;
1153   GstQuery *query;
1154   gboolean pull_mode;
1155   GstCaps *found_caps = NULL;
1156   GstTypeFindProbability probability = GST_TYPE_FIND_NONE;
1157
1158   typefind = GST_TYPE_FIND_ELEMENT (parent);
1159
1160   /* if we have force caps, use those */
1161   GST_OBJECT_LOCK (typefind);
1162   if (typefind->force_caps) {
1163     found_caps = gst_caps_ref (typefind->force_caps);
1164     probability = GST_TYPE_FIND_MAXIMUM;
1165     GST_OBJECT_UNLOCK (typefind);
1166
1167     GST_DEBUG ("Emiting found caps %" GST_PTR_FORMAT, found_caps);
1168     g_signal_emit (typefind, gst_type_find_element_signals[HAVE_TYPE],
1169         0, probability, found_caps);
1170     typefind->mode = MODE_NORMAL;
1171     goto typefind_push;
1172   }
1173   GST_OBJECT_UNLOCK (typefind);
1174
1175   query = gst_query_new_scheduling ();
1176
1177   if (!gst_pad_peer_query (pad, query)) {
1178     gst_query_unref (query);
1179     goto typefind_push;
1180   }
1181
1182   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
1183   gst_query_unref (query);
1184
1185   if (!pull_mode)
1186     goto typefind_push;
1187
1188   if (!gst_pad_activate_mode (pad, GST_PAD_MODE_PULL, TRUE))
1189     goto typefind_push;
1190
1191   return TRUE;
1192
1193 typefind_push:
1194   {
1195     return gst_pad_activate_mode (pad, GST_PAD_MODE_PUSH, TRUE);
1196   }
1197 }
1198
1199 static GstStateChangeReturn
1200 gst_type_find_element_change_state (GstElement * element,
1201     GstStateChange transition)
1202 {
1203   GstStateChangeReturn ret;
1204   GstTypeFindElement *typefind;
1205
1206   typefind = GST_TYPE_FIND_ELEMENT (element);
1207
1208
1209   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1210
1211   switch (transition) {
1212     case GST_STATE_CHANGE_PAUSED_TO_READY:
1213     case GST_STATE_CHANGE_READY_TO_NULL:
1214       GST_OBJECT_LOCK (typefind);
1215       gst_caps_replace (&typefind->caps, NULL);
1216
1217       g_list_foreach (typefind->cached_events,
1218           (GFunc) gst_mini_object_unref, NULL);
1219       g_list_free (typefind->cached_events);
1220       typefind->cached_events = NULL;
1221       typefind->mode = MODE_TYPEFIND;
1222       GST_OBJECT_UNLOCK (typefind);
1223       break;
1224     default:
1225       break;
1226   }
1227
1228   return ret;
1229 }