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