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