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