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