typefindhelper: also unmap collected mapped buffers
[platform/upstream/gstreamer.git] / libs / gst / base / gsttypefindhelper.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) 2000,2005 Wim Taymans <wim@fluendo.com>
4  * Copyright (C) 2006      Tim-Philipp Müller <tim centricular net>
5  *
6  * gsttypefindhelper.c:
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:gsttypefindhelper
26  * @short_description: Utility functions for typefinding 
27  *
28  * Utility functions for elements doing typefinding:
29  * gst_type_find_helper() does typefinding in pull mode, while
30  * gst_type_find_helper_for_buffer() is useful for elements needing to do
31  * typefinding in push mode from a chain function.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #  include "config.h"
36 #endif
37
38 #include <stdlib.h>
39 #include <string.h>
40
41 #include "gsttypefindhelper.h"
42
43 /* ********************** typefinding in pull mode ************************ */
44
45 static void
46 helper_find_suggest (gpointer data, guint probability, GstCaps * caps);
47
48 typedef struct
49 {
50   GstBuffer *buffer;
51   GstMapInfo map;
52 } GstMappedBuffer;
53
54 typedef struct
55 {
56   GSList *buffers;              /* buffer cache */
57   guint64 size;
58   guint64 last_offset;
59   GstTypeFindHelperGetRangeFunction func;
60   GstTypeFindProbability best_probability;
61   GstCaps *caps;
62   GstTypeFindFactory *factory;  /* for logging */
63   GstObject *obj;               /* for logging */
64   GstObject *parent;
65 } GstTypeFindHelper;
66
67 /*
68  * helper_find_peek:
69  * @data: helper data struct
70  * @off: stream offset
71  * @size: block size
72  *
73  * Get data pointer within a stream. Keeps a cache of read buffers (partly
74  * for performance reasons, but mostly because pointers returned by us need
75  * to stay valid until typefinding has finished)
76  *
77  * Returns: address of the data or %NULL if buffer does not cover the
78  * requested range.
79  */
80 static const guint8 *
81 helper_find_peek (gpointer data, gint64 offset, guint size)
82 {
83   GstTypeFindHelper *helper;
84   GstBuffer *buffer;
85   GstFlowReturn ret;
86   GSList *insert_pos = NULL;
87   gsize buf_size;
88   guint64 buf_offset;
89   GstMappedBuffer *bmap;
90 #if 0
91   GstCaps *caps;
92 #endif
93
94   helper = (GstTypeFindHelper *) data;
95
96   GST_LOG_OBJECT (helper->obj, "'%s' called peek (%" G_GINT64_FORMAT
97       ", %u)", GST_OBJECT_NAME (helper->factory), offset, size);
98
99   if (size == 0)
100     return NULL;
101
102   if (offset < 0) {
103     if (helper->size == -1 || helper->size < -offset)
104       return NULL;
105
106     offset += helper->size;
107   }
108
109   /* see if we have a matching buffer already in our list */
110   if (size > 0 && offset <= helper->last_offset) {
111     GSList *walk;
112
113     for (walk = helper->buffers; walk; walk = walk->next) {
114       GstMappedBuffer *bmp = (GstMappedBuffer *) walk->data;
115       GstBuffer *buf = GST_BUFFER_CAST (bmp->buffer);
116       guint64 buf_offset = GST_BUFFER_OFFSET (buf);
117       guint buf_size = gst_buffer_get_size (buf);
118
119       /* buffers are kept sorted by end offset (highest first) in the list, so
120        * at this point we save the current position and stop searching if 
121        * we're after the searched end offset */
122       if (buf_offset <= offset) {
123         if ((offset + size) < (buf_offset + buf_size)) {
124           /* must already have been mapped before */
125           return (guint8 *) bmp->map.data + (offset - buf_offset);
126         }
127       } else if (offset + size >= buf_offset + buf_size) {
128         insert_pos = walk;
129         break;
130       }
131     }
132   }
133
134   buffer = NULL;
135   /* some typefinders go in 1 byte steps over 1k of data and request
136    * small buffers. It is really inefficient to pull each time, and pulling
137    * a larger chunk is almost free. Trying to pull a larger chunk at the end
138    * of the file is also not a problem here, we'll just get a truncated buffer
139    * in that case (and we'll have to double-check the size we actually get
140    * anyway, see below) */
141   ret =
142       helper->func (helper->obj, helper->parent, offset, MAX (size, 4096),
143       &buffer);
144
145   if (ret != GST_FLOW_OK)
146     goto error;
147
148 #if 0
149   caps = GST_BUFFER_CAPS (buffer);
150
151   if (caps && !gst_caps_is_empty (caps) && !gst_caps_is_any (caps)) {
152     GST_DEBUG ("buffer has caps %" GST_PTR_FORMAT ", suggest max probability",
153         caps);
154
155     gst_caps_replace (&helper->caps, caps);
156     helper->best_probability = GST_TYPE_FIND_MAXIMUM;
157
158     gst_buffer_unref (buffer);
159     return NULL;
160   }
161 #endif
162
163   /* getrange might silently return shortened buffers at the end of a file,
164    * we must, however, always return either the full requested data or NULL */
165   buf_offset = GST_BUFFER_OFFSET (buffer);
166   buf_size = gst_buffer_get_size (buffer);
167
168   if ((buf_offset != -1 && buf_offset != offset) || buf_size < size) {
169     GST_DEBUG ("dropping short buffer: %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
170         " instead of %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT,
171         buf_offset, buf_offset + buf_size - 1, offset, offset + size - 1);
172     gst_buffer_unref (buffer);
173     return NULL;
174   }
175
176   bmap = g_slice_new0 (GstMappedBuffer);
177   bmap->buffer = buffer;
178   if (insert_pos) {
179     helper->buffers = g_slist_insert_before (helper->buffers, insert_pos, bmap);
180   } else {
181     /* if insert_pos is not set, our offset is bigger than the largest offset
182      * we have so far; since we keep the list sorted with highest offsets
183      * first, we need to prepend the buffer to the list */
184     helper->last_offset = GST_BUFFER_OFFSET (buffer) + buf_size;
185     helper->buffers = g_slist_prepend (helper->buffers, bmap);
186   }
187
188   gst_buffer_map (buffer, &bmap->map, GST_MAP_READ);
189
190   return bmap->map.data;
191
192 error:
193   {
194     GST_INFO ("typefind function returned: %s", gst_flow_get_name (ret));
195     return NULL;
196   }
197 }
198
199 /*
200  * helper_find_suggest:
201  * @data: helper data struct
202  * @probability: probability of the match
203  * @caps: caps of the type
204  *
205  * If given @probability is higher, replace previously store caps.
206  */
207 static void
208 helper_find_suggest (gpointer data, GstTypeFindProbability probability,
209     GstCaps * caps)
210 {
211   GstTypeFindHelper *helper = (GstTypeFindHelper *) data;
212
213   GST_LOG_OBJECT (helper->obj,
214       "'%s' called suggest (%u, %" GST_PTR_FORMAT ")",
215       GST_OBJECT_NAME (helper->factory), probability, caps);
216
217   if (probability > helper->best_probability) {
218     gst_caps_replace (&helper->caps, caps);
219     helper->best_probability = probability;
220   }
221 }
222
223 static guint64
224 helper_find_get_length (gpointer data)
225 {
226   GstTypeFindHelper *helper = (GstTypeFindHelper *) data;
227
228   GST_LOG_OBJECT (helper->obj, "'%s' called get_length, returning %"
229       G_GUINT64_FORMAT, GST_OBJECT_NAME (helper->factory), helper->size);
230
231   return helper->size;
232 }
233
234 /**
235  * gst_type_find_helper_get_range:
236  * @obj: A #GstObject that will be passed as first argument to @func
237  * @parent: the parent of @obj or NULL
238  * @func: (scope call): A generic #GstTypeFindHelperGetRangeFunction that will
239  *        be used to access data at random offsets when doing the typefinding
240  * @size: The length in bytes
241  * @extension: extension of the media
242  * @prob: (out) (allow-none): location to store the probability of the found
243  *     caps, or #NULL
244  *
245  * Utility function to do pull-based typefinding. Unlike gst_type_find_helper()
246  * however, this function will use the specified function @func to obtain the
247  * data needed by the typefind functions, rather than operating on a given
248  * source pad. This is useful mostly for elements like tag demuxers which
249  * strip off data at the beginning and/or end of a file and want to typefind
250  * the stripped data stream before adding their own source pad (the specified
251  * callback can then call the upstream peer pad with offsets adjusted for the
252  * tag size, for example).
253  *
254  * When @extension is not NULL, this function will first try the typefind
255  * functions for the given extension, which might speed up the typefinding
256  * in many cases.
257  *
258  * Free-function: gst_caps_unref
259  *
260  * Returns: (transfer full): the #GstCaps corresponding to the data stream.
261  *     Returns #NULL if no #GstCaps matches the data stream.
262  *
263  * Since: 0.10.26
264  */
265 GstCaps *
266 gst_type_find_helper_get_range (GstObject * obj, GstObject * parent,
267     GstTypeFindHelperGetRangeFunction func, guint64 size,
268     const gchar * extension, GstTypeFindProbability * prob)
269 {
270   GstTypeFindHelper helper;
271   GstTypeFind find;
272   GSList *walk;
273   GList *l, *type_list;
274   GstCaps *result = NULL;
275   gint pos = 0;
276
277   g_return_val_if_fail (GST_IS_OBJECT (obj), NULL);
278   g_return_val_if_fail (func != NULL, NULL);
279
280   helper.buffers = NULL;
281   helper.size = size;
282   helper.last_offset = 0;
283   helper.func = func;
284   helper.best_probability = GST_TYPE_FIND_NONE;
285   helper.caps = NULL;
286   helper.obj = obj;
287   helper.parent = parent;
288
289   find.data = &helper;
290   find.peek = helper_find_peek;
291   find.suggest = helper_find_suggest;
292
293   if (size == 0 || size == (guint64) - 1) {
294     find.get_length = NULL;
295   } else {
296     find.get_length = helper_find_get_length;
297   }
298
299   type_list = gst_type_find_factory_get_list ();
300
301   /* move the typefinders for the extension first in the list. The idea is that
302    * when one of them returns MAX we don't need to search further as there is a
303    * very high chance we got the right type. */
304   if (extension) {
305     GList *next;
306
307     GST_LOG_OBJECT (obj, "sorting typefind for extension %s to head",
308         extension);
309
310     for (l = type_list; l; l = next) {
311       GstTypeFindFactory *factory;
312       gint i;
313       gchar **ext;
314
315       next = l->next;
316
317       factory = GST_TYPE_FIND_FACTORY (l->data);
318
319       ext = gst_type_find_factory_get_extensions (factory);
320       if (ext == NULL)
321         continue;
322
323       GST_LOG_OBJECT (obj, "testing factory %s for extension %s",
324           GST_OBJECT_NAME (factory), extension);
325
326       for (i = 0; ext[i]; i++) {
327         if (strcmp (ext[i], extension) == 0) {
328           /* found extension, move in front */
329           GST_LOG_OBJECT (obj, "moving typefind for extension %s to head",
330               extension);
331           /* remove entry from list */
332           type_list = g_list_delete_link (type_list, l);
333           /* insert at the position */
334           type_list = g_list_insert (type_list, factory, pos);
335           /* next element will be inserted after this one */
336           pos++;
337           break;
338         }
339       }
340     }
341   }
342
343   for (l = type_list; l; l = l->next) {
344     helper.factory = GST_TYPE_FIND_FACTORY (l->data);
345     gst_type_find_factory_call_function (helper.factory, &find);
346     if (helper.best_probability >= GST_TYPE_FIND_MAXIMUM)
347       break;
348   }
349   gst_plugin_feature_list_free (type_list);
350
351   for (walk = helper.buffers; walk; walk = walk->next) {
352     GstMappedBuffer *bmap = (GstMappedBuffer *) walk->data;
353
354     gst_buffer_unmap (bmap->buffer, &bmap->map);
355     gst_buffer_unref (bmap->buffer);
356     g_slice_free (GstMappedBuffer, bmap);
357   }
358   g_slist_free (helper.buffers);
359
360   if (helper.best_probability > 0)
361     result = helper.caps;
362
363   if (prob)
364     *prob = helper.best_probability;
365
366   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT " (probability = %u)",
367       result, (guint) helper.best_probability);
368
369   return result;
370 }
371
372 /**
373  * gst_type_find_helper:
374  * @src: A source #GstPad
375  * @size: The length in bytes
376  *
377  * Tries to find what type of data is flowing from the given source #GstPad.
378  *
379  * Free-function: gst_caps_unref
380  *
381  * Returns: (transfer full): the #GstCaps corresponding to the data stream.
382  *     Returns #NULL if no #GstCaps matches the data stream.
383  */
384
385 GstCaps *
386 gst_type_find_helper (GstPad * src, guint64 size)
387 {
388   GstTypeFindHelperGetRangeFunction func;
389
390   g_return_val_if_fail (GST_IS_OBJECT (src), NULL);
391   g_return_val_if_fail (GST_PAD_GETRANGEFUNC (src) != NULL, NULL);
392
393   func = (GstTypeFindHelperGetRangeFunction) (GST_PAD_GETRANGEFUNC (src));
394
395   return gst_type_find_helper_get_range (GST_OBJECT (src),
396       GST_OBJECT_PARENT (src), func, size, NULL, NULL);
397 }
398
399 /* ********************** typefinding for buffers ************************* */
400
401 typedef struct
402 {
403   const guint8 *data;           /* buffer data */
404   gsize size;
405   GstTypeFindProbability best_probability;
406   GstCaps *caps;
407   GstTypeFindFactory *factory;  /* for logging */
408   GstObject *obj;               /* for logging */
409 } GstTypeFindBufHelper;
410
411 /*
412  * buf_helper_find_peek:
413  * @data: helper data struct
414  * @off: stream offset
415  * @size: block size
416  *
417  * Get data pointer within a buffer.
418  *
419  * Returns: address inside the buffer or %NULL if buffer does not cover the
420  * requested range.
421  */
422 static const guint8 *
423 buf_helper_find_peek (gpointer data, gint64 off, guint size)
424 {
425   GstTypeFindBufHelper *helper;
426
427   helper = (GstTypeFindBufHelper *) data;
428   GST_LOG_OBJECT (helper->obj, "'%s' called peek (%" G_GINT64_FORMAT ", %u)",
429       GST_OBJECT_NAME (helper->factory), off, size);
430
431   if (size == 0)
432     return NULL;
433
434   if (off < 0) {
435     GST_LOG_OBJECT (helper->obj, "'%s' wanted to peek at end; not supported",
436         GST_OBJECT_NAME (helper->factory));
437     return NULL;
438   }
439
440   if ((off + size) <= helper->size)
441     return helper->data + off;
442
443   return NULL;
444 }
445
446 /*
447  * buf_helper_find_suggest:
448  * @data: helper data struct
449  * @probability: probability of the match
450  * @caps: caps of the type
451  *
452  * If given @probability is higher, replace previously store caps.
453  */
454 static void
455 buf_helper_find_suggest (gpointer data, GstTypeFindProbability probability,
456     GstCaps * caps)
457 {
458   GstTypeFindBufHelper *helper = (GstTypeFindBufHelper *) data;
459
460   GST_LOG_OBJECT (helper->obj,
461       "'%s' called suggest (%u, %" GST_PTR_FORMAT ")",
462       GST_OBJECT_NAME (helper->factory), probability, caps);
463
464   /* Note: not >= as we call typefinders in order of rank, highest first */
465   if (probability > helper->best_probability) {
466     gst_caps_replace (&helper->caps, caps);
467     helper->best_probability = probability;
468   }
469 }
470
471 /**
472  * gst_type_find_helper_for_data:
473  * @obj: object doing the typefinding, or NULL (used for logging)
474  * @data: (in) (transfer none): a pointer with data to typefind
475  * @size: (in) (transfer none): the size of @data
476  * @prob: (out) (allow-none): location to store the probability of the found
477  *     caps, or #NULL
478  *
479  * Tries to find what type of data is contained in the given @data, the
480  * assumption being that the data represents the beginning of the stream or
481  * file.
482  *
483  * All available typefinders will be called on the data in order of rank. If
484  * a typefinding function returns a probability of #GST_TYPE_FIND_MAXIMUM,
485  * typefinding is stopped immediately and the found caps will be returned
486  * right away. Otherwise, all available typefind functions will the tried,
487  * and the caps with the highest probability will be returned, or #NULL if
488  * the content of @data could not be identified.
489  *
490  * Free-function: gst_caps_unref
491  *
492  * Returns: (transfer full): the #GstCaps corresponding to the data, or #NULL
493  *     if no type could be found. The caller should free the caps returned
494  *     with gst_caps_unref().
495  */
496 GstCaps *
497 gst_type_find_helper_for_data (GstObject * obj, const guint8 * data, gsize size,
498     GstTypeFindProbability * prob)
499 {
500   GstTypeFindBufHelper helper;
501   GstTypeFind find;
502   GList *l, *type_list;
503   GstCaps *result = NULL;
504
505   g_return_val_if_fail (data != NULL, NULL);
506
507   helper.data = data;
508   helper.size = size;
509   helper.best_probability = GST_TYPE_FIND_NONE;
510   helper.caps = NULL;
511   helper.obj = obj;
512
513   if (helper.data == NULL || helper.size == 0)
514     return NULL;
515
516   find.data = &helper;
517   find.peek = buf_helper_find_peek;
518   find.suggest = buf_helper_find_suggest;
519   find.get_length = NULL;
520
521   type_list = gst_type_find_factory_get_list ();
522
523   for (l = type_list; l; l = l->next) {
524     helper.factory = GST_TYPE_FIND_FACTORY (l->data);
525     gst_type_find_factory_call_function (helper.factory, &find);
526     if (helper.best_probability >= GST_TYPE_FIND_MAXIMUM)
527       break;
528   }
529   gst_plugin_feature_list_free (type_list);
530
531   if (helper.best_probability > 0)
532     result = helper.caps;
533
534   if (prob)
535     *prob = helper.best_probability;
536
537   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT " (probability = %u)",
538       result, (guint) helper.best_probability);
539
540   return result;
541 }
542
543 /**
544  * gst_type_find_helper_for_buffer:
545  * @obj: object doing the typefinding, or NULL (used for logging)
546  * @buf: (in) (transfer none): a #GstBuffer with data to typefind
547  * @prob: (out) (allow-none): location to store the probability of the found
548  *     caps, or #NULL
549  *
550  * Tries to find what type of data is contained in the given #GstBuffer, the
551  * assumption being that the buffer represents the beginning of the stream or
552  * file.
553  *
554  * All available typefinders will be called on the data in order of rank. If
555  * a typefinding function returns a probability of #GST_TYPE_FIND_MAXIMUM,
556  * typefinding is stopped immediately and the found caps will be returned
557  * right away. Otherwise, all available typefind functions will the tried,
558  * and the caps with the highest probability will be returned, or #NULL if
559  * the content of the buffer could not be identified.
560  *
561  * Free-function: gst_caps_unref
562  *
563  * Returns: (transfer full): the #GstCaps corresponding to the data, or #NULL
564  *     if no type could be found. The caller should free the caps returned
565  *     with gst_caps_unref().
566  */
567 GstCaps *
568 gst_type_find_helper_for_buffer (GstObject * obj, GstBuffer * buf,
569     GstTypeFindProbability * prob)
570 {
571   GstCaps *result;
572   GstMapInfo info;
573
574   g_return_val_if_fail (buf != NULL, NULL);
575   g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
576   g_return_val_if_fail (GST_BUFFER_OFFSET (buf) == 0 ||
577       GST_BUFFER_OFFSET (buf) == GST_BUFFER_OFFSET_NONE, NULL);
578
579   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
580     return NULL;
581   result = gst_type_find_helper_for_data (obj, info.data, info.size, prob);
582   gst_buffer_unmap (buf, &info);
583
584   return result;
585 }
586
587 /**
588  * gst_type_find_helper_for_extension:
589  * @obj: (allow-none): object doing the typefinding, or NULL (used for logging)
590  * @extension: an extension
591  *
592  * Tries to find the best #GstCaps associated with @extension.
593  *
594  * All available typefinders will be checked against the extension in order
595  * of rank. The caps of the first typefinder that can handle @extension will be
596  * returned.
597  *
598  * Free-function: gst_caps_unref
599  *
600  * Returns: (transfer full): the #GstCaps corresponding to @extension, or
601  *     #NULL if no type could be found. The caller should free the caps
602  *     returned with gst_caps_unref().
603  * 
604  * Since: 0.10.23
605  */
606 GstCaps *
607 gst_type_find_helper_for_extension (GstObject * obj, const gchar * extension)
608 {
609   GList *l, *type_list;
610   GstCaps *result = NULL;
611
612   g_return_val_if_fail (extension != NULL, NULL);
613
614   GST_LOG_OBJECT (obj, "finding caps for extension %s", extension);
615
616   type_list = gst_type_find_factory_get_list ();
617
618   for (l = type_list; l; l = g_list_next (l)) {
619     GstTypeFindFactory *factory;
620     gchar **ext;
621     gint i;
622
623     factory = GST_TYPE_FIND_FACTORY (l->data);
624
625     /* we only want to check those factories without a function */
626     if (factory->function != NULL)
627       continue;
628
629     /* get the extension that this typefind factory can handle */
630     ext = gst_type_find_factory_get_extensions (factory);
631     if (ext == NULL)
632       continue;
633
634     /* there are extension, see if one of them matches the requested
635      * extension */
636     for (i = 0; ext[i]; i++) {
637       if (strcmp (ext[i], extension) == 0) {
638         /* we found a matching extension, take the caps */
639         if ((result = gst_type_find_factory_get_caps (factory))) {
640           gst_caps_ref (result);
641           goto done;
642         }
643       }
644     }
645   }
646 done:
647   gst_plugin_feature_list_free (type_list);
648
649   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT, result);
650
651   return result;
652 }