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