8828534ab68c8a877711c50e61bd013cbb775e9d
[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., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, 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: (nullable): address of the data or %NULL if buffer does not cover
78  * the 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
117       buf_offset = GST_BUFFER_OFFSET (buf);
118       buf_size = bmp->map.size;
119
120       /* buffers are kept sorted by end offset (highest first) in the list, so
121        * at this point we save the current position and stop searching if 
122        * we're after the searched end offset */
123       if (buf_offset <= offset) {
124         if ((offset + size) < (buf_offset + buf_size)) {
125           /* must already have been mapped before */
126           return (guint8 *) bmp->map.data + (offset - buf_offset);
127         }
128       } else if (offset + size >= buf_offset + buf_size) {
129         insert_pos = walk;
130         break;
131       }
132     }
133   }
134
135   buffer = NULL;
136   /* some typefinders go in 1 byte steps over 1k of data and request
137    * small buffers. It is really inefficient to pull each time, and pulling
138    * a larger chunk is almost free. Trying to pull a larger chunk at the end
139    * of the file is also not a problem here, we'll just get a truncated buffer
140    * in that case (and we'll have to double-check the size we actually get
141    * anyway, see below) */
142   ret =
143       helper->func (helper->obj, helper->parent, offset, MAX (size, 4096),
144       &buffer);
145
146   if (ret != GST_FLOW_OK)
147     goto error;
148
149 #if 0
150   caps = GST_BUFFER_CAPS (buffer);
151
152   if (caps && !gst_caps_is_empty (caps) && !gst_caps_is_any (caps)) {
153     GST_DEBUG ("buffer has caps %" GST_PTR_FORMAT ", suggest max probability",
154         caps);
155
156     gst_caps_replace (&helper->caps, caps);
157     helper->best_probability = GST_TYPE_FIND_MAXIMUM;
158
159     gst_buffer_unref (buffer);
160     return NULL;
161   }
162 #endif
163
164   /* getrange might silently return shortened buffers at the end of a file,
165    * we must, however, always return either the full requested data or %NULL */
166   buf_offset = GST_BUFFER_OFFSET (buffer);
167   buf_size = gst_buffer_get_size (buffer);
168
169   if ((buf_offset != -1 && buf_offset != offset) || buf_size < size) {
170     GST_DEBUG ("dropping short buffer: %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
171         " instead of %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT,
172         buf_offset, buf_offset + buf_size - 1, offset, offset + size - 1);
173     gst_buffer_unref (buffer);
174     return NULL;
175   }
176
177   bmap = g_slice_new0 (GstMappedBuffer);
178
179   if (!gst_buffer_map (buffer, &bmap->map, GST_MAP_READ))
180     goto map_failed;
181
182   bmap->buffer = buffer;
183
184   if (insert_pos) {
185     helper->buffers = g_slist_insert_before (helper->buffers, insert_pos, bmap);
186   } else {
187     /* if insert_pos is not set, our offset is bigger than the largest offset
188      * we have so far; since we keep the list sorted with highest offsets
189      * first, we need to prepend the buffer to the list */
190     helper->last_offset = GST_BUFFER_OFFSET (buffer) + buf_size;
191     helper->buffers = g_slist_prepend (helper->buffers, bmap);
192   }
193
194   return bmap->map.data;
195
196 error:
197   {
198     GST_INFO ("typefind function returned: %s", gst_flow_get_name (ret));
199     return NULL;
200   }
201 map_failed:
202   {
203     GST_ERROR ("map failed");
204     gst_buffer_unref (buffer);
205     g_slice_free (GstMappedBuffer, bmap);
206     return NULL;
207   }
208 }
209
210 /*
211  * helper_find_suggest:
212  * @data: helper data struct
213  * @probability: probability of the match
214  * @caps: caps of the type
215  *
216  * If given @probability is higher, replace previously store caps.
217  */
218 static void
219 helper_find_suggest (gpointer data, guint probability, GstCaps * caps)
220 {
221   GstTypeFindHelper *helper = (GstTypeFindHelper *) data;
222
223   GST_LOG_OBJECT (helper->obj,
224       "'%s' called suggest (%u, %" GST_PTR_FORMAT ")",
225       GST_OBJECT_NAME (helper->factory), probability, caps);
226
227   if (probability > helper->best_probability) {
228     gst_caps_replace (&helper->caps, caps);
229     helper->best_probability = probability;
230   }
231 }
232
233 static guint64
234 helper_find_get_length (gpointer data)
235 {
236   GstTypeFindHelper *helper = (GstTypeFindHelper *) data;
237
238   GST_LOG_OBJECT (helper->obj, "'%s' called get_length, returning %"
239       G_GUINT64_FORMAT, GST_OBJECT_NAME (helper->factory), helper->size);
240
241   return helper->size;
242 }
243
244 /**
245  * gst_type_find_helper_get_range:
246  * @obj: A #GstObject that will be passed as first argument to @func
247  * @parent: (allow-none): the parent of @obj or %NULL
248  * @func: (scope call): A generic #GstTypeFindHelperGetRangeFunction that will
249  *        be used to access data at random offsets when doing the typefinding
250  * @size: The length in bytes
251  * @extension: extension of the media
252  * @prob: (out) (allow-none): location to store the probability of the found
253  *     caps, or %NULL
254  *
255  * Utility function to do pull-based typefinding. Unlike gst_type_find_helper()
256  * however, this function will use the specified function @func to obtain the
257  * data needed by the typefind functions, rather than operating on a given
258  * source pad. This is useful mostly for elements like tag demuxers which
259  * strip off data at the beginning and/or end of a file and want to typefind
260  * the stripped data stream before adding their own source pad (the specified
261  * callback can then call the upstream peer pad with offsets adjusted for the
262  * tag size, for example).
263  *
264  * When @extension is not %NULL, this function will first try the typefind
265  * functions for the given extension, which might speed up the typefinding
266  * in many cases.
267  *
268  * Free-function: gst_caps_unref
269  *
270  * Returns: (transfer full) (nullable): the #GstCaps corresponding to the data
271  *     stream.  Returns %NULL if no #GstCaps matches the data stream.
272  */
273 GstCaps *
274 gst_type_find_helper_get_range (GstObject * obj, GstObject * parent,
275     GstTypeFindHelperGetRangeFunction func, guint64 size,
276     const gchar * extension, GstTypeFindProbability * prob)
277 {
278   GstTypeFindHelper helper;
279   GstTypeFind find;
280   GSList *walk;
281   GList *l, *type_list;
282   GstCaps *result = NULL;
283   gint pos = 0;
284
285   g_return_val_if_fail (GST_IS_OBJECT (obj), NULL);
286   g_return_val_if_fail (func != NULL, NULL);
287
288   helper.buffers = NULL;
289   helper.size = size;
290   helper.last_offset = 0;
291   helper.func = func;
292   helper.best_probability = GST_TYPE_FIND_NONE;
293   helper.caps = NULL;
294   helper.obj = obj;
295   helper.parent = parent;
296
297   find.data = &helper;
298   find.peek = helper_find_peek;
299   find.suggest = helper_find_suggest;
300
301   if (size == 0 || size == (guint64) - 1) {
302     find.get_length = NULL;
303   } else {
304     find.get_length = helper_find_get_length;
305   }
306
307   type_list = gst_type_find_factory_get_list ();
308
309   /* move the typefinders for the extension first in the list. The idea is that
310    * when one of them returns MAX we don't need to search further as there is a
311    * very high chance we got the right type. */
312   if (extension) {
313     GList *next;
314
315     GST_LOG_OBJECT (obj, "sorting typefind for extension %s to head",
316         extension);
317
318     for (l = type_list; l; l = next) {
319       const gchar *const *ext;
320       GstTypeFindFactory *factory;
321
322       next = l->next;
323
324       factory = GST_TYPE_FIND_FACTORY (l->data);
325
326       ext = gst_type_find_factory_get_extensions (factory);
327       if (ext == NULL)
328         continue;
329
330       GST_LOG_OBJECT (obj, "testing factory %s for extension %s",
331           GST_OBJECT_NAME (factory), extension);
332
333       while (*ext != NULL) {
334         if (strcmp (*ext, extension) == 0) {
335           /* found extension, move in front */
336           GST_LOG_OBJECT (obj, "moving typefind for extension %s to head",
337               extension);
338           /* remove entry from list */
339           type_list = g_list_delete_link (type_list, l);
340           /* insert at the position */
341           type_list = g_list_insert (type_list, factory, pos);
342           /* next element will be inserted after this one */
343           pos++;
344           break;
345         }
346         ++ext;
347       }
348     }
349   }
350
351   for (l = type_list; l; l = l->next) {
352     helper.factory = GST_TYPE_FIND_FACTORY (l->data);
353     gst_type_find_factory_call_function (helper.factory, &find);
354     if (helper.best_probability >= GST_TYPE_FIND_MAXIMUM)
355       break;
356   }
357   gst_plugin_feature_list_free (type_list);
358
359   for (walk = helper.buffers; walk; walk = walk->next) {
360     GstMappedBuffer *bmap = (GstMappedBuffer *) walk->data;
361
362     gst_buffer_unmap (bmap->buffer, &bmap->map);
363     gst_buffer_unref (bmap->buffer);
364     g_slice_free (GstMappedBuffer, bmap);
365   }
366   g_slist_free (helper.buffers);
367
368   if (helper.best_probability > 0)
369     result = helper.caps;
370
371   if (prob)
372     *prob = helper.best_probability;
373
374   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT " (probability = %u)",
375       result, (guint) helper.best_probability);
376
377   return result;
378 }
379
380 /**
381  * gst_type_find_helper:
382  * @src: A source #GstPad
383  * @size: The length in bytes
384  *
385  * Tries to find what type of data is flowing from the given source #GstPad.
386  *
387  * Free-function: gst_caps_unref
388  *
389  * Returns: (transfer full) (nullable): the #GstCaps corresponding to the data
390  *     stream.  Returns %NULL if no #GstCaps matches the data stream.
391  */
392
393 GstCaps *
394 gst_type_find_helper (GstPad * src, guint64 size)
395 {
396   GstTypeFindHelperGetRangeFunction func;
397
398   g_return_val_if_fail (GST_IS_OBJECT (src), NULL);
399   g_return_val_if_fail (GST_PAD_GETRANGEFUNC (src) != NULL, NULL);
400
401   func = (GstTypeFindHelperGetRangeFunction) (GST_PAD_GETRANGEFUNC (src));
402
403   return gst_type_find_helper_get_range (GST_OBJECT (src),
404       GST_OBJECT_PARENT (src), func, size, NULL, NULL);
405 }
406
407 /* ********************** typefinding for buffers ************************* */
408
409 typedef struct
410 {
411   const guint8 *data;           /* buffer data */
412   gsize size;
413   GstTypeFindProbability best_probability;
414   GstCaps *caps;
415   GstTypeFindFactory *factory;  /* for logging */
416   GstObject *obj;               /* for logging */
417 } GstTypeFindBufHelper;
418
419 /*
420  * buf_helper_find_peek:
421  * @data: helper data struct
422  * @off: stream offset
423  * @size: block size
424  *
425  * Get data pointer within a buffer.
426  *
427  * Returns: (nullable): address inside the buffer or %NULL if buffer does not
428  * cover the requested range.
429  */
430 static const guint8 *
431 buf_helper_find_peek (gpointer data, gint64 off, guint size)
432 {
433   GstTypeFindBufHelper *helper;
434
435   helper = (GstTypeFindBufHelper *) data;
436   GST_LOG_OBJECT (helper->obj, "'%s' called peek (%" G_GINT64_FORMAT ", %u)",
437       GST_OBJECT_NAME (helper->factory), off, size);
438
439   if (size == 0)
440     return NULL;
441
442   if (off < 0) {
443     GST_LOG_OBJECT (helper->obj, "'%s' wanted to peek at end; not supported",
444         GST_OBJECT_NAME (helper->factory));
445     return NULL;
446   }
447
448   if ((off + size) <= helper->size)
449     return helper->data + off;
450
451   return NULL;
452 }
453
454 /*
455  * buf_helper_find_suggest:
456  * @data: helper data struct
457  * @probability: probability of the match
458  * @caps: caps of the type
459  *
460  * If given @probability is higher, replace previously store caps.
461  */
462 static void
463 buf_helper_find_suggest (gpointer data, guint probability, GstCaps * caps)
464 {
465   GstTypeFindBufHelper *helper = (GstTypeFindBufHelper *) data;
466
467   GST_LOG_OBJECT (helper->obj,
468       "'%s' called suggest (%u, %" GST_PTR_FORMAT ")",
469       GST_OBJECT_NAME (helper->factory), probability, caps);
470
471   /* Note: not >= as we call typefinders in order of rank, highest first */
472   if (probability > helper->best_probability) {
473     gst_caps_replace (&helper->caps, caps);
474     helper->best_probability = probability;
475   }
476 }
477
478 /**
479  * gst_type_find_helper_for_data:
480  * @obj: (allow-none): object doing the typefinding, or %NULL (used for logging)
481  * @data: (in) (transfer none): a pointer with data to typefind
482  * @size: (in): the size of @data
483  * @prob: (out) (allow-none): location to store the probability of the found
484  *     caps, or %NULL
485  *
486  * Tries to find what type of data is contained in the given @data, the
487  * assumption being that the data represents the beginning of the stream or
488  * file.
489  *
490  * All available typefinders will be called on the data in order of rank. If
491  * a typefinding function returns a probability of %GST_TYPE_FIND_MAXIMUM,
492  * typefinding is stopped immediately and the found caps will be returned
493  * right away. Otherwise, all available typefind functions will the tried,
494  * and the caps with the highest probability will be returned, or %NULL if
495  * the content of @data could not be identified.
496  *
497  * Free-function: gst_caps_unref
498  *
499  * Returns: (transfer full) (nullable): the #GstCaps corresponding to the data,
500  *     or %NULL if no type could be found. The caller should free the caps
501  *     returned with gst_caps_unref().
502  */
503 GstCaps *
504 gst_type_find_helper_for_data (GstObject * obj, const guint8 * data, gsize size,
505     GstTypeFindProbability * prob)
506 {
507   GstTypeFindBufHelper helper;
508   GstTypeFind find;
509   GList *l, *type_list;
510   GstCaps *result = NULL;
511
512   g_return_val_if_fail (data != NULL, NULL);
513
514   helper.data = data;
515   helper.size = size;
516   helper.best_probability = GST_TYPE_FIND_NONE;
517   helper.caps = NULL;
518   helper.obj = obj;
519
520   if (helper.data == NULL || helper.size == 0)
521     return NULL;
522
523   find.data = &helper;
524   find.peek = buf_helper_find_peek;
525   find.suggest = buf_helper_find_suggest;
526   find.get_length = NULL;
527
528   type_list = gst_type_find_factory_get_list ();
529
530   for (l = type_list; l; l = l->next) {
531     helper.factory = GST_TYPE_FIND_FACTORY (l->data);
532     gst_type_find_factory_call_function (helper.factory, &find);
533     if (helper.best_probability >= GST_TYPE_FIND_MAXIMUM)
534       break;
535   }
536   gst_plugin_feature_list_free (type_list);
537
538   if (helper.best_probability > 0)
539     result = helper.caps;
540
541   if (prob)
542     *prob = helper.best_probability;
543
544   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT " (probability = %u)",
545       result, (guint) helper.best_probability);
546
547   return result;
548 }
549
550 /**
551  * gst_type_find_helper_for_buffer:
552  * @obj: (allow-none): object doing the typefinding, or %NULL (used for logging)
553  * @buf: (in) (transfer none): a #GstBuffer with data to typefind
554  * @prob: (out) (allow-none): location to store the probability of the found
555  *     caps, or %NULL
556  *
557  * Tries to find what type of data is contained in the given #GstBuffer, the
558  * assumption being that the buffer represents the beginning of the stream or
559  * file.
560  *
561  * All available typefinders will be called on the data in order of rank. If
562  * a typefinding function returns a probability of %GST_TYPE_FIND_MAXIMUM,
563  * typefinding is stopped immediately and the found caps will be returned
564  * right away. Otherwise, all available typefind functions will the tried,
565  * and the caps with the highest probability will be returned, or %NULL if
566  * the content of the buffer could not be identified.
567  *
568  * Free-function: gst_caps_unref
569  *
570  * Returns: (transfer full) (nullable): the #GstCaps corresponding to the data,
571  *     or %NULL if no type could be found. The caller should free the caps
572  *     returned with gst_caps_unref().
573  */
574 GstCaps *
575 gst_type_find_helper_for_buffer (GstObject * obj, GstBuffer * buf,
576     GstTypeFindProbability * prob)
577 {
578   GstCaps *result;
579   GstMapInfo info;
580
581   g_return_val_if_fail (buf != NULL, NULL);
582   g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
583   g_return_val_if_fail (GST_BUFFER_OFFSET (buf) == 0 ||
584       GST_BUFFER_OFFSET (buf) == GST_BUFFER_OFFSET_NONE, NULL);
585
586   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
587     return NULL;
588   result = gst_type_find_helper_for_data (obj, info.data, info.size, prob);
589   gst_buffer_unmap (buf, &info);
590
591   return result;
592 }
593
594 /**
595  * gst_type_find_helper_for_extension:
596  * @obj: (allow-none): object doing the typefinding, or %NULL (used for logging)
597  * @extension: an extension
598  *
599  * Tries to find the best #GstCaps associated with @extension.
600  *
601  * All available typefinders will be checked against the extension in order
602  * of rank. The caps of the first typefinder that can handle @extension will be
603  * returned.
604  *
605  * Free-function: gst_caps_unref
606  *
607  * Returns: (transfer full) (nullable): the #GstCaps corresponding to
608  *     @extension, or %NULL if no type could be found. The caller should free
609  *     the caps returned with gst_caps_unref().
610  */
611 GstCaps *
612 gst_type_find_helper_for_extension (GstObject * obj, const gchar * extension)
613 {
614   GList *l, *type_list;
615   GstCaps *result = NULL;
616
617   g_return_val_if_fail (extension != NULL, NULL);
618
619   GST_LOG_OBJECT (obj, "finding caps for extension %s", extension);
620
621   type_list = gst_type_find_factory_get_list ();
622
623   for (l = type_list; l; l = g_list_next (l)) {
624     GstTypeFindFactory *factory;
625     const gchar *const *ext;
626
627     factory = GST_TYPE_FIND_FACTORY (l->data);
628
629     /* we only want to check those factories without a function */
630     if (gst_type_find_factory_has_function (factory))
631       continue;
632
633     /* get the extension that this typefind factory can handle */
634     ext = gst_type_find_factory_get_extensions (factory);
635     if (ext == NULL)
636       continue;
637
638     /* there are extension, see if one of them matches the requested
639      * extension */
640     while (*ext != NULL) {
641       if (strcmp (*ext, extension) == 0) {
642         /* we found a matching extension, take the caps */
643         if ((result = gst_type_find_factory_get_caps (factory))) {
644           gst_caps_ref (result);
645           goto done;
646         }
647       }
648       ++ext;
649     }
650   }
651 done:
652   gst_plugin_feature_list_free (type_list);
653
654   GST_LOG_OBJECT (obj, "Returning %" GST_PTR_FORMAT, result);
655
656   return result;
657 }