typefind: probe for DVD ISO files, to avoid matching H.264
[platform/upstream/gstreamer.git] / gst / typefind / gsttypefindfunctions.c
1 /* GStreamer
2  * Copyright (C) 2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
3  * Copyright (C) 2005-2009 Tim-Philipp Müller <tim centricular net>
4  * Copyright (C) 2009 Sebastian Dröge <sebastian.droege@collabora.co.uk>
5  *
6  * gsttypefindfunctions.c: collection of various typefind functions
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 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <glib.h>
29 #include <glib/gprintf.h>
30
31 /* don't want to add gio xdgmime typefinder if gio was disabled via configure */
32 #ifdef HAVE_GIO
33 #include <gio/gio.h>
34 #define USE_GIO
35 #endif
36
37 #include <gst/gst.h>
38
39 #include <stdio.h>
40 #include <string.h>
41 #include <ctype.h>
42
43 #include <gst/pbutils/pbutils.h>
44 #include <gst/base/gstbytereader.h>
45
46 GST_DEBUG_CATEGORY_STATIC (type_find_debug);
47 #define GST_CAT_DEFAULT type_find_debug
48
49 /* so our code stays ready for 0.11 */
50 #define gst_type_find_peek(tf,off,len) \
51     ((const guint8 *)gst_type_find_peek((tf),(off),(len)))
52
53 /* DataScanCtx: helper for typefind functions that scan through data
54  * step-by-step, to avoid doing a peek at each and every offset */
55
56 #define DATA_SCAN_CTX_CHUNK_SIZE 4096
57
58 typedef struct
59 {
60   guint64 offset;
61   const guint8 *data;
62   gint size;
63 } DataScanCtx;
64
65 static inline void
66 data_scan_ctx_advance (GstTypeFind * tf, DataScanCtx * c, guint bytes_to_skip)
67 {
68   c->offset += bytes_to_skip;
69   if (G_LIKELY (c->size > bytes_to_skip)) {
70     c->size -= bytes_to_skip;
71     c->data += bytes_to_skip;
72   } else {
73     c->data += c->size;
74     c->size = 0;
75   }
76 }
77
78 static inline gboolean
79 data_scan_ctx_ensure_data (GstTypeFind * tf, DataScanCtx * c, gint min_len)
80 {
81   const guint8 *data;
82   guint64 len;
83   guint chunk_len = MAX (DATA_SCAN_CTX_CHUNK_SIZE, min_len);
84
85   if (G_LIKELY (c->size >= min_len))
86     return TRUE;
87
88   data = gst_type_find_peek (tf, c->offset, chunk_len);
89   if (G_LIKELY (data != NULL)) {
90     c->data = data;
91     c->size = chunk_len;
92     return TRUE;
93   }
94
95   /* if there's less than our chunk size, try to get as much as we can, but
96    * always at least min_len bytes (we might be typefinding the first buffer
97    * of the stream and not have as much data available as we'd like) */
98   len = gst_type_find_get_length (tf);
99   if (len > 0) {
100     len = CLAMP (len - c->offset, min_len, chunk_len);
101   } else {
102     len = min_len;
103   }
104
105   data = gst_type_find_peek (tf, c->offset, len);
106   if (data != NULL) {
107     c->data = data;
108     c->size = len;
109     return TRUE;
110   }
111
112   return FALSE;
113 }
114
115 static inline gboolean
116 data_scan_ctx_memcmp (GstTypeFind * tf, DataScanCtx * c, guint offset,
117     const gchar * data, guint len)
118 {
119   if (!data_scan_ctx_ensure_data (tf, c, offset + len))
120     return FALSE;
121
122   return (memcmp (c->data + offset, data, len) == 0);
123 }
124
125 /*** text/plain ***/
126 static gboolean xml_check_first_element (GstTypeFind * tf,
127     const gchar * element, guint elen, gboolean strict);
128 static gboolean sdp_check_header (GstTypeFind * tf);
129
130 static GstStaticCaps utf8_caps = GST_STATIC_CAPS ("text/plain");
131
132 #define UTF8_CAPS gst_static_caps_get(&utf8_caps)
133
134 static gboolean
135 utf8_type_find_have_valid_utf8_at_offset (GstTypeFind * tf, guint64 offset,
136     GstTypeFindProbability * prob)
137 {
138   const guint8 *data;
139
140   /* randomly decided values */
141   guint min_size = 16;          /* minimum size  */
142   guint size = 32 * 1024;       /* starting size */
143   guint probability = 95;       /* starting probability */
144   guint step = 10;              /* how much we reduce probability in each
145                                  * iteration */
146
147   while (probability > step && size > min_size) {
148     data = gst_type_find_peek (tf, offset, size);
149     if (data) {
150       gchar *end;
151       gchar *start = (gchar *) data;
152
153       if (g_utf8_validate (start, size, (const gchar **) &end) || (end - start + 4 > size)) {   /* allow last char to be cut off */
154         *prob = probability;
155         return TRUE;
156       }
157       *prob = 0;
158       return FALSE;
159     }
160     size /= 2;
161     probability -= step;
162   }
163   *prob = 0;
164   return FALSE;
165 }
166
167 static void
168 utf8_type_find (GstTypeFind * tf, gpointer unused)
169 {
170   GstTypeFindProbability start_prob, mid_prob;
171   guint64 length;
172
173   /* leave xml to the xml typefinders */
174   if (xml_check_first_element (tf, "", 0, TRUE))
175     return;
176
177   /* leave sdp to the sdp typefinders */
178   if (sdp_check_header (tf))
179     return;
180
181   /* check beginning of stream */
182   if (!utf8_type_find_have_valid_utf8_at_offset (tf, 0, &start_prob))
183     return;
184
185   GST_LOG ("start is plain text with probability of %u", start_prob);
186
187   /* POSSIBLE is the highest probability we ever return if we can't
188    * probe into the middle of the file and don't know its length */
189
190   length = gst_type_find_get_length (tf);
191   if (length == 0 || length == (guint64) - 1) {
192     gst_type_find_suggest (tf, MIN (start_prob, GST_TYPE_FIND_POSSIBLE),
193         UTF8_CAPS);
194     return;
195   }
196
197   if (length < 64 * 1024) {
198     gst_type_find_suggest (tf, start_prob, UTF8_CAPS);
199     return;
200   }
201
202   /* check middle of stream */
203   if (!utf8_type_find_have_valid_utf8_at_offset (tf, length / 2, &mid_prob))
204     return;
205
206   GST_LOG ("middle is plain text with probability of %u", mid_prob);
207   gst_type_find_suggest (tf, (start_prob + mid_prob) / 2, UTF8_CAPS);
208 }
209
210 /*** text/utf-16 and text/utf-32} ***/
211 /* While UTF-8 is unicode too, using text/plain for UTF-16 and UTF-32
212    is going to break stuff. */
213
214 typedef struct
215 {
216   size_t bomlen;
217   const char *const bom;
218     gboolean (*checker) (const guint8 *, gint, gint);
219   int boost;
220   int endianness;
221 } GstUnicodeTester;
222
223 static gboolean
224 check_utf16 (const guint8 * data, gint len, gint endianness)
225 {
226   GstByteReader br;
227   guint16 high, low;
228
229   low = high = 0;
230
231   if (len & 1)
232     return FALSE;
233
234   gst_byte_reader_init (&br, data, len);
235   while (len >= 2) {
236     /* test first for a single 16 bit value in the BMP */
237     if (endianness == G_BIG_ENDIAN)
238       high = gst_byte_reader_get_uint16_be_unchecked (&br);
239     else
240       high = gst_byte_reader_get_uint16_le_unchecked (&br);
241     if (high >= 0xD800 && high <= 0xDBFF) {
242       /* start of a surrogate pair */
243       if (len < 4)
244         return FALSE;
245       len -= 2;
246       if (endianness == G_BIG_ENDIAN)
247         low = gst_byte_reader_get_uint16_be_unchecked (&br);
248       else
249         low = gst_byte_reader_get_uint16_le_unchecked (&br);
250       if (low >= 0xDC00 && low <= 0xDFFF) {
251         /* second half of the surrogate pair */
252       } else
253         return FALSE;
254     } else {
255       if (high >= 0xDC00 && high <= 0xDFFF)
256         return FALSE;
257     }
258     len -= 2;
259   }
260   return TRUE;
261 }
262
263 static gboolean
264 check_utf32 (const guint8 * data, gint len, gint endianness)
265 {
266   if (len & 3)
267     return FALSE;
268   while (len > 3) {
269     guint32 v;
270     if (endianness == G_BIG_ENDIAN)
271       v = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
272     else
273       v = (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0];
274     if (v >= 0x10FFFF)
275       return FALSE;
276     data += 4;
277     len -= 4;
278   }
279   return TRUE;
280 }
281
282 static void
283 unicode_type_find (GstTypeFind * tf, const GstUnicodeTester * tester,
284     guint n_tester, const char *media_type, gboolean require_bom)
285 {
286   size_t n;
287   gint len = 4;
288   const guint8 *data = gst_type_find_peek (tf, 0, len);
289   int prob = -1;
290   const gint max_scan_size = 256 * 1024;
291   int endianness = 0;
292
293   if (!data) {
294     len = 2;
295     data = gst_type_find_peek (tf, 0, len);
296     if (!data)
297       return;
298   }
299
300   /* find a large enough size that works */
301   while (len < max_scan_size) {
302     size_t newlen = len << 1;
303     const guint8 *newdata = gst_type_find_peek (tf, 0, newlen);
304     if (!newdata)
305       break;
306     len = newlen;
307     data = newdata;
308   }
309
310   for (n = 0; n < n_tester; ++n) {
311     int bom_boost = 0, tmpprob;
312     if (len >= tester[n].bomlen) {
313       if (!memcmp (data, tester[n].bom, tester[n].bomlen))
314         bom_boost = tester[n].boost;
315     }
316     if (require_bom && bom_boost == 0)
317       continue;
318     if (!(*tester[n].checker) (data, len, tester[n].endianness))
319       continue;
320     tmpprob = GST_TYPE_FIND_POSSIBLE - 20 + bom_boost;
321     if (tmpprob > prob) {
322       prob = tmpprob;
323       endianness = tester[n].endianness;
324     }
325   }
326
327   if (prob > 0) {
328     GST_DEBUG ("This is valid %s %s", media_type,
329         endianness == G_BIG_ENDIAN ? "be" : "le");
330     gst_type_find_suggest_simple (tf, prob, media_type,
331         "endianness", G_TYPE_INT, endianness, NULL);
332   }
333 }
334
335 static GstStaticCaps utf16_caps = GST_STATIC_CAPS ("text/utf-16");
336
337 #define UTF16_CAPS gst_static_caps_get(&utf16_caps)
338
339 static void
340 utf16_type_find (GstTypeFind * tf, gpointer unused)
341 {
342   static const GstUnicodeTester utf16tester[2] = {
343     {2, "\xff\xfe", check_utf16, 10, G_LITTLE_ENDIAN},
344     {2, "\xfe\xff", check_utf16, 20, G_BIG_ENDIAN},
345   };
346   unicode_type_find (tf, utf16tester, G_N_ELEMENTS (utf16tester),
347       "text/utf-16", TRUE);
348 }
349
350 static GstStaticCaps utf32_caps = GST_STATIC_CAPS ("text/utf-32");
351
352 #define UTF32_CAPS gst_static_caps_get(&utf32_caps)
353
354 static void
355 utf32_type_find (GstTypeFind * tf, gpointer unused)
356 {
357   static const GstUnicodeTester utf32tester[2] = {
358     {4, "\xff\xfe\x00\x00", check_utf32, 10, G_LITTLE_ENDIAN},
359     {4, "\x00\x00\xfe\xff", check_utf32, 20, G_BIG_ENDIAN}
360   };
361   unicode_type_find (tf, utf32tester, G_N_ELEMENTS (utf32tester),
362       "text/utf-32", TRUE);
363 }
364
365 /*** text/uri-list ***/
366
367 static GstStaticCaps uri_caps = GST_STATIC_CAPS ("text/uri-list");
368
369 #define URI_CAPS (gst_static_caps_get(&uri_caps))
370 #define BUFFER_SIZE 16          /* If the string is < 16 bytes we're screwed */
371 #define INC_BUFFER {                                                    \
372   pos++;                                                                \
373   if (pos == BUFFER_SIZE) {                                             \
374     pos = 0;                                                            \
375     offset += BUFFER_SIZE;                                              \
376     data = gst_type_find_peek (tf, offset, BUFFER_SIZE);                \
377     if (data == NULL) return;                                           \
378   } else {                                                              \
379     data++;                                                             \
380   }                                                                     \
381 }
382 static void
383 uri_type_find (GstTypeFind * tf, gpointer unused)
384 {
385   const guint8 *data = gst_type_find_peek (tf, 0, BUFFER_SIZE);
386   guint pos = 0;
387   guint offset = 0;
388
389   if (data) {
390     /* Search for # comment lines */
391     while (*data == '#') {
392       /* Goto end of line */
393       while (*data != '\n') {
394         INC_BUFFER;
395       }
396
397       INC_BUFFER;
398     }
399
400     if (!g_ascii_isalpha (*data)) {
401       /* Had a non alpha char - can't be uri-list */
402       return;
403     }
404
405     INC_BUFFER;
406
407     while (g_ascii_isalnum (*data)) {
408       INC_BUFFER;
409     }
410
411     if (*data != ':') {
412       /* First non alpha char is not a : */
413       return;
414     }
415
416     /* Get the next 2 bytes as well */
417     data = gst_type_find_peek (tf, offset + pos, 3);
418     if (data == NULL)
419       return;
420
421     if (data[1] != '/' && data[2] != '/') {
422       return;
423     }
424
425     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, URI_CAPS);
426   }
427 }
428
429 /*** application/x-hls ***/
430
431 static GstStaticCaps hls_caps = GST_STATIC_CAPS ("application/x-hls");
432 #define HLS_CAPS (gst_static_caps_get(&hls_caps))
433
434 /* See http://tools.ietf.org/html/draft-pantos-http-live-streaming-05 */
435 static void
436 hls_type_find (GstTypeFind * tf, gpointer unused)
437 {
438   DataScanCtx c = { 0, NULL, 0 };
439
440   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 7)))
441     return;
442
443   if (memcmp (c.data, "#EXTM3U", 7))
444     return;
445
446   data_scan_ctx_advance (tf, &c, 7);
447
448   /* Check only the first 256 bytes */
449   while (c.offset < 256) {
450     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 21)))
451       return;
452
453     /* Search for # comment lines */
454     if (c.data[0] == '#' && (memcmp (c.data, "#EXT-X-TARGETDURATION", 21) == 0
455             || memcmp (c.data, "#EXT-X-STREAM-INF", 17) == 0)) {
456       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, HLS_CAPS);
457       return;
458     }
459
460     data_scan_ctx_advance (tf, &c, 1);
461   }
462 }
463
464
465 /*** application/xml **********************************************************/
466
467 #define XML_BUFFER_SIZE 16
468 #define XML_INC_BUFFER {                                                \
469   pos++;                                                                \
470   if (pos == XML_BUFFER_SIZE) {                                         \
471     pos = 0;                                                            \
472     offset += XML_BUFFER_SIZE;                                          \
473     data = gst_type_find_peek (tf, offset, XML_BUFFER_SIZE);            \
474     if (data == NULL) return FALSE;                                     \
475   } else {                                                              \
476     data++;                                                             \
477   }                                                                     \
478 }
479
480 static gboolean
481 xml_check_first_element (GstTypeFind * tf, const gchar * element, guint elen,
482     gboolean strict)
483 {
484   gboolean got_xmldec;
485   const guint8 *data;
486   guint offset = 0;
487   guint pos = 0;
488
489   data = gst_type_find_peek (tf, 0, XML_BUFFER_SIZE);
490   if (!data)
491     return FALSE;
492
493   /* look for the XMLDec
494    * see XML spec 2.8, Prolog and Document Type Declaration
495    * http://www.w3.org/TR/2004/REC-xml-20040204/#sec-prolog-dtd */
496   got_xmldec = (memcmp (data, "<?xml", 5) == 0);
497
498   if (strict && !got_xmldec)
499     return FALSE;
500
501   /* skip XMLDec in any case if we've got one */
502   if (got_xmldec) {
503     pos += 5;
504     data += 5;
505   }
506
507   /* look for the first element, it has to be the requested element. Bail
508    * out if it is not within the first 4kB. */
509   while (data && (offset + pos) < 4096) {
510     while (*data != '<' && (offset + pos) < 4096) {
511       XML_INC_BUFFER;
512     }
513
514     XML_INC_BUFFER;
515     if (!g_ascii_isalpha (*data)) {
516       /* if not alphabetic, it's a PI or an element / attribute declaration
517        * like <?xxx or <!xxx */
518       XML_INC_BUFFER;
519       continue;
520     }
521
522     /* the first normal element, check if it's the one asked for */
523     data = gst_type_find_peek (tf, offset + pos, elen + 1);
524     return (data && element && strncmp ((char *) data, element, elen) == 0);
525   }
526
527   return FALSE;
528 }
529
530 static GstStaticCaps generic_xml_caps = GST_STATIC_CAPS ("application/xml");
531
532 #define GENERIC_XML_CAPS (gst_static_caps_get(&generic_xml_caps))
533 static void
534 xml_type_find (GstTypeFind * tf, gpointer unused)
535 {
536   if (xml_check_first_element (tf, "", 0, TRUE)) {
537     gst_type_find_suggest (tf, GST_TYPE_FIND_MINIMUM, GENERIC_XML_CAPS);
538   }
539 }
540
541 /*** application/sdp *********************************************************/
542
543 static GstStaticCaps sdp_caps = GST_STATIC_CAPS ("application/sdp");
544
545 #define SDP_CAPS (gst_static_caps_get(&sdp_caps))
546 static gboolean
547 sdp_check_header (GstTypeFind * tf)
548 {
549   const guint8 *data;
550
551   data = gst_type_find_peek (tf, 0, 5);
552   if (!data)
553     return FALSE;
554
555   /* sdp must start with v=0[\r]\n */
556   if (memcmp (data, "v=0", 3))
557     return FALSE;
558
559   if (data[3] == '\r' && data[4] == '\n')
560     return TRUE;
561   if (data[3] == '\n')
562     return TRUE;
563
564   return FALSE;
565 }
566
567 static void
568 sdp_type_find (GstTypeFind * tf, gpointer unused)
569 {
570   if (sdp_check_header (tf))
571     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SDP_CAPS);
572 }
573
574 /*** application/smil *********************************************************/
575
576 static GstStaticCaps smil_caps = GST_STATIC_CAPS ("application/smil");
577
578 #define SMIL_CAPS (gst_static_caps_get(&smil_caps))
579 static void
580 smil_type_find (GstTypeFind * tf, gpointer unused)
581 {
582   if (xml_check_first_element (tf, "smil", 4, FALSE)) {
583     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SMIL_CAPS);
584   }
585 }
586
587 /*** text/html ***/
588
589 static GstStaticCaps html_caps = GST_STATIC_CAPS ("text/html");
590
591 #define HTML_CAPS gst_static_caps_get (&html_caps)
592
593 static void
594 html_type_find (GstTypeFind * tf, gpointer unused)
595 {
596   const gchar *d, *data;
597
598   data = (const gchar *) gst_type_find_peek (tf, 0, 16);
599   if (!data)
600     return;
601
602   if (!g_ascii_strncasecmp (data, "<!DOCTYPE HTML", 14)) {
603     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, HTML_CAPS);
604   } else if (xml_check_first_element (tf, "html", 4, FALSE)) {
605     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, HTML_CAPS);
606   } else if ((d = memchr (data, '<', 16))) {
607     data = (const gchar *) gst_type_find_peek (tf, d - data, 6);
608     if (data && g_ascii_strncasecmp (data, "<html>", 6) == 0) {
609       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, HTML_CAPS);
610     }
611   }
612 }
613
614 /*** audio/midi ***/
615
616 static GstStaticCaps mid_caps = GST_STATIC_CAPS ("audio/midi");
617
618 #define MID_CAPS gst_static_caps_get(&mid_caps)
619 static void
620 mid_type_find (GstTypeFind * tf, gpointer unused)
621 {
622   const guint8 *data = gst_type_find_peek (tf, 0, 4);
623
624   /* http://jedi.ks.uiuc.edu/~johns/links/music/midifile.html */
625   if (data && data[0] == 'M' && data[1] == 'T' && data[2] == 'h'
626       && data[3] == 'd')
627     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MID_CAPS);
628 }
629
630 /*** audio/mobile-xmf ***/
631
632 static GstStaticCaps mxmf_caps = GST_STATIC_CAPS ("audio/mobile-xmf");
633
634 #define MXMF_CAPS gst_static_caps_get(&mxmf_caps)
635 static void
636 mxmf_type_find (GstTypeFind * tf, gpointer unused)
637 {
638   const guint8 *data = NULL;
639
640   /* Search FileId "XMF_" 4 bytes */
641   data = gst_type_find_peek (tf, 0, 4);
642   if (data && data[0] == 'X' && data[1] == 'M' && data[2] == 'F'
643       && data[3] == '_') {
644     /* Search Format version "2.00" 4 bytes */
645     data = gst_type_find_peek (tf, 4, 4);
646     if (data && data[0] == '2' && data[1] == '.' && data[2] == '0'
647         && data[3] == '0') {
648       /* Search TypeId 2     1 byte */
649       data = gst_type_find_peek (tf, 11, 1);
650       if (data && data[0] == 2) {
651         gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MXMF_CAPS);
652       }
653     }
654   }
655 }
656
657
658 /*** video/x-fli ***/
659
660 static GstStaticCaps flx_caps = GST_STATIC_CAPS ("video/x-fli");
661
662 #define FLX_CAPS gst_static_caps_get(&flx_caps)
663 static void
664 flx_type_find (GstTypeFind * tf, gpointer unused)
665 {
666   const guint8 *data = gst_type_find_peek (tf, 0, 134);
667
668   if (data) {
669     /* check magic and the frame type of the first frame */
670     if ((data[4] == 0x11 || data[4] == 0x12 ||
671             data[4] == 0x30 || data[4] == 0x44) &&
672         data[5] == 0xaf &&
673         ((data[132] == 0x00 || data[132] == 0xfa) && data[133] == 0xf1)) {
674       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, FLX_CAPS);
675     }
676     return;
677   }
678   data = gst_type_find_peek (tf, 0, 6);
679   if (data) {
680     /* check magic only */
681     if ((data[4] == 0x11 || data[4] == 0x12 ||
682             data[4] == 0x30 || data[4] == 0x44) && data[5] == 0xaf) {
683       gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, FLX_CAPS);
684     }
685     return;
686   }
687 }
688
689 /*** application/x-id3 ***/
690
691 static GstStaticCaps id3_caps = GST_STATIC_CAPS ("application/x-id3");
692
693 #define ID3_CAPS gst_static_caps_get(&id3_caps)
694 static void
695 id3v2_type_find (GstTypeFind * tf, gpointer unused)
696 {
697   const guint8 *data = gst_type_find_peek (tf, 0, 10);
698
699   if (data && memcmp (data, "ID3", 3) == 0 &&
700       data[3] != 0xFF && data[4] != 0xFF &&
701       (data[6] & 0x80) == 0 && (data[7] & 0x80) == 0 &&
702       (data[8] & 0x80) == 0 && (data[9] & 0x80) == 0) {
703     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, ID3_CAPS);
704   }
705 }
706
707 static void
708 id3v1_type_find (GstTypeFind * tf, gpointer unused)
709 {
710   const guint8 *data = gst_type_find_peek (tf, -128, 3);
711
712   if (data && memcmp (data, "TAG", 3) == 0) {
713     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, ID3_CAPS);
714   }
715 }
716
717 /*** application/x-ape ***/
718
719 static GstStaticCaps apetag_caps = GST_STATIC_CAPS ("application/x-apetag");
720
721 #define APETAG_CAPS gst_static_caps_get(&apetag_caps)
722 static void
723 apetag_type_find (GstTypeFind * tf, gpointer unused)
724 {
725   const guint8 *data;
726
727   /* APEv1/2 at start of file */
728   data = gst_type_find_peek (tf, 0, 8);
729   if (data && !memcmp (data, "APETAGEX", 8)) {
730     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, APETAG_CAPS);
731     return;
732   }
733
734   /* APEv1/2 at end of file */
735   data = gst_type_find_peek (tf, -32, 8);
736   if (data && !memcmp (data, "APETAGEX", 8)) {
737     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, APETAG_CAPS);
738     return;
739   }
740 }
741
742 /*** audio/x-ttafile ***/
743
744 static GstStaticCaps tta_caps = GST_STATIC_CAPS ("audio/x-ttafile");
745
746 #define TTA_CAPS gst_static_caps_get(&tta_caps)
747 static void
748 tta_type_find (GstTypeFind * tf, gpointer unused)
749 {
750   const guint8 *data = gst_type_find_peek (tf, 0, 3);
751
752   if (data) {
753     if (memcmp (data, "TTA", 3) == 0) {
754       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, TTA_CAPS);
755       return;
756     }
757   }
758 }
759
760 /*** audio/x-flac ***/
761 static GstStaticCaps flac_caps = GST_STATIC_CAPS ("audio/x-flac");
762
763 #define FLAC_CAPS (gst_static_caps_get(&flac_caps))
764
765 static void
766 flac_type_find (GstTypeFind * tf, gpointer unused)
767 {
768   DataScanCtx c = { 0, NULL, 0 };
769
770   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 4)))
771     return;
772
773   /* standard flac (also old/broken flac-in-ogg with an initial 4-byte marker
774    * packet and without the usual packet framing) */
775   if (memcmp (c.data, "fLaC", 4) == 0) {
776     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, FLAC_CAPS);
777     return;
778   }
779
780   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 6)))
781     return;
782
783   /* flac-in-ogg, see http://flac.sourceforge.net/ogg_mapping.html */
784   if (memcmp (c.data, "\177FLAC\001", 6) == 0) {
785     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, FLAC_CAPS);
786     return;
787   }
788
789 /* disabled because it happily typefinds /dev/urandom as audio/x-flac, and
790  * because I yet have to see header-less flac in the wild */
791 #if 0
792   /* flac without headers (subset format) */
793   /* 64K should be enough */
794   while (c.offset < (64 * 1024)) {
795     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 4)))
796       break;
797
798     /* look for frame header,
799      * http://flac.sourceforge.net/format.html#frame_header
800      */
801     if (c.data[0] == 0xff && (c.data[1] >> 2) == 0x3e) {
802       /* bit 15 in the header must be 0 */
803       if (((c.data[1] >> 1) & 0x01) == 0x01)
804         goto advance;
805
806       /* blocksize must be != 0x00 */
807       if ((c.data[2] >> 4) == 0x00)
808         goto advance;
809
810       /* samplerate must be != 0x0f */
811       if ((c.data[2] & 0x0f) == 0x0f)
812         goto advance;
813       /* also 0 is invalid, as it means get the info from the header and we
814        * don't have headers if we are here */
815       if ((c.data[2] & 0x0f) == 0x00)
816         goto advance;
817
818       /* channel assignment must be < 11 */
819       if ((c.data[3] >> 4) >= 11)
820         goto advance;
821
822       /* sample size must be != 0x07 and != 0x05 */
823       if (((c.data[3] >> 1) & 0x07) == 0x07)
824         goto advance;
825       if (((c.data[3] >> 1) & 0x07) == 0x05)
826         goto advance;
827       /* also 0 is invalid, as it means get the info from the header and we
828        * don't have headers if we are here */
829       if (((c.data[3] >> 1) & 0x07) == 0x00)
830         goto advance;
831
832       /* next bit must be 0 */
833       if ((c.data[3] & 0x01) == 0x01)
834         goto advance;
835
836       /* FIXME: shouldn't we include the crc check ? */
837
838       GST_DEBUG ("Found flac without headers at %d", (gint) c.offset);
839       gst_type_find_suggest (tf, GST_TYPE_FIND_POSSIBLE, FLAC_CAPS);
840       return;
841     }
842   advance:
843     data_scan_ctx_advance (tf, &c, 1);
844   }
845 #endif
846 }
847
848 /*** audio/mpeg version 2, 4 ***/
849
850 static GstStaticCaps aac_caps = GST_STATIC_CAPS ("audio/mpeg, "
851     "mpegversion = (int) { 2, 4 }, framed = (bool) false");
852 #define AAC_CAPS (gst_static_caps_get(&aac_caps))
853 #define AAC_AMOUNT (4096)
854 static void
855 aac_type_find (GstTypeFind * tf, gpointer unused)
856 {
857   /* LUT to convert the AudioObjectType from the ADTS header to a string */
858   DataScanCtx c = { 0, NULL, 0 };
859
860   while (c.offset < AAC_AMOUNT) {
861     guint snc, len;
862
863     /* detect adts header or adif header.
864      * The ADIF header is 4 bytes, that should be OK. The ADTS header, on
865      * the other hand, is 14 bits only, so we require one valid frame with
866      * again a valid syncpoint on the next one (28 bits) for certainty. We
867      * require 4 kB, which is quite a lot, since frames are generally 200-400
868      * bytes.
869      * LOAS has 2 possible syncwords, which are 11 bits and 16 bits long.
870      * The following stream syntax depends on which one is found.
871      */
872     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 6)))
873       break;
874
875     snc = GST_READ_UINT16_BE (c.data);
876     if (G_UNLIKELY ((snc & 0xfff6) == 0xfff0)) {
877       /* ADTS header - find frame length */
878       GST_DEBUG ("Found one ADTS syncpoint at offset 0x%" G_GINT64_MODIFIER
879           "x, tracing next...", c.offset);
880       len = ((c.data[3] & 0x03) << 11) |
881           (c.data[4] << 3) | ((c.data[5] & 0xe0) >> 5);
882
883       if (len == 0 || !data_scan_ctx_ensure_data (tf, &c, len + 2)) {
884         GST_DEBUG ("Wrong sync or next frame not within reach, len=%u", len);
885         goto next;
886       }
887
888       /* check if there's a second ADTS frame */
889       snc = GST_READ_UINT16_BE (c.data + len);
890       if ((snc & 0xfff6) == 0xfff0) {
891         GstCaps *caps;
892         guint mpegversion, sample_freq_idx, channel_config, profile_idx, rate;
893         guint8 audio_config[2];
894
895         mpegversion = (c.data[1] & 0x08) ? 2 : 4;
896         profile_idx = c.data[2] >> 6;
897         sample_freq_idx = ((c.data[2] & 0x3c) >> 2);
898         channel_config = ((c.data[2] & 0x01) << 2) + (c.data[3] >> 6);
899
900         GST_DEBUG ("Found second ADTS-%d syncpoint at offset 0x%"
901             G_GINT64_MODIFIER "x, framelen %u", mpegversion, c.offset, len);
902
903         /* 0xd and 0xe are reserved. 0xf means the sample frequency is directly
904          * specified in the header, but that's not allowed for ADTS */
905         if (sample_freq_idx > 0xc) {
906           GST_DEBUG ("Unexpected sample frequency index %d or wrong sync",
907               sample_freq_idx);
908           goto next;
909         }
910
911         rate = gst_codec_utils_aac_get_sample_rate_from_index (sample_freq_idx);
912         GST_LOG ("ADTS: profile=%u, rate=%u", profile_idx, rate);
913
914         /* The ADTS frame header is slightly different from the
915          * AudioSpecificConfig defined for the MPEG-4 container, so we just
916          * construct enough of it for getting the level here. */
917         /* ADTS counts profiles from 0 instead of 1 to save bits */
918         audio_config[0] = (profile_idx + 1) << 3;
919         audio_config[0] |= (sample_freq_idx >> 1) & 0x7;
920         audio_config[1] = (sample_freq_idx & 0x1) << 7;
921         audio_config[1] |= (channel_config & 0xf) << 3;
922
923         caps = gst_caps_new_simple ("audio/mpeg",
924             "framed", G_TYPE_BOOLEAN, FALSE,
925             "mpegversion", G_TYPE_INT, mpegversion,
926             "stream-format", G_TYPE_STRING, "adts", NULL);
927
928         gst_codec_utils_aac_caps_set_level_and_profile (caps, audio_config, 2);
929
930         /* add rate and number of channels if we can */
931         if (channel_config != 0 && channel_config <= 7) {
932           const guint channels_map[] = { 0, 1, 2, 3, 4, 5, 6, 8 };
933
934           gst_caps_set_simple (caps, "channels", G_TYPE_INT,
935               channels_map[channel_config], "rate", G_TYPE_INT, rate, NULL);
936         }
937
938         gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, caps);
939         gst_caps_unref (caps);
940         break;
941       }
942
943       GST_DEBUG ("No next frame found... (should have been at 0x%x)", len);
944     } else if (G_UNLIKELY (((snc & 0xffe0) == 0x56e0) || (snc == 0x4de1))) {
945       /* LOAS frame */
946
947       GST_DEBUG ("Found one LOAS syncword at offset 0x%" G_GINT64_MODIFIER
948           "x, tracing next...", c.offset);
949
950       /* check length of frame for each type of detectable LOAS streams */
951       if (snc == 0x4de1) {
952         /* EPAudioSyncStream */
953         len = ((c.data[2] & 0x0f) << 9) | (c.data[3] << 1) |
954             ((c.data[4] & 0x80) >> 7);
955         /* add size of EP sync stream header */
956         len += 7;
957       } else {
958         /* AudioSyncStream */
959         len = ((c.data[1] & 0x1f) << 8) | c.data[2];
960         /* add size of sync stream header */
961         len += 3;
962       }
963
964       if (len == 0 || !data_scan_ctx_ensure_data (tf, &c, len + 2)) {
965         GST_DEBUG ("Wrong sync or next frame not within reach, len=%u", len);
966         goto next;
967       }
968
969       /* check if there's a second LOAS frame */
970       snc = GST_READ_UINT16_BE (c.data + len);
971       if (((snc & 0xffe0) == 0x56e0) || (snc == 0x4de1)) {
972         GST_DEBUG ("Found second LOAS syncword at offset 0x%"
973             G_GINT64_MODIFIER "x, framelen %u", c.offset, len);
974
975         gst_type_find_suggest_simple (tf, GST_TYPE_FIND_LIKELY, "audio/mpeg",
976             "framed", G_TYPE_BOOLEAN, FALSE,
977             "mpegversion", G_TYPE_INT, 4,
978             "stream-format", G_TYPE_STRING, "loas", NULL);
979         break;
980       }
981
982       GST_DEBUG ("No next frame found... (should have been at 0x%x)", len);
983     } else if (!memcmp (c.data, "ADIF", 4)) {
984       /* ADIF header */
985       gst_type_find_suggest_simple (tf, GST_TYPE_FIND_LIKELY, "audio/mpeg",
986           "framed", G_TYPE_BOOLEAN, FALSE, "mpegversion", G_TYPE_INT, 4,
987           "stream-format", G_TYPE_STRING, "adif", NULL);
988       break;
989     }
990
991   next:
992
993     data_scan_ctx_advance (tf, &c, 1);
994   }
995 }
996
997 /*** audio/mpeg version 1 ***/
998
999 /*
1000  * The chance that random data is identified as a valid mp3 header is 63 / 2^18
1001  * (0.024%) per try. This makes the function for calculating false positives
1002  *   1 - (1 - ((63 / 2 ^18) ^ GST_MP3_TYPEFIND_MIN_HEADERS)) ^ buffersize)
1003  * This has the following probabilities of false positives:
1004  * datasize               MIN_HEADERS
1005  * (bytes)      1       2       3       4
1006  * 4096         62.6%    0.02%   0%      0%
1007  * 16384        98%      0.09%   0%      0%
1008  * 1 MiB       100%      5.88%   0%      0%
1009  * 1 GiB       100%    100%      1.44%   0%
1010  * 1 TiB       100%    100%    100%      0.35%
1011  * This means that the current choice (3 headers by most of the time 4096 byte
1012  * buffers is pretty safe for now.
1013  *
1014  * The max. size of each frame is 1440 bytes, which means that for N frames to
1015  * be detected, we need 1440 * GST_MP3_TYPEFIND_MIN_HEADERS + 3 bytes of data.
1016  * Assuming we step into the stream right after the frame header, this
1017  * means we need 1440 * (GST_MP3_TYPEFIND_MIN_HEADERS + 1) - 1 + 3 bytes
1018  * of data (5762) to always detect any mp3.
1019  */
1020
1021 static const guint mp3types_bitrates[2][3][16] =
1022     { {{0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,},
1023     {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,},
1024     {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,}},
1025 {{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,},
1026     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,},
1027     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,}},
1028 };
1029
1030 static const guint mp3types_freqs[3][3] = { {11025, 12000, 8000},
1031 {22050, 24000, 16000},
1032 {44100, 48000, 32000}
1033 };
1034
1035 static inline guint
1036 mp3_type_frame_length_from_header (guint32 header, guint * put_layer,
1037     guint * put_channels, guint * put_bitrate, guint * put_samplerate,
1038     gboolean * may_be_free_format, gint possible_free_framelen)
1039 {
1040   guint bitrate, layer, length, mode, samplerate, version, channels;
1041
1042   if ((header & 0xffe00000) != 0xffe00000)
1043     return 0;
1044
1045   /* we don't need extension, copyright, original or
1046    * emphasis for the frame length */
1047   header >>= 6;
1048
1049   /* mode */
1050   mode = header & 0x3;
1051   header >>= 3;
1052
1053   /* padding */
1054   length = header & 0x1;
1055   header >>= 1;
1056
1057   /* sampling frequency */
1058   samplerate = header & 0x3;
1059   if (samplerate == 3)
1060     return 0;
1061   header >>= 2;
1062
1063   /* bitrate index */
1064   bitrate = header & 0xF;
1065   if (bitrate == 0 && possible_free_framelen == -1) {
1066     GST_LOG ("Possibly a free format mp3 - signaling");
1067     *may_be_free_format = TRUE;
1068   }
1069   if (bitrate == 15 || (bitrate == 0 && possible_free_framelen == -1))
1070     return 0;
1071
1072   /* ignore error correction, too */
1073   header >>= 5;
1074
1075   /* layer */
1076   layer = 4 - (header & 0x3);
1077   if (layer == 4)
1078     return 0;
1079   header >>= 2;
1080
1081   /* version 0=MPEG2.5; 2=MPEG2; 3=MPEG1 */
1082   version = header & 0x3;
1083   if (version == 1)
1084     return 0;
1085
1086   /* lookup */
1087   channels = (mode == 3) ? 1 : 2;
1088   samplerate = mp3types_freqs[version > 0 ? version - 1 : 0][samplerate];
1089   if (bitrate == 0) {
1090     if (layer == 1) {
1091       length *= 4;
1092       length += possible_free_framelen;
1093       bitrate = length * samplerate / 48000;
1094     } else {
1095       length += possible_free_framelen;
1096       bitrate = length * samplerate /
1097           ((layer == 3 && version != 3) ? 72000 : 144000);
1098     }
1099   } else {
1100     /* calculating */
1101     bitrate = mp3types_bitrates[version == 3 ? 0 : 1][layer - 1][bitrate];
1102     if (layer == 1) {
1103       length = ((12000 * bitrate / samplerate) + length) * 4;
1104     } else {
1105       length += ((layer == 3
1106               && version != 3) ? 72000 : 144000) * bitrate / samplerate;
1107     }
1108   }
1109
1110   GST_LOG ("mp3typefind: calculated mp3 frame length of %u bytes", length);
1111   GST_LOG
1112       ("mp3typefind: samplerate = %u - bitrate = %u - layer = %u - version = %u"
1113       " - channels = %u", samplerate, bitrate, layer, version, channels);
1114
1115   if (put_layer)
1116     *put_layer = layer;
1117   if (put_channels)
1118     *put_channels = channels;
1119   if (put_bitrate)
1120     *put_bitrate = bitrate;
1121   if (put_samplerate)
1122     *put_samplerate = samplerate;
1123
1124   return length;
1125 }
1126
1127
1128 static GstStaticCaps mp3_caps = GST_STATIC_CAPS ("audio/mpeg, "
1129     "mpegversion = (int) 1, layer = (int) [ 1, 3 ]");
1130 #define MP3_CAPS (gst_static_caps_get(&mp3_caps))
1131 /*
1132  * random values for typefinding
1133  * if no more data is available, we will return a probability of
1134  * (found_headers/TRY_HEADERS) * (MAXIMUM * (TRY_SYNC - bytes_skipped)
1135  *        / TRY_SYNC)
1136  * if found_headers >= MIN_HEADERS
1137  */
1138 #define GST_MP3_TYPEFIND_MIN_HEADERS (2)
1139 #define GST_MP3_TYPEFIND_TRY_HEADERS (5)
1140 #define GST_MP3_TYPEFIND_TRY_SYNC (GST_TYPE_FIND_MAXIMUM * 100) /* 10kB */
1141 #define GST_MP3_TYPEFIND_SYNC_SIZE (2048)
1142 #define GST_MP3_WRONG_HEADER (10)
1143
1144 static void
1145 mp3_type_find_at_offset (GstTypeFind * tf, guint64 start_off,
1146     guint * found_layer, GstTypeFindProbability * found_prob)
1147 {
1148   const guint8 *data = NULL;
1149   const guint8 *data_end = NULL;
1150   guint size;
1151   guint64 skipped;
1152   gint last_free_offset = -1;
1153   gint last_free_framelen = -1;
1154   gboolean headerstart = TRUE;
1155
1156   *found_layer = 0;
1157   *found_prob = 0;
1158
1159   size = 0;
1160   skipped = 0;
1161   while (skipped < GST_MP3_TYPEFIND_TRY_SYNC) {
1162     if (size <= 0) {
1163       size = GST_MP3_TYPEFIND_SYNC_SIZE * 2;
1164       do {
1165         size /= 2;
1166         data = gst_type_find_peek (tf, skipped + start_off, size);
1167       } while (size > 10 && !data);
1168       if (!data)
1169         break;
1170       data_end = data + size;
1171     }
1172     if (*data == 0xFF) {
1173       const guint8 *head_data = NULL;
1174       guint layer = 0, bitrate, samplerate, channels;
1175       guint found = 0;          /* number of valid headers found */
1176       guint64 offset = skipped;
1177       gboolean changed = FALSE;
1178
1179       while (found < GST_MP3_TYPEFIND_TRY_HEADERS) {
1180         guint32 head;
1181         guint length;
1182         guint prev_layer = 0;
1183         guint prev_channels = 0, prev_samplerate = 0;
1184         gboolean free = FALSE;
1185
1186         if ((gint64) (offset - skipped + 4) >= 0 &&
1187             data + offset - skipped + 4 < data_end) {
1188           head_data = data + offset - skipped;
1189         } else {
1190           head_data = gst_type_find_peek (tf, offset + start_off, 4);
1191         }
1192         if (!head_data)
1193           break;
1194         head = GST_READ_UINT32_BE (head_data);
1195         if (!(length = mp3_type_frame_length_from_header (head, &layer,
1196                     &channels, &bitrate, &samplerate, &free,
1197                     last_free_framelen))) {
1198           if (free) {
1199             if (last_free_offset == -1)
1200               last_free_offset = offset;
1201             else {
1202               last_free_framelen = offset - last_free_offset;
1203               offset = last_free_offset;
1204               continue;
1205             }
1206           } else {
1207             last_free_framelen = -1;
1208           }
1209
1210           /* Mark the fact that we didn't find a valid header at the beginning */
1211           if (found == 0)
1212             headerstart = FALSE;
1213
1214           GST_LOG ("%d. header at offset %" G_GUINT64_FORMAT
1215               " (0x%" G_GINT64_MODIFIER "x) was not an mp3 header "
1216               "(possibly-free: %s)", found + 1, start_off + offset,
1217               start_off + offset, free ? "yes" : "no");
1218           break;
1219         }
1220         if ((prev_layer && prev_layer != layer) ||
1221             /* (prev_bitrate && prev_bitrate != bitrate) || <-- VBR */
1222             (prev_samplerate && prev_samplerate != samplerate) ||
1223             (prev_channels && prev_channels != channels)) {
1224           /* this means an invalid property, or a change, which might mean
1225            * that this is not a mp3 but just a random bytestream. It could
1226            * be a freaking funky encoded mp3 though. We'll just not count
1227            * this header*/
1228           if (prev_layer)
1229             changed = TRUE;
1230           prev_layer = layer;
1231           prev_channels = channels;
1232           prev_samplerate = samplerate;
1233         } else {
1234           found++;
1235           GST_LOG ("found %d. header at offset %" G_GUINT64_FORMAT " (0x%"
1236               G_GINT64_MODIFIER "X)", found, start_off + offset,
1237               start_off + offset);
1238         }
1239         offset += length;
1240       }
1241       g_assert (found <= GST_MP3_TYPEFIND_TRY_HEADERS);
1242       if (head_data == NULL &&
1243           gst_type_find_peek (tf, offset + start_off - 1, 1) == NULL)
1244         /* Incomplete last frame - don't count it. */
1245         found--;
1246       if (found == GST_MP3_TYPEFIND_TRY_HEADERS ||
1247           (found >= GST_MP3_TYPEFIND_MIN_HEADERS && head_data == NULL)) {
1248         /* we can make a valid guess */
1249         guint probability = found * GST_TYPE_FIND_MAXIMUM *
1250             (GST_MP3_TYPEFIND_TRY_SYNC - skipped) /
1251             GST_MP3_TYPEFIND_TRY_HEADERS / GST_MP3_TYPEFIND_TRY_SYNC;
1252
1253         if (!headerstart
1254             && probability > (GST_TYPE_FIND_MINIMUM + GST_MP3_WRONG_HEADER))
1255           probability -= GST_MP3_WRONG_HEADER;
1256         if (probability < GST_TYPE_FIND_MINIMUM)
1257           probability = GST_TYPE_FIND_MINIMUM;
1258         if (start_off > 0)
1259           probability /= 2;
1260         if (!changed)
1261           probability = (probability + GST_TYPE_FIND_MAXIMUM) / 2;
1262
1263         GST_INFO
1264             ("audio/mpeg calculated %u  =  %u  *  %u / %u  *  (%u - %"
1265             G_GUINT64_FORMAT ") / %u", probability, GST_TYPE_FIND_MAXIMUM,
1266             found, GST_MP3_TYPEFIND_TRY_HEADERS, GST_MP3_TYPEFIND_TRY_SYNC,
1267             (guint64) skipped, GST_MP3_TYPEFIND_TRY_SYNC);
1268         /* make sure we're not id3 tagged */
1269         head_data = gst_type_find_peek (tf, -128, 3);
1270         if (head_data && (memcmp (head_data, "TAG", 3) == 0)) {
1271           probability = 0;
1272         }
1273         g_assert (probability <= GST_TYPE_FIND_MAXIMUM);
1274
1275         *found_prob = probability;
1276         if (probability > 0)
1277           *found_layer = layer;
1278         return;
1279       }
1280     }
1281     data++;
1282     skipped++;
1283     size--;
1284   }
1285 }
1286
1287 static void
1288 mp3_type_find (GstTypeFind * tf, gpointer unused)
1289 {
1290   GstTypeFindProbability prob, mid_prob;
1291   const guint8 *data;
1292   guint layer, mid_layer;
1293   guint64 length;
1294
1295   mp3_type_find_at_offset (tf, 0, &layer, &prob);
1296   length = gst_type_find_get_length (tf);
1297
1298   if (length == 0 || length == (guint64) - 1) {
1299     if (prob != 0)
1300       goto suggest;
1301     return;
1302   }
1303
1304   /* if we're pretty certain already, skip the additional check */
1305   if (prob >= GST_TYPE_FIND_LIKELY)
1306     goto suggest;
1307
1308   mp3_type_find_at_offset (tf, length / 2, &mid_layer, &mid_prob);
1309
1310   if (mid_prob > 0) {
1311     if (prob == 0) {
1312       GST_LOG ("detected audio/mpeg only in the middle (p=%u)", mid_prob);
1313       layer = mid_layer;
1314       prob = mid_prob;
1315       goto suggest;
1316     }
1317
1318     if (layer != mid_layer) {
1319       GST_WARNING ("audio/mpeg layer discrepancy: %u vs. %u", layer, mid_layer);
1320       return;                   /* FIXME: or should we just go with the one in the middle? */
1321     }
1322
1323     /* detected mpeg audio both in middle of the file and at the start */
1324     prob = (prob + mid_prob) / 2;
1325     goto suggest;
1326   }
1327
1328   /* let's see if there's a valid header right at the start */
1329   data = gst_type_find_peek (tf, 0, 4); /* use min. frame size? */
1330   if (data && mp3_type_frame_length_from_header (GST_READ_UINT32_BE (data),
1331           &layer, NULL, NULL, NULL, NULL, 0) != 0) {
1332     if (prob == 0)
1333       prob = GST_TYPE_FIND_POSSIBLE - 10;
1334     else
1335       prob = MAX (GST_TYPE_FIND_POSSIBLE - 10, prob + 10);
1336   }
1337
1338   if (prob > 0)
1339     goto suggest;
1340
1341   return;
1342
1343 suggest:
1344   {
1345     g_return_if_fail (layer >= 1 && layer <= 3);
1346
1347     gst_type_find_suggest_simple (tf, prob, "audio/mpeg",
1348         "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
1349   }
1350 }
1351
1352 /*** audio/x-musepack ***/
1353
1354 static GstStaticCaps musepack_caps =
1355 GST_STATIC_CAPS ("audio/x-musepack, streamversion= (int) { 7, 8 }");
1356
1357 #define MUSEPACK_CAPS (gst_static_caps_get(&musepack_caps))
1358 static void
1359 musepack_type_find (GstTypeFind * tf, gpointer unused)
1360 {
1361   const guint8 *data = gst_type_find_peek (tf, 0, 4);
1362   GstTypeFindProbability prop = GST_TYPE_FIND_MINIMUM;
1363   gint streamversion = -1;
1364
1365   if (data && memcmp (data, "MP+", 3) == 0) {
1366     streamversion = 7;
1367     if ((data[3] & 0x7f) == 7) {
1368       prop = GST_TYPE_FIND_MAXIMUM;
1369     } else {
1370       prop = GST_TYPE_FIND_LIKELY + 10;
1371     }
1372   } else if (data && memcmp (data, "MPCK", 4) == 0) {
1373     streamversion = 8;
1374     prop = GST_TYPE_FIND_MAXIMUM;
1375   }
1376
1377   if (streamversion != -1) {
1378     gst_type_find_suggest_simple (tf, prop, "audio/x-musepack",
1379         "streamversion", G_TYPE_INT, streamversion, NULL);
1380   }
1381 }
1382
1383 /*** audio/x-ac3 ***/
1384 /* FIXME 0.11: should be audio/ac3, but isn't for backwards compatibility */
1385 static GstStaticCaps ac3_caps = GST_STATIC_CAPS ("audio/x-ac3");
1386
1387 #define AC3_CAPS (gst_static_caps_get(&ac3_caps))
1388
1389 static GstStaticCaps eac3_caps = GST_STATIC_CAPS ("audio/x-eac3");
1390
1391 #define EAC3_CAPS (gst_static_caps_get(&eac3_caps))
1392
1393 struct ac3_frmsize
1394 {
1395   unsigned short bit_rate;
1396   unsigned short frm_size[3];
1397 };
1398
1399 static const struct ac3_frmsize ac3_frmsizecod_tbl[] = {
1400   {32, {64, 69, 96}},
1401   {32, {64, 70, 96}},
1402   {40, {80, 87, 120}},
1403   {40, {80, 88, 120}},
1404   {48, {96, 104, 144}},
1405   {48, {96, 105, 144}},
1406   {56, {112, 121, 168}},
1407   {56, {112, 122, 168}},
1408   {64, {128, 139, 192}},
1409   {64, {128, 140, 192}},
1410   {80, {160, 174, 240}},
1411   {80, {160, 175, 240}},
1412   {96, {192, 208, 288}},
1413   {96, {192, 209, 288}},
1414   {112, {224, 243, 336}},
1415   {112, {224, 244, 336}},
1416   {128, {256, 278, 384}},
1417   {128, {256, 279, 384}},
1418   {160, {320, 348, 480}},
1419   {160, {320, 349, 480}},
1420   {192, {384, 417, 576}},
1421   {192, {384, 418, 576}},
1422   {224, {448, 487, 672}},
1423   {224, {448, 488, 672}},
1424   {256, {512, 557, 768}},
1425   {256, {512, 558, 768}},
1426   {320, {640, 696, 960}},
1427   {320, {640, 697, 960}},
1428   {384, {768, 835, 1152}},
1429   {384, {768, 836, 1152}},
1430   {448, {896, 975, 1344}},
1431   {448, {896, 976, 1344}},
1432   {512, {1024, 1114, 1536}},
1433   {512, {1024, 1115, 1536}},
1434   {576, {1152, 1253, 1728}},
1435   {576, {1152, 1254, 1728}},
1436   {640, {1280, 1393, 1920}},
1437   {640, {1280, 1394, 1920}}
1438 };
1439
1440 static void
1441 ac3_type_find (GstTypeFind * tf, gpointer unused)
1442 {
1443   DataScanCtx c = { 0, NULL, 0 };
1444
1445   /* Search for an ac3 frame; not necessarily right at the start, but give it
1446    * a lower probability if not found right at the start. Check that the
1447    * frame is followed by a second frame at the expected offset.
1448    * We could also check the two ac3 CRCs, but we don't do that right now */
1449   while (c.offset < 1024) {
1450     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 5)))
1451       break;
1452
1453     if (c.data[0] == 0x0b && c.data[1] == 0x77) {
1454       guint bsid = c.data[5] >> 3;
1455
1456       if (bsid <= 8) {
1457         /* ac3 */
1458         guint fscod = c.data[4] >> 6;
1459         guint frmsizecod = c.data[4] & 0x3f;
1460
1461         if (fscod < 3 && frmsizecod < 38) {
1462           DataScanCtx c_next = c;
1463           guint frame_size;
1464
1465           frame_size = ac3_frmsizecod_tbl[frmsizecod].frm_size[fscod];
1466           GST_LOG ("possible AC3 frame sync at offset %"
1467               G_GUINT64_FORMAT ", size=%u", c.offset, frame_size);
1468           if (data_scan_ctx_ensure_data (tf, &c_next, (frame_size * 2) + 5)) {
1469             data_scan_ctx_advance (tf, &c_next, frame_size * 2);
1470
1471             if (c_next.data[0] == 0x0b && c_next.data[1] == 0x77) {
1472               fscod = c_next.data[4] >> 6;
1473               frmsizecod = c_next.data[4] & 0x3f;
1474
1475               if (fscod < 3 && frmsizecod < 38) {
1476                 GstTypeFindProbability prob;
1477
1478                 GST_LOG ("found second AC3 frame (size=%u), looks good",
1479                     ac3_frmsizecod_tbl[frmsizecod].frm_size[fscod]);
1480                 if (c.offset == 0)
1481                   prob = GST_TYPE_FIND_MAXIMUM;
1482                 else
1483                   prob = GST_TYPE_FIND_NEARLY_CERTAIN;
1484
1485                 gst_type_find_suggest (tf, prob, AC3_CAPS);
1486                 return;
1487               }
1488             } else {
1489               GST_LOG ("no second AC3 frame found, false sync");
1490             }
1491           }
1492         }
1493       } else if (bsid <= 16 && bsid > 10) {
1494         /* eac3 */
1495         DataScanCtx c_next = c;
1496         guint frame_size;
1497
1498         frame_size = (((c.data[2] & 0x07) << 8) + c.data[3]) + 1;
1499         GST_LOG ("possible E-AC3 frame sync at offset %"
1500             G_GUINT64_FORMAT ", size=%u", c.offset, frame_size);
1501         if (data_scan_ctx_ensure_data (tf, &c_next, (frame_size * 2) + 5)) {
1502           data_scan_ctx_advance (tf, &c_next, frame_size * 2);
1503
1504           if (c_next.data[0] == 0x0b && c_next.data[1] == 0x77) {
1505             GstTypeFindProbability prob;
1506
1507             GST_LOG ("found second E-AC3 frame, looks good");
1508             if (c.offset == 0)
1509               prob = GST_TYPE_FIND_MAXIMUM;
1510             else
1511               prob = GST_TYPE_FIND_NEARLY_CERTAIN;
1512
1513             gst_type_find_suggest (tf, prob, EAC3_CAPS);
1514             return;
1515           } else {
1516             GST_LOG ("no second E-AC3 frame found, false sync");
1517           }
1518         }
1519       } else {
1520         GST_LOG ("invalid AC3 BSID: %u", bsid);
1521       }
1522     }
1523     data_scan_ctx_advance (tf, &c, 1);
1524   }
1525 }
1526
1527 /*** audio/x-dts ***/
1528 static GstStaticCaps dts_caps = GST_STATIC_CAPS ("audio/x-dts");
1529 #define DTS_CAPS (gst_static_caps_get (&dts_caps))
1530 #define DTS_MIN_FRAMESIZE 96
1531 #define DTS_MAX_FRAMESIZE 18725 /* 16384*16/14 */
1532
1533 static gboolean
1534 dts_parse_frame_header (DataScanCtx * c, guint * frame_size,
1535     guint * sample_rate, guint * channels, guint * depth, guint * endianness)
1536 {
1537   static const int sample_rates[16] = { 0, 8000, 16000, 32000, 0, 0, 11025,
1538     22050, 44100, 0, 0, 12000, 24000, 48000, 96000, 192000
1539   };
1540   static const guint8 channels_table[16] = { 1, 2, 2, 2, 2, 3, 3, 4, 4, 5,
1541     6, 6, 6, 7, 8, 8
1542   };
1543   guint16 hdr[8];
1544   guint32 marker;
1545   guint num_blocks, chans, lfe, i;
1546
1547   marker = GST_READ_UINT32_BE (c->data);
1548
1549   /* raw big endian or 14-bit big endian */
1550   if (marker == 0x7FFE8001 || marker == 0x1FFFE800) {
1551     *endianness = G_BIG_ENDIAN;
1552     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
1553       hdr[i] = GST_READ_UINT16_BE (c->data + (i * sizeof (guint16)));
1554   } else
1555     /* raw little endian or 14-bit little endian */
1556   if (marker == 0xFE7F0180 || marker == 0xFF1F00E8) {
1557     *endianness = G_LITTLE_ENDIAN;
1558     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
1559       hdr[i] = GST_READ_UINT16_LE (c->data + (i * sizeof (guint16)));
1560   } else {
1561     return FALSE;
1562   }
1563
1564   GST_LOG ("dts sync marker 0x%08x at offset %u", marker, (guint) c->offset);
1565
1566   /* 14-bit mode */
1567   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8) {
1568     if ((hdr[2] & 0xFFF0) != 0x07F0)
1569       return FALSE;
1570     /* discard top 2 bits (2 void), shift in 2 */
1571     hdr[0] = (hdr[0] << 2) | ((hdr[1] >> 12) & 0x0003);
1572     /* discard top 4 bits (2 void, 2 shifted into hdr[0]), shift in 4 etc. */
1573     hdr[1] = (hdr[1] << 4) | ((hdr[2] >> 10) & 0x000F);
1574     hdr[2] = (hdr[2] << 6) | ((hdr[3] >> 8) & 0x003F);
1575     hdr[3] = (hdr[3] << 8) | ((hdr[4] >> 6) & 0x00FF);
1576     hdr[4] = (hdr[4] << 10) | ((hdr[5] >> 4) & 0x03FF);
1577     hdr[5] = (hdr[5] << 12) | ((hdr[6] >> 2) & 0x0FFF);
1578     hdr[6] = (hdr[6] << 14) | ((hdr[7] >> 0) & 0x3FFF);
1579     g_assert (hdr[0] == 0x7FFE && hdr[1] == 0x8001);
1580     *depth = 14;
1581   } else {
1582     *depth = 16;
1583   }
1584
1585   GST_LOG ("frame header: %04x%04x%04x%04x", hdr[2], hdr[3], hdr[4], hdr[5]);
1586
1587   num_blocks = (hdr[2] >> 2) & 0x7F;
1588   *frame_size = (((hdr[2] & 0x03) << 12) | (hdr[3] >> 4)) + 1;
1589   chans = ((hdr[3] & 0x0F) << 2) | (hdr[4] >> 14);
1590   *sample_rate = sample_rates[(hdr[4] >> 10) & 0x0F];
1591   lfe = (hdr[5] >> 9) & 0x03;
1592
1593   if (num_blocks < 5 || *frame_size < 96 || *sample_rate == 0)
1594     return FALSE;
1595
1596   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8)
1597     *frame_size = (*frame_size * 16) / 14;      /* FIXME: round up? */
1598
1599   if (chans < G_N_ELEMENTS (channels_table))
1600     *channels = channels_table[chans] + ((lfe) ? 1 : 0);
1601   else
1602     *channels = 0;
1603
1604   return TRUE;
1605 }
1606
1607 static void
1608 dts_type_find (GstTypeFind * tf, gpointer unused)
1609 {
1610   DataScanCtx c = { 0, NULL, 0 };
1611
1612   /* Search for an dts frame; not necessarily right at the start, but give it
1613    * a lower probability if not found right at the start. Check that the
1614    * frame is followed by a second frame at the expected offset. */
1615   while (c.offset <= DTS_MAX_FRAMESIZE) {
1616     guint frame_size = 0, rate = 0, chans = 0, depth = 0, endianness = 0;
1617
1618     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, DTS_MIN_FRAMESIZE)))
1619       return;
1620
1621     if (G_UNLIKELY (dts_parse_frame_header (&c, &frame_size, &rate, &chans,
1622                 &depth, &endianness))) {
1623       GstTypeFindProbability prob;
1624       DataScanCtx next_c;
1625
1626       prob = (c.offset == 0) ? GST_TYPE_FIND_LIKELY : GST_TYPE_FIND_POSSIBLE;
1627
1628       /* check for second frame sync */
1629       next_c = c;
1630       data_scan_ctx_advance (tf, &next_c, frame_size);
1631       if (data_scan_ctx_ensure_data (tf, &next_c, 4)) {
1632         GST_LOG ("frame size: %u 0x%04x", frame_size, frame_size);
1633         GST_MEMDUMP ("second frame sync", next_c.data, 4);
1634         if (GST_READ_UINT32_BE (c.data) == GST_READ_UINT32_BE (next_c.data))
1635           prob = GST_TYPE_FIND_MAXIMUM;
1636       }
1637
1638       if (chans > 0) {
1639         gst_type_find_suggest_simple (tf, prob, "audio/x-dts",
1640             "rate", G_TYPE_INT, rate, "channels", G_TYPE_INT, chans,
1641             "depth", G_TYPE_INT, depth, "endianness", G_TYPE_INT, endianness,
1642             "framed", G_TYPE_BOOLEAN, FALSE, NULL);
1643       } else {
1644         gst_type_find_suggest_simple (tf, prob, "audio/x-dts",
1645             "rate", G_TYPE_INT, rate, "depth", G_TYPE_INT, depth,
1646             "endianness", G_TYPE_INT, endianness,
1647             "framed", G_TYPE_BOOLEAN, FALSE, NULL);
1648       }
1649
1650       return;
1651     }
1652
1653     data_scan_ctx_advance (tf, &c, 1);
1654   }
1655 }
1656
1657 /*** gsm ***/
1658
1659 /* can only be detected by using the extension, in which case we use the default
1660  * GSM properties */
1661 static GstStaticCaps gsm_caps =
1662 GST_STATIC_CAPS ("audio/x-gsm, rate=8000, channels=1");
1663
1664 #define GSM_CAPS (gst_static_caps_get(&gsm_caps))
1665
1666 /*** wavpack ***/
1667
1668 static GstStaticCaps wavpack_caps =
1669 GST_STATIC_CAPS ("audio/x-wavpack, framed = (boolean) false");
1670
1671 #define WAVPACK_CAPS (gst_static_caps_get(&wavpack_caps))
1672
1673 static GstStaticCaps wavpack_correction_caps =
1674 GST_STATIC_CAPS ("audio/x-wavpack-correction, framed = (boolean) false");
1675
1676 #define WAVPACK_CORRECTION_CAPS (gst_static_caps_get(&wavpack_correction_caps))
1677
1678 static void
1679 wavpack_type_find (GstTypeFind * tf, gpointer unused)
1680 {
1681   guint64 offset;
1682   guint32 blocksize;
1683   const guint8 *data;
1684
1685   data = gst_type_find_peek (tf, 0, 32);
1686   if (!data)
1687     return;
1688
1689   if (data[0] != 'w' || data[1] != 'v' || data[2] != 'p' || data[3] != 'k')
1690     return;
1691
1692   /* Note: wavpack blocks can be fairly large (easily 60-110k), possibly
1693    * larger than the max. limits imposed by certain typefinding elements
1694    * like id3demux or apedemux, so typefinding is most likely only going to
1695    * work in pull-mode */
1696   blocksize = GST_READ_UINT32_LE (data + 4);
1697   GST_LOG ("wavpack header, blocksize=0x%04x", blocksize);
1698   offset = 32;
1699   while (offset < 32 + blocksize) {
1700     guint32 sublen;
1701
1702     /* get chunk header */
1703     GST_LOG ("peeking at chunk at offset 0x%04x", (guint) offset);
1704     data = gst_type_find_peek (tf, offset, 4);
1705     if (data == NULL)
1706       break;
1707     sublen = ((guint32) data[1]) << 1;
1708     if (data[0] & 0x80) {
1709       sublen |= (((guint32) data[2]) << 9) | (((guint32) data[3]) << 17);
1710       sublen += 1 + 3;          /* id + length */
1711     } else {
1712       sublen += 1 + 1;          /* id + length */
1713     }
1714     if (sublen > blocksize - offset + 32) {
1715       GST_LOG ("chunk length too big (%u > %" G_GUINT64_FORMAT ")", sublen,
1716           blocksize - offset);
1717       break;
1718     }
1719     if ((data[0] & 0x20) == 0) {
1720       switch (data[0] & 0x0f) {
1721         case 0xa:              /* ID_WV_BITSTREAM  */
1722         case 0xc:              /* ID_WVX_BITSTREAM */
1723           gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, WAVPACK_CAPS);
1724           return;
1725         case 0xb:              /* ID_WVC_BITSTREAM */
1726           gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY,
1727               WAVPACK_CORRECTION_CAPS);
1728           return;
1729         default:
1730           break;
1731       }
1732     }
1733     offset += sublen;
1734   }
1735 }
1736
1737 /*** application/postscrip ***/
1738 static GstStaticCaps postscript_caps =
1739 GST_STATIC_CAPS ("application/postscript");
1740
1741 #define POSTSCRIPT_CAPS (gst_static_caps_get(&postscript_caps))
1742
1743 static void
1744 postscript_type_find (GstTypeFind * tf, gpointer unused)
1745 {
1746   const guint8 *data = gst_type_find_peek (tf, 0, 3);
1747   if (!data)
1748     return;
1749
1750   if (data[0] == 0x04)
1751     data++;
1752   if (data[0] == '%' && data[1] == '!')
1753     gst_type_find_suggest (tf, GST_TYPE_FIND_POSSIBLE, POSTSCRIPT_CAPS);
1754
1755 }
1756
1757 /*** image/svg+xml ***/
1758 static GstStaticCaps svg_caps = GST_STATIC_CAPS ("image/svg+xml");
1759
1760 #define SVG_CAPS (gst_static_caps_get(&svg_caps))
1761
1762 static void
1763 svg_type_find (GstTypeFind * tf, gpointer unused)
1764 {
1765   static const gchar svg_doctype[] = "!DOCTYPE svg";
1766   static const gchar svg_tag[] = "<svg";
1767   DataScanCtx c = { 0, NULL, 0 };
1768
1769   while (c.offset <= 1024) {
1770     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 12)))
1771       break;
1772
1773     if (memcmp (svg_doctype, c.data, 12) == 0) {
1774       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SVG_CAPS);
1775       return;
1776     } else if (memcmp (svg_tag, c.data, 4) == 0) {
1777       gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, SVG_CAPS);
1778       return;
1779     }
1780     data_scan_ctx_advance (tf, &c, 1);
1781   }
1782 }
1783
1784 /*** multipart/x-mixed-replace mimestream ***/
1785
1786 static GstStaticCaps multipart_caps =
1787 GST_STATIC_CAPS ("multipart/x-mixed-replace");
1788 #define MULTIPART_CAPS gst_static_caps_get(&multipart_caps)
1789
1790 /* multipart/x-mixed replace is: 
1791  *   <maybe some whitespace>--<some ascii chars>[\r]\n
1792  *   <more ascii chars>[\r]\nContent-type:<more ascii>[\r]\n */
1793 static void
1794 multipart_type_find (GstTypeFind * tf, gpointer unused)
1795 {
1796   const guint8 *data;
1797   const guint8 *x;
1798
1799 #define MULTIPART_MAX_BOUNDARY_OFFSET 16
1800   data = gst_type_find_peek (tf, 0, MULTIPART_MAX_BOUNDARY_OFFSET);
1801   if (!data)
1802     return;
1803
1804   for (x = data;
1805       x - data < MULTIPART_MAX_BOUNDARY_OFFSET - 2 && g_ascii_isspace (*x);
1806       x++);
1807   if (x[0] != '-' || x[1] != '-')
1808     return;
1809
1810   /* Could be okay, peek what should be enough for a complete header */
1811 #define MULTIPART_MAX_HEADER_SIZE 256
1812   data = gst_type_find_peek (tf, 0, MULTIPART_MAX_HEADER_SIZE);
1813   if (!data)
1814     return;
1815
1816   for (x = data; x - data < MULTIPART_MAX_HEADER_SIZE - 14; x++) {
1817     if (!isascii (*x)) {
1818       return;
1819     }
1820     if (*x == '\n' &&
1821         !g_ascii_strncasecmp ("content-type:", (gchar *) x + 1, 13)) {
1822       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MULTIPART_CAPS);
1823       return;
1824     }
1825   }
1826 }
1827
1828 /*** video/mpeg systemstream ***/
1829 static GstStaticCaps mpeg_sys_caps = GST_STATIC_CAPS ("video/mpeg, "
1830     "systemstream = (boolean) true, mpegversion = (int) [ 1, 2 ]");
1831
1832 #define MPEG_SYS_CAPS gst_static_caps_get(&mpeg_sys_caps)
1833 #define IS_MPEG_HEADER(data) (G_UNLIKELY((((guint8 *)(data))[0] == 0x00) &&  \
1834                                          (((guint8 *)(data))[1] == 0x00) &&  \
1835                                          (((guint8 *)(data))[2] == 0x01)))
1836
1837 #define IS_MPEG_PACK_CODE(b) ((b) == 0xBA)
1838 #define IS_MPEG_SYS_CODE(b) ((b) == 0xBB)
1839 #define IS_MPEG_PACK_HEADER(data)       (IS_MPEG_HEADER (data) &&            \
1840                                          IS_MPEG_PACK_CODE (((guint8 *)(data))[3]))
1841
1842 #define IS_MPEG_PES_CODE(b) (((b) & 0xF0) == 0xE0 || ((b) & 0xF0) == 0xC0 || \
1843                              (b) >= 0xBD)
1844 #define IS_MPEG_PES_HEADER(data)        (IS_MPEG_HEADER (data) &&            \
1845                                          IS_MPEG_PES_CODE (((guint8 *)(data))[3]))
1846
1847 #define MPEG2_MAX_PROBE_LENGTH (128 * 1024)     /* 128kB should be 64 packs of the 
1848                                                  * most common 2kB pack size. */
1849
1850 #define MPEG2_MIN_SYS_HEADERS 2
1851 #define MPEG2_MAX_SYS_HEADERS 5
1852
1853 static gboolean
1854 mpeg_sys_is_valid_pack (GstTypeFind * tf, const guint8 * data, guint len,
1855     guint * pack_size)
1856 {
1857   /* Check the pack header @ offset for validity, assuming that the 4 byte header
1858    * itself has already been checked. */
1859   guint8 stuff_len;
1860
1861   if (len < 12)
1862     return FALSE;
1863
1864   /* Check marker bits */
1865   if ((data[4] & 0xC4) == 0x44) {
1866     /* MPEG-2 PACK */
1867     if (len < 14)
1868       return FALSE;
1869
1870     if ((data[6] & 0x04) != 0x04 ||
1871         (data[8] & 0x04) != 0x04 ||
1872         (data[9] & 0x01) != 0x01 || (data[12] & 0x03) != 0x03)
1873       return FALSE;
1874
1875     stuff_len = data[13] & 0x07;
1876
1877     /* Check the following header bytes, if we can */
1878     if ((14 + stuff_len + 4) <= len) {
1879       if (!IS_MPEG_HEADER (data + 14 + stuff_len))
1880         return FALSE;
1881     }
1882     if (pack_size)
1883       *pack_size = 14 + stuff_len;
1884     return TRUE;
1885   } else if ((data[4] & 0xF1) == 0x21) {
1886     /* MPEG-1 PACK */
1887     if ((data[6] & 0x01) != 0x01 ||
1888         (data[8] & 0x01) != 0x01 ||
1889         (data[9] & 0x80) != 0x80 || (data[11] & 0x01) != 0x01)
1890       return FALSE;
1891
1892     /* Check the following header bytes, if we can */
1893     if ((12 + 4) <= len) {
1894       if (!IS_MPEG_HEADER (data + 12))
1895         return FALSE;
1896     }
1897     if (pack_size)
1898       *pack_size = 12;
1899     return TRUE;
1900   }
1901
1902   return FALSE;
1903 }
1904
1905 static gboolean
1906 mpeg_sys_is_valid_pes (GstTypeFind * tf, const guint8 * data, guint len,
1907     guint * pack_size)
1908 {
1909   guint pes_packet_len;
1910
1911   /* Check the PES header at the given position, assuming the header code itself
1912    * was already checked */
1913   if (len < 6)
1914     return FALSE;
1915
1916   /* For MPEG Program streams, unbounded PES is not allowed, so we must have a
1917    * valid length present */
1918   pes_packet_len = GST_READ_UINT16_BE (data + 4);
1919   if (pes_packet_len == 0)
1920     return FALSE;
1921
1922   /* Check the following header, if we can */
1923   if (6 + pes_packet_len + 4 <= len) {
1924     if (!IS_MPEG_HEADER (data + 6 + pes_packet_len))
1925       return FALSE;
1926   }
1927
1928   if (pack_size)
1929     *pack_size = 6 + pes_packet_len;
1930   return TRUE;
1931 }
1932
1933 static gboolean
1934 mpeg_sys_is_valid_sys (GstTypeFind * tf, const guint8 * data, guint len,
1935     guint * pack_size)
1936 {
1937   guint sys_hdr_len;
1938
1939   /* Check the System header at the given position, assuming the header code itself
1940    * was already checked */
1941   if (len < 6)
1942     return FALSE;
1943   sys_hdr_len = GST_READ_UINT16_BE (data + 4);
1944   if (sys_hdr_len < 6)
1945     return FALSE;
1946
1947   /* Check the following header, if we can */
1948   if (6 + sys_hdr_len + 4 <= len) {
1949     if (!IS_MPEG_HEADER (data + 6 + sys_hdr_len))
1950       return FALSE;
1951   }
1952
1953   if (pack_size)
1954     *pack_size = 6 + sys_hdr_len;
1955
1956   return TRUE;
1957 }
1958
1959 /* calculation of possibility to identify random data as mpeg systemstream:
1960  * bits that must match in header detection:            32 (or more)
1961  * chance that random data is identifed:                1/2^32
1962  * chance that MPEG2_MIN_PACK_HEADERS headers are identified:
1963  *       1/2^(32*MPEG2_MIN_PACK_HEADERS)
1964  * chance that this happens in MPEG2_MAX_PROBE_LENGTH bytes:
1965  *       1-(1+1/2^(32*MPEG2_MIN_PACK_HEADERS)^MPEG2_MAX_PROBE_LENGTH)
1966  * for current values:
1967  *       1-(1+1/2^(32*4)^101024)
1968  *       = <some_number>
1969  * Since we also check marker bits and pes packet lengths, this probability is a
1970  * very coarse upper bound.
1971  */
1972 static void
1973 mpeg_sys_type_find (GstTypeFind * tf, gpointer unused)
1974 {
1975   const guint8 *data, *data0, *first_sync, *end;
1976   gint mpegversion = 0;
1977   guint pack_headers = 0;
1978   guint pes_headers = 0;
1979   guint pack_size;
1980   guint since_last_sync = 0;
1981   guint32 sync_word = 0xffffffff;
1982
1983   G_STMT_START {
1984     gint len;
1985
1986     len = MPEG2_MAX_PROBE_LENGTH;
1987     do {
1988       len = len / 2;
1989       data = gst_type_find_peek (tf, 0, 5 + len);
1990     } while (data == NULL && len >= 32);
1991
1992     if (!data)
1993       return;
1994
1995     end = data + len;
1996   }
1997   G_STMT_END;
1998
1999   data0 = data;
2000   first_sync = NULL;
2001
2002   while (data < end) {
2003     sync_word <<= 8;
2004     if (sync_word == 0x00000100) {
2005       /* Found potential sync word */
2006       if (first_sync == NULL)
2007         first_sync = data - 3;
2008
2009       if (since_last_sync > 4) {
2010         /* If more than 4 bytes since the last sync word, reset our counters,
2011          * as we're only interested in counting contiguous packets */
2012         pes_headers = pack_headers = 0;
2013       }
2014       pack_size = 0;
2015
2016       if (IS_MPEG_PACK_CODE (data[0])) {
2017         if ((data[1] & 0xC0) == 0x40) {
2018           /* MPEG-2 */
2019           mpegversion = 2;
2020         } else if ((data[1] & 0xF0) == 0x20) {
2021           mpegversion = 1;
2022         }
2023         if (mpegversion != 0 &&
2024             mpeg_sys_is_valid_pack (tf, data - 3, end - data + 3, &pack_size)) {
2025           pack_headers++;
2026         }
2027       } else if (IS_MPEG_PES_CODE (data[0])) {
2028         /* PES stream */
2029         if (mpeg_sys_is_valid_pes (tf, data - 3, end - data + 3, &pack_size)) {
2030           pes_headers++;
2031           if (mpegversion == 0)
2032             mpegversion = 2;
2033         }
2034       } else if (IS_MPEG_SYS_CODE (data[0])) {
2035         if (mpeg_sys_is_valid_sys (tf, data - 3, end - data + 3, &pack_size)) {
2036           pack_headers++;
2037         }
2038       }
2039
2040       /* If we found a packet with a known size, skip the bytes in it and loop
2041        * around to check the next packet. */
2042       if (pack_size != 0) {
2043         data += pack_size - 3;
2044         sync_word = 0xffffffff;
2045         since_last_sync = 0;
2046         continue;
2047       }
2048     }
2049
2050     sync_word |= data[0];
2051     since_last_sync++;
2052     data++;
2053
2054     /* If we have found MAX headers, and *some* were pes headers (pack headers
2055      * are optional in an mpeg system stream) then return our high-probability
2056      * result */
2057     if (pes_headers > 0 && (pack_headers + pes_headers) > MPEG2_MAX_SYS_HEADERS)
2058       goto suggest;
2059   }
2060
2061   /* If we at least saw MIN headers, and *some* were pes headers (pack headers
2062    * are optional in an mpeg system stream) then return a lower-probability 
2063    * result */
2064   if (pes_headers > 0 && (pack_headers + pes_headers) > MPEG2_MIN_SYS_HEADERS)
2065     goto suggest;
2066
2067   return;
2068 suggest:
2069   {
2070     guint prob;
2071
2072     prob = GST_TYPE_FIND_POSSIBLE + (10 * (pack_headers + pes_headers));
2073     prob = MIN (prob, GST_TYPE_FIND_MAXIMUM);
2074
2075     /* lower probability if the first packet wasn't right at the start */
2076     if (data0 != first_sync && prob >= 10)
2077       prob -= 10;
2078
2079     GST_LOG ("Suggesting MPEG %d system stream, %d packs, %d pes, prob %u%%\n",
2080         mpegversion, pack_headers, pes_headers, prob);
2081
2082     gst_type_find_suggest_simple (tf, prob, "video/mpeg",
2083         "systemstream", G_TYPE_BOOLEAN, TRUE,
2084         "mpegversion", G_TYPE_INT, mpegversion, NULL);
2085   }
2086 };
2087
2088 /*** video/mpegts Transport Stream ***/
2089 static GstStaticCaps mpegts_caps = GST_STATIC_CAPS ("video/mpegts, "
2090     "systemstream = (boolean) true, packetsize = (int) [ 188, 208 ]");
2091 #define MPEGTS_CAPS gst_static_caps_get(&mpegts_caps)
2092
2093 #define GST_MPEGTS_TYPEFIND_MIN_HEADERS 4
2094 #define GST_MPEGTS_TYPEFIND_MAX_HEADERS 10
2095 #define GST_MPEGTS_MAX_PACKET_SIZE 208
2096 #define GST_MPEGTS_TYPEFIND_SYNC_SIZE \
2097             (GST_MPEGTS_TYPEFIND_MIN_HEADERS * GST_MPEGTS_MAX_PACKET_SIZE)
2098 #define GST_MPEGTS_TYPEFIND_MAX_SYNC \
2099             (GST_MPEGTS_TYPEFIND_MAX_HEADERS * GST_MPEGTS_MAX_PACKET_SIZE)
2100 #define GST_MPEGTS_TYPEFIND_SCAN_LENGTH \
2101             (GST_MPEGTS_TYPEFIND_MAX_SYNC * 4)
2102
2103 #define MPEGTS_HDR_SIZE 4
2104 /* Check for sync byte, error_indicator == 0 and packet has payload */
2105 #define IS_MPEGTS_HEADER(data) (((data)[0] == 0x47) && \
2106                                 (((data)[1] & 0x80) == 0x00) && \
2107                                 (((data)[3] & 0x30) != 0x00))
2108
2109 /* Helper function to search ahead at intervals of packet_size for mpegts
2110  * headers */
2111 static gint
2112 mpeg_ts_probe_headers (GstTypeFind * tf, guint64 offset, gint packet_size)
2113 {
2114   /* We always enter this function having found at least one header already */
2115   gint found = 1;
2116   const guint8 *data = NULL;
2117
2118   GST_LOG ("looking for mpeg-ts packets of size %u", packet_size);
2119   while (found < GST_MPEGTS_TYPEFIND_MAX_HEADERS) {
2120     offset += packet_size;
2121
2122     data = gst_type_find_peek (tf, offset, MPEGTS_HDR_SIZE);
2123     if (data == NULL || !IS_MPEGTS_HEADER (data))
2124       return found;
2125
2126     found++;
2127     GST_LOG ("mpeg-ts sync #%2d at offset %" G_GUINT64_FORMAT, found, offset);
2128   }
2129
2130   return found;
2131 }
2132
2133 /* Try and detect at least 4 packets in at most 10 packets worth of
2134  * data. Need to try several possible packet sizes */
2135 static void
2136 mpeg_ts_type_find (GstTypeFind * tf, gpointer unused)
2137 {
2138   /* TS packet sizes to test: normal, DVHS packet size and 
2139    * FEC with 16 or 20 byte codes packet size. */
2140   const gint pack_sizes[] = { 188, 192, 204, 208 };
2141   const guint8 *data = NULL;
2142   guint size = 0;
2143   guint64 skipped = 0;
2144
2145   while (skipped < GST_MPEGTS_TYPEFIND_SCAN_LENGTH) {
2146     if (size < MPEGTS_HDR_SIZE) {
2147       data = gst_type_find_peek (tf, skipped, GST_MPEGTS_TYPEFIND_SYNC_SIZE);
2148       if (!data)
2149         break;
2150       size = GST_MPEGTS_TYPEFIND_SYNC_SIZE;
2151     }
2152
2153     /* Have at least MPEGTS_HDR_SIZE bytes at this point */
2154     if (IS_MPEGTS_HEADER (data)) {
2155       gint p;
2156
2157       GST_LOG ("possible mpeg-ts sync at offset %" G_GUINT64_FORMAT, skipped);
2158
2159       for (p = 0; p < G_N_ELEMENTS (pack_sizes); p++) {
2160         gint found;
2161
2162         /* Probe ahead at size pack_sizes[p] */
2163         found = mpeg_ts_probe_headers (tf, skipped, pack_sizes[p]);
2164         if (found >= GST_MPEGTS_TYPEFIND_MIN_HEADERS) {
2165           gint probability;
2166
2167           /* found at least 4 headers. 10 headers = MAXIMUM probability. 
2168            * Arbitrarily, I assigned 10% probability for each header we
2169            * found, 40% -> 100% */
2170           probability = MIN (10 * found, GST_TYPE_FIND_MAXIMUM);
2171
2172           gst_type_find_suggest_simple (tf, probability, "video/mpegts",
2173               "systemstream", G_TYPE_BOOLEAN, TRUE,
2174               "packetsize", G_TYPE_INT, pack_sizes[p], NULL);
2175           return;
2176         }
2177       }
2178     }
2179     data++;
2180     skipped++;
2181     size--;
2182   }
2183 }
2184
2185 #define GST_MPEGVID_TYPEFIND_TRY_PICTURES 6
2186 #define GST_MPEGVID_TYPEFIND_TRY_SYNC (100 * 1024)      /* 100 kB */
2187
2188 /* Scan ahead a maximum of max_extra_offset bytes until the next IS_MPEG_HEADER
2189  * offset.  After the call, offset will be after the 0x000001, i.e. at the 4th
2190  * byte of the MPEG header.  Returns TRUE if a header was found, FALSE if not.
2191  */
2192 static gboolean
2193 mpeg_find_next_header (GstTypeFind * tf, DataScanCtx * c,
2194     guint64 max_extra_offset)
2195 {
2196   guint64 extra_offset;
2197
2198   for (extra_offset = 0; extra_offset <= max_extra_offset; ++extra_offset) {
2199     if (!data_scan_ctx_ensure_data (tf, c, 4))
2200       return FALSE;
2201     if (IS_MPEG_HEADER (c->data)) {
2202       data_scan_ctx_advance (tf, c, 3);
2203       return TRUE;
2204     }
2205     data_scan_ctx_advance (tf, c, 1);
2206   }
2207   return FALSE;
2208 }
2209
2210 /*** video/mpeg MPEG-4 elementary video stream ***/
2211
2212 static GstStaticCaps mpeg4_video_caps = GST_STATIC_CAPS ("video/mpeg, "
2213     "systemstream=(boolean)false, mpegversion=4, parsed=(boolean)false");
2214 #define MPEG4_VIDEO_CAPS gst_static_caps_get(&mpeg4_video_caps)
2215
2216 /*
2217  * This typefind is based on the elementary video header defined in
2218  * http://xhelmboyx.tripod.com/formats/mpeg-layout.txt
2219  * In addition, it allows the visual object sequence header to be
2220  * absent, and even the VOS header to be absent.  In the latter case,
2221  * a number of VOPs have to be present.
2222  */
2223 static void
2224 mpeg4_video_type_find (GstTypeFind * tf, gpointer unused)
2225 {
2226   DataScanCtx c = { 0, NULL, 0 };
2227   gboolean seen_vios_at_0 = FALSE;
2228   gboolean seen_vios = FALSE;
2229   gboolean seen_vos = FALSE;
2230   gboolean seen_vol = FALSE;
2231   guint num_vop_headers = 0;
2232   guint8 sc;
2233
2234   while (c.offset < GST_MPEGVID_TYPEFIND_TRY_SYNC) {
2235     if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES)
2236       break;
2237
2238     if (!mpeg_find_next_header (tf, &c,
2239             GST_MPEGVID_TYPEFIND_TRY_SYNC - c.offset))
2240       break;
2241
2242     sc = c.data[0];
2243
2244     /* visual_object_sequence_start_code */
2245     if (sc == 0xB0) {
2246       if (seen_vios)
2247         break;                  /* Terminate at second vios */
2248       if (c.offset == 0)
2249         seen_vios_at_0 = TRUE;
2250       seen_vios = TRUE;
2251       data_scan_ctx_advance (tf, &c, 2);
2252       if (!mpeg_find_next_header (tf, &c, 0))
2253         break;
2254
2255       sc = c.data[0];
2256
2257       /* Optional metadata */
2258       if (sc == 0xB2)
2259         if (!mpeg_find_next_header (tf, &c, 24))
2260           break;
2261     }
2262
2263     /* visual_object_start_code (consider it optional) */
2264     if (sc == 0xB5) {
2265       data_scan_ctx_advance (tf, &c, 2);
2266       /* may contain ID marker and YUV clamping */
2267       if (!mpeg_find_next_header (tf, &c, 7))
2268         break;
2269
2270       sc = c.data[0];
2271     }
2272
2273     /* video_object_start_code */
2274     if (sc <= 0x1F) {
2275       if (seen_vos)
2276         break;                  /* Terminate at second vos */
2277       seen_vos = TRUE;
2278       data_scan_ctx_advance (tf, &c, 2);
2279       continue;
2280     }
2281
2282     /* video_object_layer_start_code */
2283     if (sc >= 0x20 && sc <= 0x2F) {
2284       seen_vol = TRUE;
2285       data_scan_ctx_advance (tf, &c, 5);
2286       continue;
2287     }
2288
2289     /* video_object_plane_start_code */
2290     if (sc == 0xB6) {
2291       num_vop_headers++;
2292       data_scan_ctx_advance (tf, &c, 2);
2293       continue;
2294     }
2295
2296     /* Unknown start code. */
2297   }
2298
2299   if (num_vop_headers > 0 || seen_vol) {
2300     GstTypeFindProbability probability = 0;
2301
2302     GST_LOG ("Found %d pictures, vios: %d, vos:%d, vol:%d", num_vop_headers,
2303         seen_vios, seen_vos, seen_vol);
2304
2305     if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_vios_at_0
2306         && seen_vos && seen_vol)
2307       probability = GST_TYPE_FIND_MAXIMUM - 1;
2308     else if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_vios
2309         && seen_vos && seen_vol)
2310       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 1;
2311     else if (seen_vios_at_0 && seen_vos && seen_vol)
2312       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 6;
2313     else if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_vos
2314         && seen_vol)
2315       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 6;
2316     else if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_vol)
2317       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 9;
2318     else if (num_vop_headers >= GST_MPEGVID_TYPEFIND_TRY_PICTURES)
2319       probability = GST_TYPE_FIND_LIKELY - 1;
2320     else if (num_vop_headers > 2 && seen_vios && seen_vos && seen_vol)
2321       probability = GST_TYPE_FIND_LIKELY - 9;
2322     else if (seen_vios && seen_vos && seen_vol)
2323       probability = GST_TYPE_FIND_LIKELY - 20;
2324     else if (num_vop_headers > 0 && seen_vos && seen_vol)
2325       probability = GST_TYPE_FIND_POSSIBLE;
2326     else if (num_vop_headers > 0)
2327       probability = GST_TYPE_FIND_POSSIBLE - 10;
2328     else if (seen_vos && seen_vol)
2329       probability = GST_TYPE_FIND_POSSIBLE - 20;
2330
2331     gst_type_find_suggest (tf, probability, MPEG4_VIDEO_CAPS);
2332   }
2333 }
2334
2335 /*** video/x-h263 H263 video stream ***/
2336 static GstStaticCaps h263_video_caps = GST_STATIC_CAPS ("video/x-h263");
2337
2338 #define H263_VIDEO_CAPS gst_static_caps_get(&h263_video_caps)
2339
2340 #define H263_MAX_PROBE_LENGTH (128 * 1024)
2341
2342 static void
2343 h263_video_type_find (GstTypeFind * tf, gpointer unused)
2344 {
2345   DataScanCtx c = { 0, NULL, 0 };
2346   guint64 data = 0;
2347   guint64 psc = 0;
2348   guint8 tr = 0;
2349   guint format;
2350   guint good = 0;
2351   guint bad = 0;
2352
2353   while (c.offset < H263_MAX_PROBE_LENGTH) {
2354     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 4)))
2355       break;
2356
2357     /* Find the picture start code */
2358     data = (data << 8) + c.data[0];
2359     psc = data & G_GUINT64_CONSTANT (0xfffffc0000);
2360     if (psc == 0x800000) {
2361       /* Found PSC */
2362       /* TR */
2363       tr = (data & 0x3fc) >> 2;
2364       /* Source Format */
2365       format = tr & 0x07;
2366
2367       /* Now that we have a Valid PSC, check if we also have a valid PTYPE and
2368          the Source Format, which should range between 1 and 5 */
2369       if (((tr >> 6) == 0x2) && (format > 0 && format < 6))
2370         good++;
2371       else
2372         bad++;
2373
2374       /* FIXME: maybe bail out early if we get mostly bad syncs ? */
2375     }
2376
2377     data_scan_ctx_advance (tf, &c, 1);
2378   }
2379
2380   if (good > 0 && bad == 0)
2381     gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, H263_VIDEO_CAPS);
2382   else if (good > 2 * bad)
2383     gst_type_find_suggest (tf, GST_TYPE_FIND_POSSIBLE, H263_VIDEO_CAPS);
2384
2385   return;
2386 }
2387
2388 /*** video/x-h264 H264 elementary video stream ***/
2389
2390 static GstStaticCaps h264_video_caps =
2391 GST_STATIC_CAPS ("video/x-h264,stream-format=byte-stream");
2392
2393 #define H264_VIDEO_CAPS gst_static_caps_get(&h264_video_caps)
2394
2395 #define H264_MAX_PROBE_LENGTH (128 * 1024)      /* 128kB for HD should be enough. */
2396
2397 static void
2398 h264_video_type_find (GstTypeFind * tf, gpointer unused)
2399 {
2400   DataScanCtx c = { 0, NULL, 0 };
2401
2402   /* Stream consists of: a series of sync codes (00 00 00 01) followed 
2403    * by NALs
2404    */
2405   gboolean seen_idr = FALSE;
2406   gboolean seen_sps = FALSE;
2407   gboolean seen_pps = FALSE;
2408   int nut, ref;
2409   int good = 0;
2410   int bad = 0;
2411
2412   while (c.offset < H264_MAX_PROBE_LENGTH) {
2413     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 4)))
2414       break;
2415
2416     if (IS_MPEG_HEADER (c.data)) {
2417       nut = c.data[3] & 0x9f;   /* forbiden_zero_bit | nal_unit_type */
2418       ref = c.data[3] & 0x60;   /* nal_ref_idc */
2419
2420       /* if forbidden bit is different to 0 won't be h264 */
2421       if (nut > 0x1f) {
2422         bad++;
2423         break;
2424       }
2425
2426       /* collect statistics about the NAL types */
2427       if ((nut >= 1 && nut <= 13) || nut == 19) {
2428         if ((nut == 5 && ref == 0) ||
2429             ((nut == 6 || (nut >= 9 && nut <= 12)) && ref != 0)) {
2430           bad++;
2431         } else {
2432           if (nut == 7)
2433             seen_sps = TRUE;
2434           else if (nut == 8)
2435             seen_pps = TRUE;
2436           else if (nut == 5)
2437             seen_idr = TRUE;
2438
2439           good++;
2440         }
2441       } else if (nut >= 14 && nut <= 33) {
2442         /* reserved */
2443         /* Theoretically these are good, since if they exist in the
2444            stream it merely means that a newer backwards-compatible
2445            h.264 stream.  But we should be identifying that separately. */
2446         bad++;
2447       } else {
2448         /* unspecified, application specific */
2449         /* don't consider these bad */
2450       }
2451
2452       GST_LOG ("good:%d, bad:%d, pps:%d, sps:%d, idr:%d", good, bad, seen_pps,
2453           seen_sps, seen_idr);
2454
2455       if (seen_sps && seen_pps && seen_idr && good >= 10 && bad < 4) {
2456         gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, H264_VIDEO_CAPS);
2457         return;
2458       }
2459
2460       data_scan_ctx_advance (tf, &c, 4);
2461     }
2462     data_scan_ctx_advance (tf, &c, 1);
2463   }
2464
2465   GST_LOG ("good:%d, bad:%d, pps:%d, sps:%d, idr:%d", good, bad, seen_pps,
2466       seen_sps, seen_idr);
2467
2468   if (good >= 2 && bad == 0) {
2469     gst_type_find_suggest (tf, GST_TYPE_FIND_POSSIBLE, H264_VIDEO_CAPS);
2470   }
2471 }
2472
2473 /*** video/mpeg video stream ***/
2474
2475 static GstStaticCaps mpeg_video_caps = GST_STATIC_CAPS ("video/mpeg, "
2476     "systemstream = (boolean) false");
2477 #define MPEG_VIDEO_CAPS gst_static_caps_get(&mpeg_video_caps)
2478
2479 /*
2480  * Idea is the same as MPEG system stream typefinding: We check each
2481  * byte of the stream to see if - from that point on - the stream
2482  * matches a predefined set of marker bits as defined in the MPEG
2483  * video specs.
2484  *
2485  * I'm sure someone will do a chance calculation here too.
2486  */
2487
2488 static void
2489 mpeg_video_stream_type_find (GstTypeFind * tf, gpointer unused)
2490 {
2491   DataScanCtx c = { 0, NULL, 0 };
2492   gboolean seen_seq_at_0 = FALSE;
2493   gboolean seen_seq = FALSE;
2494   gboolean seen_gop = FALSE;
2495   guint64 last_pic_offset = 0;
2496   guint num_pic_headers = 0;
2497   gint found = 0;
2498
2499   while (c.offset < GST_MPEGVID_TYPEFIND_TRY_SYNC) {
2500     if (found >= GST_MPEGVID_TYPEFIND_TRY_PICTURES)
2501       break;
2502
2503     if (!data_scan_ctx_ensure_data (tf, &c, 5))
2504       break;
2505
2506     if (!IS_MPEG_HEADER (c.data))
2507       goto next;
2508
2509     /* a pack header indicates that this isn't an elementary stream */
2510     if (c.data[3] == 0xBA && mpeg_sys_is_valid_pack (tf, c.data, c.size, NULL))
2511       return;
2512
2513     /* do we have a sequence header? */
2514     if (c.data[3] == 0xB3) {
2515       seen_seq_at_0 = seen_seq_at_0 || (c.offset == 0);
2516       seen_seq = TRUE;
2517       data_scan_ctx_advance (tf, &c, 4 + 8);
2518       continue;
2519     }
2520
2521     /* or a GOP header */
2522     if (c.data[3] == 0xB8) {
2523       seen_gop = TRUE;
2524       data_scan_ctx_advance (tf, &c, 8);
2525       continue;
2526     }
2527
2528     /* but what we'd really like to see is a picture header */
2529     if (c.data[3] == 0x00) {
2530       ++num_pic_headers;
2531       last_pic_offset = c.offset;
2532       data_scan_ctx_advance (tf, &c, 8);
2533       continue;
2534     }
2535
2536     /* ... each followed by a slice header with slice_vertical_pos=1 that's
2537      * not too far away from the previously seen picture header. */
2538     if (c.data[3] == 0x01 && num_pic_headers > found &&
2539         (c.offset - last_pic_offset) >= 4 &&
2540         (c.offset - last_pic_offset) <= 64) {
2541       data_scan_ctx_advance (tf, &c, 4);
2542       found += 1;
2543       continue;
2544     }
2545
2546   next:
2547
2548     data_scan_ctx_advance (tf, &c, 1);
2549   }
2550
2551   if (found > 0 || seen_seq) {
2552     GstTypeFindProbability probability = 0;
2553
2554     GST_LOG ("Found %d pictures, seq:%d, gop:%d", found, seen_seq, seen_gop);
2555
2556     if (found >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_seq && seen_gop)
2557       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 1;
2558     else if (found >= GST_MPEGVID_TYPEFIND_TRY_PICTURES && seen_seq)
2559       probability = GST_TYPE_FIND_NEARLY_CERTAIN - 9;
2560     else if (found >= GST_MPEGVID_TYPEFIND_TRY_PICTURES)
2561       probability = GST_TYPE_FIND_LIKELY;
2562     else if (seen_seq_at_0 && seen_gop && found > 2)
2563       probability = GST_TYPE_FIND_LIKELY - 10;
2564     else if (seen_seq && seen_gop && found > 2)
2565       probability = GST_TYPE_FIND_LIKELY - 20;
2566     else if (seen_seq_at_0 && found > 0)
2567       probability = GST_TYPE_FIND_POSSIBLE;
2568     else if (seen_seq && found > 0)
2569       probability = GST_TYPE_FIND_POSSIBLE - 5;
2570     else if (found > 0)
2571       probability = GST_TYPE_FIND_POSSIBLE - 10;
2572     else if (seen_seq)
2573       probability = GST_TYPE_FIND_POSSIBLE - 20;
2574
2575     gst_type_find_suggest_simple (tf, probability, "video/mpeg",
2576         "systemstream", G_TYPE_BOOLEAN, FALSE,
2577         "mpegversion", G_TYPE_INT, 1, NULL);
2578   }
2579 }
2580
2581 /*** audio/x-aiff ***/
2582
2583 static GstStaticCaps aiff_caps = GST_STATIC_CAPS ("audio/x-aiff");
2584
2585 #define AIFF_CAPS gst_static_caps_get(&aiff_caps)
2586 static void
2587 aiff_type_find (GstTypeFind * tf, gpointer unused)
2588 {
2589   const guint8 *data = gst_type_find_peek (tf, 0, 4);
2590
2591   if (data && memcmp (data, "FORM", 4) == 0) {
2592     data += 8;
2593     if (memcmp (data, "AIFF", 4) == 0 || memcmp (data, "AIFC", 4) == 0)
2594       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, AIFF_CAPS);
2595   }
2596 }
2597
2598 /*** audio/x-svx ***/
2599
2600 static GstStaticCaps svx_caps = GST_STATIC_CAPS ("audio/x-svx");
2601
2602 #define SVX_CAPS gst_static_caps_get(&svx_caps)
2603 static void
2604 svx_type_find (GstTypeFind * tf, gpointer unused)
2605 {
2606   const guint8 *data = gst_type_find_peek (tf, 0, 4);
2607
2608   if (data && memcmp (data, "FORM", 4) == 0) {
2609     data += 8;
2610     if (memcmp (data, "8SVX", 4) == 0 || memcmp (data, "16SV", 4) == 0)
2611       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SVX_CAPS);
2612   }
2613 }
2614
2615 /*** audio/x-shorten ***/
2616
2617 static GstStaticCaps shn_caps = GST_STATIC_CAPS ("audio/x-shorten");
2618
2619 #define SHN_CAPS gst_static_caps_get(&shn_caps)
2620 static void
2621 shn_type_find (GstTypeFind * tf, gpointer unused)
2622 {
2623   const guint8 *data = gst_type_find_peek (tf, 0, 4);
2624
2625   if (data && memcmp (data, "ajkg", 4) == 0) {
2626     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SHN_CAPS);
2627   }
2628   data = gst_type_find_peek (tf, -8, 8);
2629   if (data && memcmp (data, "SHNAMPSK", 8) == 0) {
2630     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SHN_CAPS);
2631   }
2632 }
2633
2634 /*** application/x-ape ***/
2635
2636 static GstStaticCaps ape_caps = GST_STATIC_CAPS ("application/x-ape");
2637
2638 #define APE_CAPS gst_static_caps_get(&ape_caps)
2639 static void
2640 ape_type_find (GstTypeFind * tf, gpointer unused)
2641 {
2642   const guint8 *data = gst_type_find_peek (tf, 0, 4);
2643
2644   if (data && memcmp (data, "MAC ", 4) == 0) {
2645     gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY + 10, APE_CAPS);
2646   }
2647 }
2648
2649 /*** ISO FORMATS ***/
2650
2651 /*** audio/x-m4a ***/
2652
2653 static GstStaticCaps m4a_caps = GST_STATIC_CAPS ("audio/x-m4a");
2654
2655 #define M4A_CAPS (gst_static_caps_get(&m4a_caps))
2656 static void
2657 m4a_type_find (GstTypeFind * tf, gpointer unused)
2658 {
2659   const guint8 *data = gst_type_find_peek (tf, 4, 8);
2660
2661   if (data && (memcmp (data, "ftypM4A ", 8) == 0)) {
2662     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, M4A_CAPS);
2663   }
2664 }
2665
2666 /*** application/x-3gp ***/
2667
2668 /* The Q is there because variables can't start with a number. */
2669 static GstStaticCaps q3gp_caps = GST_STATIC_CAPS ("application/x-3gp");
2670 #define Q3GP_CAPS (gst_static_caps_get(&q3gp_caps))
2671
2672 static const gchar *
2673 q3gp_type_find_get_profile (const guint8 * data)
2674 {
2675   switch (GST_MAKE_FOURCC (data[0], data[1], data[2], 0)) {
2676     case GST_MAKE_FOURCC ('3', 'g', 'g', 0):
2677       return "general";
2678     case GST_MAKE_FOURCC ('3', 'g', 'p', 0):
2679       return "basic";
2680     case GST_MAKE_FOURCC ('3', 'g', 's', 0):
2681       return "streaming-server";
2682     case GST_MAKE_FOURCC ('3', 'g', 'r', 0):
2683       return "progressive-download";
2684     default:
2685       break;
2686   }
2687   return NULL;
2688 }
2689
2690 static void
2691 q3gp_type_find (GstTypeFind * tf, gpointer unused)
2692 {
2693   const gchar *profile;
2694   guint32 ftyp_size = 0;
2695   gint offset = 0;
2696   const guint8 *data = NULL;
2697
2698   if ((data = gst_type_find_peek (tf, 0, 12)) == NULL) {
2699     return;
2700   }
2701
2702   data += 4;
2703   if (memcmp (data, "ftyp", 4) != 0) {
2704     return;
2705   }
2706
2707   /* check major brand */
2708   data += 4;
2709   if ((profile = q3gp_type_find_get_profile (data))) {
2710     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM,
2711         "application/x-3gp", "profile", G_TYPE_STRING, profile, NULL);
2712     return;
2713   }
2714
2715   /* check compatible brands */
2716   if ((data = gst_type_find_peek (tf, 0, 4)) != NULL) {
2717     ftyp_size = GST_READ_UINT32_BE (data);
2718   }
2719   for (offset = 16; offset < ftyp_size; offset += 4) {
2720     if ((data = gst_type_find_peek (tf, offset, 3)) == NULL) {
2721       break;
2722     }
2723     if ((profile = q3gp_type_find_get_profile (data))) {
2724       gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM,
2725           "application/x-3gp", "profile", G_TYPE_STRING, profile, NULL);
2726       return;
2727     }
2728   }
2729
2730   return;
2731
2732 }
2733
2734 /*** video/mj2 and image/jp2 ***/
2735 static GstStaticCaps mj2_caps = GST_STATIC_CAPS ("video/mj2");
2736
2737 #define MJ2_CAPS gst_static_caps_get(&mj2_caps)
2738
2739 static GstStaticCaps jp2_caps = GST_STATIC_CAPS ("image/jp2");
2740
2741 #define JP2_CAPS gst_static_caps_get(&jp2_caps)
2742
2743 static void
2744 jp2_type_find (GstTypeFind * tf, gpointer unused)
2745 {
2746   const guint8 *data;
2747
2748   data = gst_type_find_peek (tf, 0, 24);
2749   if (!data)
2750     return;
2751
2752   /* jp2 signature */
2753   if (memcmp (data, "\000\000\000\014jP  \015\012\207\012", 12) != 0)
2754     return;
2755
2756   /* check ftyp box */
2757   data += 12;
2758   if (memcmp (data + 4, "ftyp", 4) == 0) {
2759     if (memcmp (data + 8, "jp2 ", 4) == 0)
2760       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, JP2_CAPS);
2761     else if (memcmp (data + 8, "mjp2", 4) == 0)
2762       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MJ2_CAPS);
2763   }
2764 }
2765
2766 /*** video/quicktime ***/
2767
2768 static GstStaticCaps qt_caps = GST_STATIC_CAPS ("video/quicktime");
2769
2770 #define QT_CAPS gst_static_caps_get(&qt_caps)
2771 #define STRNCMP(x,y,z) (strncmp ((char*)(x), (char*)(y), z))
2772
2773 /* FIXME 0.11: go through http://www.ftyps.com/ */
2774 static void
2775 qt_type_find (GstTypeFind * tf, gpointer unused)
2776 {
2777   const guint8 *data;
2778   guint tip = 0;
2779   guint64 offset = 0;
2780   guint64 size;
2781   const gchar *variant = NULL;
2782
2783   while ((data = gst_type_find_peek (tf, offset, 12)) != NULL) {
2784     guint64 new_offset;
2785
2786     if (STRNCMP (&data[4], "ftypqt  ", 8) == 0) {
2787       tip = GST_TYPE_FIND_MAXIMUM;
2788       break;
2789     }
2790
2791     if (STRNCMP (&data[4], "ftypisom", 8) == 0 ||
2792         STRNCMP (&data[4], "ftypavc1", 8) == 0 ||
2793         STRNCMP (&data[4], "ftypmp42", 8) == 0) {
2794       tip = GST_TYPE_FIND_MAXIMUM;
2795       variant = "iso";
2796       break;
2797     }
2798
2799     /* box/atom types that are in common with ISO base media file format */
2800     if (STRNCMP (&data[4], "moov", 4) == 0 ||
2801         STRNCMP (&data[4], "mdat", 4) == 0 ||
2802         STRNCMP (&data[4], "ftyp", 4) == 0 ||
2803         STRNCMP (&data[4], "free", 4) == 0 ||
2804         STRNCMP (&data[4], "uuid", 4) == 0 ||
2805         STRNCMP (&data[4], "skip", 4) == 0) {
2806       if (tip == 0) {
2807         tip = GST_TYPE_FIND_LIKELY;
2808       } else {
2809         tip = GST_TYPE_FIND_NEARLY_CERTAIN;
2810       }
2811     }
2812     /* other box/atom types, apparently quicktime specific */
2813     else if (STRNCMP (&data[4], "pnot", 4) == 0 ||
2814         STRNCMP (&data[4], "PICT", 4) == 0 ||
2815         STRNCMP (&data[4], "wide", 4) == 0 ||
2816         STRNCMP (&data[4], "prfl", 4) == 0) {
2817       tip = GST_TYPE_FIND_MAXIMUM;
2818       break;
2819     } else {
2820       tip = 0;
2821       break;
2822     }
2823
2824     size = GST_READ_UINT32_BE (data);
2825     /* check compatible brands rather than ever expaning major brands above */
2826     if ((STRNCMP (&data[4], "ftyp", 4) == 0) && (size >= 16)) {
2827       new_offset = offset + 12;
2828       while (new_offset + 4 <= offset + size) {
2829         data = gst_type_find_peek (tf, new_offset, 4);
2830         if (data == NULL)
2831           goto done;
2832         if (STRNCMP (&data[4], "isom", 4) == 0 ||
2833             STRNCMP (&data[4], "avc1", 4) == 0 ||
2834             STRNCMP (&data[4], "mp41", 4) == 0 ||
2835             STRNCMP (&data[4], "mp42", 4) == 0) {
2836           tip = GST_TYPE_FIND_MAXIMUM;
2837           variant = "iso";
2838           goto done;
2839         }
2840         new_offset += 4;
2841       }
2842     }
2843     if (size == 1) {
2844       const guint8 *sizedata;
2845
2846       sizedata = gst_type_find_peek (tf, offset + 8, 8);
2847       if (sizedata == NULL)
2848         break;
2849
2850       size = GST_READ_UINT64_BE (sizedata);
2851     } else {
2852       if (size < 8)
2853         break;
2854     }
2855     new_offset = offset + size;
2856     if (new_offset <= offset)
2857       break;
2858     offset = new_offset;
2859   }
2860
2861 done:
2862   if (tip > 0) {
2863     if (variant) {
2864       GstCaps *caps = gst_caps_copy (QT_CAPS);
2865
2866       gst_caps_set_simple (caps, "variant", G_TYPE_STRING, variant, NULL);
2867       gst_type_find_suggest (tf, tip, caps);
2868       gst_caps_unref (caps);
2869     } else {
2870       gst_type_find_suggest (tf, tip, QT_CAPS);
2871     }
2872   }
2873 };
2874
2875
2876 /*** image/x-quicktime ***/
2877
2878 static GstStaticCaps qtif_caps = GST_STATIC_CAPS ("image/x-quicktime");
2879
2880 #define QTIF_CAPS gst_static_caps_get(&qtif_caps)
2881
2882 /* how many atoms we check before we give up */
2883 #define QTIF_MAXROUNDS 25
2884
2885 static void
2886 qtif_type_find (GstTypeFind * tf, gpointer unused)
2887 {
2888   const guint8 *data;
2889   gboolean found_idsc = FALSE;
2890   gboolean found_idat = FALSE;
2891   guint64 offset = 0;
2892   guint rounds = 0;
2893
2894   while ((data = gst_type_find_peek (tf, offset, 8)) != NULL) {
2895     guint64 size;
2896
2897     size = GST_READ_UINT32_BE (data);
2898     if (size == 1) {
2899       const guint8 *sizedata;
2900
2901       sizedata = gst_type_find_peek (tf, offset + 8, 8);
2902       if (sizedata == NULL)
2903         break;
2904
2905       size = GST_READ_UINT64_BE (sizedata);
2906     }
2907     if (size < 8)
2908       break;
2909
2910     if (STRNCMP (data + 4, "idsc", 4) == 0)
2911       found_idsc = TRUE;
2912     if (STRNCMP (data + 4, "idat", 4) == 0)
2913       found_idat = TRUE;
2914
2915     if (found_idsc && found_idat) {
2916       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, QTIF_CAPS);
2917       return;
2918     }
2919
2920     offset += size;
2921     if (++rounds > QTIF_MAXROUNDS)
2922       break;
2923   }
2924
2925   if (found_idsc || found_idat) {
2926     gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, QTIF_CAPS);
2927     return;
2928   }
2929 };
2930
2931 /*** audio/x-mod ***/
2932
2933 static GstStaticCaps mod_caps = GST_STATIC_CAPS ("audio/x-mod");
2934
2935 #define MOD_CAPS gst_static_caps_get(&mod_caps)
2936 /* FIXME: M15 CheckType to do */
2937 static void
2938 mod_type_find (GstTypeFind * tf, gpointer unused)
2939 {
2940   const guint8 *data;
2941
2942   /* MOD */
2943   if ((data = gst_type_find_peek (tf, 1080, 4)) != NULL) {
2944     /* Protracker and variants */
2945     if ((memcmp (data, "M.K.", 4) == 0) || (memcmp (data, "M!K!", 4) == 0) ||
2946         /* Star Tracker */
2947         (memcmp (data, "FLT", 3) == 0 && isdigit (data[3])) ||
2948         (memcmp (data, "EXO", 3) == 0 && isdigit (data[3])) ||
2949         /* Oktalyzer (Amiga) */
2950         (memcmp (data, "OKTA", 4) == 0) ||
2951         /* Oktalyser (Atari) */
2952         (memcmp (data, "CD81", 4) == 0) ||
2953         /* Fasttracker */
2954         (memcmp (data + 1, "CHN", 3) == 0 && isdigit (data[0])) ||
2955         /* Fasttracker or Taketracker */
2956         (memcmp (data + 2, "CH", 2) == 0 && isdigit (data[0])
2957             && isdigit (data[1])) || (memcmp (data + 2, "CN", 2) == 0
2958             && isdigit (data[0]) && isdigit (data[1]))) {
2959       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
2960       return;
2961     }
2962   }
2963   /* XM */
2964   if ((data = gst_type_find_peek (tf, 0, 38)) != NULL) {
2965     if (memcmp (data, "Extended Module: ", 17) == 0 && data[37] == 0x1A) {
2966       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
2967       return;
2968     }
2969   }
2970   /* OKT */
2971   if (data || (data = gst_type_find_peek (tf, 0, 8)) != NULL) {
2972     if (memcmp (data, "OKTASONG", 8) == 0) {
2973       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
2974       return;
2975     }
2976   }
2977   if (data || (data = gst_type_find_peek (tf, 0, 4)) != NULL) {
2978     /* 669 */
2979     if ((memcmp (data, "if", 2) == 0) || (memcmp (data, "JN", 2) == 0)) {
2980       gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, MOD_CAPS);
2981       return;
2982     }
2983     /* AMF */
2984     if ((memcmp (data, "AMF", 3) == 0 && data[3] > 10 && data[3] < 14) ||
2985         /* IT */
2986         (memcmp (data, "IMPM", 4) == 0) ||
2987         /* MED */
2988         (memcmp (data, "MMD0", 4) == 0) || (memcmp (data, "MMD1", 4) == 0) ||
2989         /* MTM */
2990         (memcmp (data, "MTM", 3) == 0)) {
2991       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
2992       return;
2993     }
2994     /* DSM */
2995     if (memcmp (data, "RIFF", 4) == 0) {
2996       const guint8 *data2 = gst_type_find_peek (tf, 8, 4);
2997
2998       if (data2) {
2999         if (memcmp (data2, "DSMF", 4) == 0) {
3000           gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3001           return;
3002         }
3003       }
3004     }
3005     /* FAM */
3006     if (memcmp (data, "FAM\xFE", 4) == 0) {
3007       const guint8 *data2 = gst_type_find_peek (tf, 44, 3);
3008
3009       if (data2) {
3010         if (memcmp (data2, "compare", 3) == 0) {
3011           gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3012           return;
3013         }
3014       } else {
3015         gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, MOD_CAPS);
3016         return;
3017       }
3018     }
3019     /* GDM */
3020     if (memcmp (data, "GDM\xFE", 4) == 0) {
3021       const guint8 *data2 = gst_type_find_peek (tf, 71, 4);
3022
3023       if (data2) {
3024         if (memcmp (data2, "GMFS", 4) == 0) {
3025           gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3026           return;
3027         }
3028       } else {
3029         gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, MOD_CAPS);
3030         return;
3031       }
3032     }
3033   }
3034   /* IMF */
3035   if ((data = gst_type_find_peek (tf, 60, 4)) != NULL) {
3036     if (memcmp (data, "IM10", 4) == 0) {
3037       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3038       return;
3039     }
3040   }
3041   /* S3M */
3042   if ((data = gst_type_find_peek (tf, 44, 4)) != NULL) {
3043     if (memcmp (data, "SCRM", 4) == 0) {
3044       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3045       return;
3046     }
3047   }
3048   /* STM */
3049   if ((data = gst_type_find_peek (tf, 20, 8)) != NULL) {
3050     if (g_ascii_strncasecmp ((gchar *) data, "!Scream!", 8) == 0 ||
3051         g_ascii_strncasecmp ((gchar *) data, "BMOD2STM", 8) == 0) {
3052       const guint8 *id, *stmtype;
3053
3054       if ((id = gst_type_find_peek (tf, 28, 1)) == NULL)
3055         return;
3056       if ((stmtype = gst_type_find_peek (tf, 29, 1)) == NULL)
3057         return;
3058       if (*id == 0x1A && *stmtype == 2)
3059         gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3060       return;
3061     }
3062   }
3063   /* AMF */
3064   if ((data = gst_type_find_peek (tf, 0, 19)) != NULL) {
3065     if (memcmp (data, "ASYLUM Music Format", 19) == 0) {
3066       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MOD_CAPS);
3067       return;
3068     }
3069   }
3070 }
3071
3072 /*** application/x-shockwave-flash ***/
3073
3074 static GstStaticCaps swf_caps =
3075 GST_STATIC_CAPS ("application/x-shockwave-flash");
3076 #define SWF_CAPS (gst_static_caps_get(&swf_caps))
3077 static void
3078 swf_type_find (GstTypeFind * tf, gpointer unused)
3079 {
3080   const guint8 *data = gst_type_find_peek (tf, 0, 4);
3081
3082   if (data && (data[0] == 'F' || data[0] == 'C') &&
3083       data[1] == 'W' && data[2] == 'S') {
3084     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SWF_CAPS);
3085   }
3086 }
3087
3088 /*** image/jpeg ***/
3089
3090 #define JPEG_MARKER_IS_START_OF_FRAME(x) \
3091     ((x)>=0xc0 && (x) <= 0xcf && (x)!=0xc4 && (x)!=0xc8 && (x)!=0xcc)
3092
3093 static GstStaticCaps jpeg_caps = GST_STATIC_CAPS ("image/jpeg");
3094
3095 #define JPEG_CAPS (gst_static_caps_get(&jpeg_caps))
3096 static void
3097 jpeg_type_find (GstTypeFind * tf, gpointer unused)
3098 {
3099   GstTypeFindProbability prob = GST_TYPE_FIND_POSSIBLE;
3100   DataScanCtx c = { 0, NULL, 0 };
3101   GstCaps *caps;
3102   guint num_markers;
3103
3104   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 2)))
3105     return;
3106
3107   if (c.data[0] != 0xff || c.data[1] != 0xd8)
3108     return;
3109
3110   num_markers = 1;
3111   data_scan_ctx_advance (tf, &c, 2);
3112
3113   caps = gst_caps_copy (JPEG_CAPS);
3114
3115   while (data_scan_ctx_ensure_data (tf, &c, 4) && c.offset < (200 * 1024)) {
3116     guint16 len;
3117     guint8 marker;
3118
3119     if (c.data[0] != 0xff)
3120       break;
3121
3122     marker = c.data[1];
3123     if (G_UNLIKELY (marker == 0xff)) {
3124       data_scan_ctx_advance (tf, &c, 1);
3125       continue;
3126     }
3127
3128     data_scan_ctx_advance (tf, &c, 2);
3129
3130     /* we assume all markers we'll see before SOF have a payload length; if
3131      * that's not the case we'll just detect a false sync and bail out, but
3132      * still report POSSIBLE probability */
3133     len = GST_READ_UINT16_BE (c.data);
3134
3135     GST_LOG ("possible JPEG marker 0x%02x (@0x%04x), segment length %u",
3136         marker, (guint) c.offset, len);
3137
3138     if (!data_scan_ctx_ensure_data (tf, &c, len))
3139       break;
3140
3141     if (marker == 0xc4 ||       /* DEFINE_HUFFMAN_TABLES          */
3142         marker == 0xcc ||       /* DEFINE_ARITHMETIC_CONDITIONING */
3143         marker == 0xdb ||       /* DEFINE_QUANTIZATION_TABLES     */
3144         marker == 0xdd ||       /* DEFINE_RESTART_INTERVAL        */
3145         marker == 0xfe) {       /* COMMENT                        */
3146       data_scan_ctx_advance (tf, &c, len);
3147       ++num_markers;
3148     } else if (marker == 0xe0 && len >= (2 + 4) &&      /* APP0 */
3149         data_scan_ctx_memcmp (tf, &c, 2, "JFIF", 4)) {
3150       GST_LOG ("found JFIF tag");
3151       prob = GST_TYPE_FIND_MAXIMUM;
3152       data_scan_ctx_advance (tf, &c, len);
3153       ++num_markers;
3154       /* we continue until we find a start of frame marker */
3155     } else if (marker == 0xe1 && len >= (2 + 4) &&      /* APP1 */
3156         data_scan_ctx_memcmp (tf, &c, 2, "Exif", 4)) {
3157       GST_LOG ("found Exif tag");
3158       prob = GST_TYPE_FIND_MAXIMUM;
3159       data_scan_ctx_advance (tf, &c, len);
3160       ++num_markers;
3161       /* we continue until we find a start of frame marker */
3162     } else if (marker >= 0xe0 && marker <= 0xef) {      /* APPn */
3163       data_scan_ctx_advance (tf, &c, len);
3164       ++num_markers;
3165     } else if (JPEG_MARKER_IS_START_OF_FRAME (marker) && len >= (2 + 8)) {
3166       int h, w;
3167
3168       h = GST_READ_UINT16_BE (c.data + 2 + 1);
3169       w = GST_READ_UINT16_BE (c.data + 2 + 1 + 2);
3170       if (h == 0 || w == 0) {
3171         GST_WARNING ("bad width %u and/or height %u in SOF header", w, h);
3172         break;
3173       }
3174
3175       GST_LOG ("SOF at offset %" G_GUINT64_FORMAT ", num_markers=%d, "
3176           "WxH=%dx%d", c.offset - 2, num_markers, w, h);
3177
3178       if (num_markers >= 5 || prob == GST_TYPE_FIND_MAXIMUM)
3179         prob = GST_TYPE_FIND_MAXIMUM;
3180       else
3181         prob = GST_TYPE_FIND_LIKELY;
3182
3183       gst_caps_set_simple (caps, "width", G_TYPE_INT, w,
3184           "height", G_TYPE_INT, h, "sof-marker", G_TYPE_INT, marker & 0xf,
3185           NULL);
3186
3187       break;
3188     } else {
3189       GST_WARNING ("bad length or unexpected JPEG marker 0xff 0x%02x", marker);
3190       break;
3191     }
3192   }
3193
3194   gst_type_find_suggest (tf, prob, caps);
3195   gst_caps_unref (caps);
3196 }
3197
3198 /*** image/bmp ***/
3199
3200 static GstStaticCaps bmp_caps = GST_STATIC_CAPS ("image/bmp");
3201
3202 #define BMP_CAPS (gst_static_caps_get(&bmp_caps))
3203 static void
3204 bmp_type_find (GstTypeFind * tf, gpointer unused)
3205 {
3206   DataScanCtx c = { 0, NULL, 0 };
3207   guint32 struct_size, w, h, planes, bpp;
3208
3209   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 54)))
3210     return;
3211
3212   if (c.data[0] != 'B' || c.data[1] != 'M')
3213     return;
3214
3215   /* skip marker + size */
3216   data_scan_ctx_advance (tf, &c, 2 + 4);
3217
3218   /* reserved, must be 0 */
3219   if (c.data[0] != 0 || c.data[1] != 0 || c.data[2] != 0 || c.data[3] != 0)
3220     return;
3221
3222   data_scan_ctx_advance (tf, &c, 2 + 2);
3223
3224   /* offset to start of image data in bytes (check for sanity) */
3225   GST_LOG ("offset=%u", GST_READ_UINT32_LE (c.data));
3226   if (GST_READ_UINT32_LE (c.data) > (10 * 1024 * 1024))
3227     return;
3228
3229   struct_size = GST_READ_UINT32_LE (c.data + 4);
3230   GST_LOG ("struct_size=%u", struct_size);
3231
3232   data_scan_ctx_advance (tf, &c, 4 + 4);
3233
3234   if (struct_size == 0x0C) {
3235     w = GST_READ_UINT16_LE (c.data);
3236     h = GST_READ_UINT16_LE (c.data + 2);
3237     planes = GST_READ_UINT16_LE (c.data + 2 + 2);
3238     bpp = GST_READ_UINT16_LE (c.data + 2 + 2 + 2);
3239   } else if (struct_size == 40 || struct_size == 64 || struct_size == 108
3240       || struct_size == 124 || struct_size == 0xF0) {
3241     w = GST_READ_UINT32_LE (c.data);
3242     h = GST_READ_UINT32_LE (c.data + 4);
3243     planes = GST_READ_UINT16_LE (c.data + 4 + 4);
3244     bpp = GST_READ_UINT16_LE (c.data + 4 + 4 + 2);
3245   } else {
3246     return;
3247   }
3248
3249   /* image sizes sanity check */
3250   GST_LOG ("w=%u, h=%u, planes=%u, bpp=%u", w, h, planes, bpp);
3251   if (w == 0 || w > 0xfffff || h == 0 || h > 0xfffff || planes != 1 ||
3252       (bpp != 1 && bpp != 4 && bpp != 8 && bpp != 16 && bpp != 24 && bpp != 32))
3253     return;
3254
3255   gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM, "image/bmp",
3256       "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, "bpp", G_TYPE_INT, bpp,
3257       NULL);
3258 }
3259
3260 /*** image/tiff ***/
3261 static GstStaticCaps tiff_caps = GST_STATIC_CAPS ("image/tiff, "
3262     "endianness = (int) { BIG_ENDIAN, LITTLE_ENDIAN }");
3263 #define TIFF_CAPS (gst_static_caps_get(&tiff_caps))
3264 static GstStaticCaps tiff_be_caps = GST_STATIC_CAPS ("image/tiff, "
3265     "endianness = (int) BIG_ENDIAN");
3266 #define TIFF_BE_CAPS (gst_static_caps_get(&tiff_be_caps))
3267 static GstStaticCaps tiff_le_caps = GST_STATIC_CAPS ("image/tiff, "
3268     "endianness = (int) LITTLE_ENDIAN");
3269 #define TIFF_LE_CAPS (gst_static_caps_get(&tiff_le_caps))
3270 static void
3271 tiff_type_find (GstTypeFind * tf, gpointer ununsed)
3272 {
3273   const guint8 *data = gst_type_find_peek (tf, 0, 8);
3274   guint8 le_header[4] = { 0x49, 0x49, 0x2A, 0x00 };
3275   guint8 be_header[4] = { 0x4D, 0x4D, 0x00, 0x2A };
3276
3277   if (data) {
3278     if (memcmp (data, le_header, 4) == 0) {
3279       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, TIFF_LE_CAPS);
3280     } else if (memcmp (data, be_header, 4) == 0) {
3281       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, TIFF_BE_CAPS);
3282     }
3283   }
3284 }
3285
3286 /*** PNM ***/
3287
3288 static GstStaticCaps pnm_caps = GST_STATIC_CAPS ("image/x-portable-bitmap; "
3289     "image/x-portable-graymap; image/x-portable-pixmap; "
3290     "image/x-portable-anymap");
3291
3292 #define PNM_CAPS (gst_static_caps_get(&pnm_caps))
3293
3294 #define IS_PNM_WHITESPACE(c) \
3295     ((c) == ' ' || (c) == '\r' || (c) == '\n' || (c) == 't')
3296
3297 static void
3298 pnm_type_find (GstTypeFind * tf, gpointer ununsed)
3299 {
3300   const gchar *media_type = NULL;
3301   DataScanCtx c = { 0, NULL, 0 };
3302   guint h = 0, w = 0;
3303
3304   if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 16)))
3305     return;
3306
3307   /* see http://en.wikipedia.org/wiki/Netpbm_format */
3308   if (c.data[0] != 'P' || c.data[1] < '1' || c.data[1] > '7' ||
3309       !IS_PNM_WHITESPACE (c.data[2]) ||
3310       (c.data[3] != '#' && c.data[3] < '0' && c.data[3] > '9'))
3311     return;
3312
3313   switch (c.data[1]) {
3314     case '1':
3315       media_type = "image/x-portable-bitmap";   /* ASCII */
3316       break;
3317     case '2':
3318       media_type = "image/x-portable-graymap";  /* ASCII */
3319       break;
3320     case '3':
3321       media_type = "image/x-portable-pixmap";   /* ASCII */
3322       break;
3323     case '4':
3324       media_type = "image/x-portable-bitmap";   /* Raw */
3325       break;
3326     case '5':
3327       media_type = "image/x-portable-graymap";  /* Raw */
3328       break;
3329     case '6':
3330       media_type = "image/x-portable-pixmap";   /* Raw */
3331       break;
3332     case '7':
3333       media_type = "image/x-portable-anymap";
3334       break;
3335     default:
3336       g_return_if_reached ();
3337   }
3338
3339   /* try to extract width and height as well */
3340   if (c.data[1] != '7') {
3341     gchar s[64] = { 0, }
3342     , sep1, sep2;
3343
3344     /* need to skip any comment lines first */
3345     data_scan_ctx_advance (tf, &c, 3);
3346     while (c.data[0] == '#') {  /* we know there's still data left */
3347       data_scan_ctx_advance (tf, &c, 1);
3348       while (c.data[0] != '\n' && c.data[0] != '\r') {
3349         if (!data_scan_ctx_ensure_data (tf, &c, 4))
3350           return;
3351         data_scan_ctx_advance (tf, &c, 1);
3352       }
3353       data_scan_ctx_advance (tf, &c, 1);
3354       GST_LOG ("skipped comment line in PNM header");
3355     }
3356
3357     if (!data_scan_ctx_ensure_data (tf, &c, 32) &&
3358         !data_scan_ctx_ensure_data (tf, &c, 4)) {
3359       return;
3360     }
3361
3362     /* need to NUL-terminate data for sscanf */
3363     memcpy (s, c.data, MIN (sizeof (s) - 1, c.size));
3364     if (sscanf (s, "%u%c%u%c", &w, &sep1, &h, &sep2) == 4 &&
3365         IS_PNM_WHITESPACE (sep1) && IS_PNM_WHITESPACE (sep2) &&
3366         w > 0 && w < G_MAXINT && h > 0 && h < G_MAXINT) {
3367       GST_LOG ("extracted PNM width and height: %dx%d", w, h);
3368     } else {
3369       w = 0;
3370       h = 0;
3371     }
3372   } else {
3373     /* FIXME: extract width + height for anymaps too */
3374   }
3375
3376   if (w > 0 && h > 0) {
3377     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM, media_type,
3378         "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
3379   } else {
3380     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_LIKELY, media_type, NULL);
3381   }
3382 }
3383
3384 static GstStaticCaps sds_caps = GST_STATIC_CAPS ("audio/x-sds");
3385
3386 #define SDS_CAPS (gst_static_caps_get(&sds_caps))
3387 static void
3388 sds_type_find (GstTypeFind * tf, gpointer ununsed)
3389 {
3390   const guint8 *data = gst_type_find_peek (tf, 0, 4);
3391   guint8 mask[4] = { 0xFF, 0xFF, 0x80, 0xFF };
3392   guint8 match[4] = { 0xF0, 0x7E, 0, 0x01 };
3393   gint x;
3394
3395   if (data) {
3396     for (x = 0; x < 4; x++) {
3397       if ((data[x] & mask[x]) != match[x]) {
3398         return;
3399       }
3400     }
3401     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SDS_CAPS);
3402   }
3403 }
3404
3405 static GstStaticCaps ircam_caps = GST_STATIC_CAPS ("audio/x-ircam");
3406
3407 #define IRCAM_CAPS (gst_static_caps_get(&ircam_caps))
3408 static void
3409 ircam_type_find (GstTypeFind * tf, gpointer ununsed)
3410 {
3411   const guint8 *data = gst_type_find_peek (tf, 0, 4);
3412   guint8 mask[4] = { 0xFF, 0xFF, 0xF8, 0xFF };
3413   guint8 match[4] = { 0x64, 0xA3, 0x00, 0x00 };
3414   gint x;
3415   gboolean matched = TRUE;
3416
3417   if (!data) {
3418     return;
3419   }
3420   for (x = 0; x < 4; x++) {
3421     if ((data[x] & mask[x]) != match[x]) {
3422       matched = FALSE;
3423     }
3424   }
3425   if (matched) {
3426     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, IRCAM_CAPS);
3427     return;
3428   }
3429   /* now try the reverse version */
3430   matched = TRUE;
3431   for (x = 0; x < 4; x++) {
3432     if ((data[x] & mask[3 - x]) != match[3 - x]) {
3433       matched = FALSE;
3434     }
3435   }
3436 }
3437
3438 /*** Matroska/WebM ***/
3439
3440 #define EBML_HEADER           0x1A45DFA3
3441 #define EBML_VERSION          0x4286
3442 #define EBML_DOCTYPE          0x4282
3443 #define EBML_DOCTYPE_VERSION  0x4287
3444 #define MATROSKA_SEGMENT      0x18538067
3445 #define MATROSKA_CLUSTER      0x1F43B675
3446 #define MATROSKA_TRACKS       0x1654AE6B
3447 #define MATROSKA_TRACK_ENTRY  0xAE
3448 #define MATROSKA_TRACK_TYPE   0x83
3449 #define MATROSKA_STEREO_MODE  0x53B8
3450
3451 #define EBML_MAX_LEN (2 * 1024 * 1024)
3452
3453 typedef enum
3454 {
3455   EBML_DOCTYPE_UNKNOWN = 0,
3456   EBML_DOCTYPE_MATROSKA,
3457   EBML_DOCTYPE_WEBM
3458 } GstEbmlDocType;
3459
3460 typedef struct
3461 {
3462   GstEbmlDocType doctype;
3463   guint audio;
3464   guint video;
3465   guint other;
3466   guint video_stereo;
3467   guint chunks;
3468   guint tracks_ok;              /* if we've seen and fully parsed the TRACKS element */
3469 } GstMatroskaInfo;
3470
3471 static inline guint
3472 ebml_read_chunk_header (GstTypeFind * tf, DataScanCtx * c, guint max_size,
3473     guint32 * id, guint64 * size)
3474 {
3475   guint64 mask;
3476   guint msbit_set, i, len, id_len;
3477
3478   if (c->size < 12 || max_size < 1)
3479     return 0;
3480
3481   /* element ID */
3482   *id = c->data[0];
3483   if ((c->data[0] & 0x80) == 0x80) {
3484     id_len = 1;
3485   } else if ((c->data[0] & 0xC0) == 0x40) {
3486     id_len = 2;
3487   } else if ((c->data[0] & 0xE0) == 0x20) {
3488     id_len = 3;
3489   } else if ((c->data[0] & 0xF0) == 0x10) {
3490     id_len = 4;
3491   } else {
3492     return 0;
3493   }
3494
3495   if (max_size < id_len)
3496     return 0;
3497
3498   for (i = 1; i < id_len; ++i) {
3499     *id = (*id << 8) | c->data[i];
3500   }
3501
3502   data_scan_ctx_advance (tf, c, id_len);
3503   max_size -= id_len;
3504
3505   /* size */
3506   if (max_size < 1 || c->data[0] == 0)
3507     return 0;
3508
3509   msbit_set = g_bit_nth_msf (c->data[0], 8);
3510   mask = ((1 << msbit_set) - 1);
3511   *size = c->data[0] & mask;
3512   len = 7 - msbit_set;
3513
3514   if (max_size < 1 + len)
3515     return 0;
3516   for (i = 0; i < len; ++i) {
3517     mask = (mask << 8) | 0xff;
3518     *size = (*size << 8) | c->data[1 + i];
3519   }
3520
3521   data_scan_ctx_advance (tf, c, 1 + len);
3522
3523   /* undefined/unknown size? (all bits 1) */
3524   if (*size == mask) {
3525     /* allow unknown size for SEGMENT chunk, bail out otherwise */
3526     if (*id == MATROSKA_SEGMENT)
3527       *size = G_MAXUINT64;
3528     else
3529       return 0;
3530   }
3531
3532   return id_len + (1 + len);
3533 }
3534
3535 static gboolean
3536 ebml_parse_chunk (GstTypeFind * tf, DataScanCtx * ctx, guint32 chunk_id,
3537     guint chunk_size, GstMatroskaInfo * info, guint depth)
3538 {                               /* FIXME: make sure input size is clipped to 32 bit */
3539   static const gchar SPACES[] = "                ";
3540   DataScanCtx c = *ctx;
3541   guint64 element_size;
3542   guint32 id, hdr_len;
3543
3544   if (depth >= 8)               /* keep SPACES large enough for depth */
3545     return FALSE;
3546
3547   while (chunk_size > 0) {
3548     if (c.offset > EBML_MAX_LEN || !data_scan_ctx_ensure_data (tf, &c, 64))
3549       return FALSE;
3550
3551     hdr_len = ebml_read_chunk_header (tf, &c, chunk_size, &id, &element_size);
3552     if (hdr_len == 0)
3553       return FALSE;
3554
3555     g_assert (hdr_len <= chunk_size);
3556     chunk_size -= hdr_len;
3557
3558     if (element_size > chunk_size)
3559       return FALSE;
3560
3561     GST_DEBUG ("%s %08x, size %" G_GUINT64_FORMAT " / %" G_GUINT64_FORMAT,
3562         SPACES + sizeof (SPACES) - 1 - (2 * depth), id, element_size,
3563         hdr_len + element_size);
3564
3565     if (!data_scan_ctx_ensure_data (tf, &c, element_size)) {
3566       GST_DEBUG ("not enough data");
3567       return FALSE;
3568     }
3569
3570     switch (id) {
3571       case EBML_DOCTYPE:
3572         if (element_size >= 8 && memcmp (c.data, "matroska", 8) == 0)
3573           info->doctype = EBML_DOCTYPE_MATROSKA;
3574         else if (element_size >= 4 && memcmp (c.data, "webm", 4) == 0)
3575           info->doctype = EBML_DOCTYPE_WEBM;
3576         break;
3577       case MATROSKA_SEGMENT:
3578         GST_LOG ("parsing segment");
3579         ebml_parse_chunk (tf, &c, id, element_size, info, depth + 1);
3580         GST_LOG ("parsed segment, done");
3581         return FALSE;
3582       case MATROSKA_TRACKS:
3583         GST_LOG ("parsing tracks");
3584         info->tracks_ok =
3585             ebml_parse_chunk (tf, &c, id, element_size, info, depth + 1);
3586         GST_LOG ("parsed tracks: %s, done (after %" G_GUINT64_FORMAT " bytes)",
3587             info->tracks_ok ? "ok" : "FAIL", c.offset + element_size);
3588         return FALSE;
3589       case MATROSKA_TRACK_ENTRY:
3590         GST_LOG ("parsing track entry");
3591         if (!ebml_parse_chunk (tf, &c, id, element_size, info, depth + 1))
3592           return FALSE;
3593         break;
3594       case MATROSKA_TRACK_TYPE:{
3595         guint type = 0, i;
3596
3597         /* is supposed to always be 1-byte, but not everyone's following that */
3598         for (i = 0; i < element_size; ++i)
3599           type = (type << 8) | c.data[i];
3600
3601         GST_DEBUG ("%s   track type %u",
3602             SPACES + sizeof (SPACES) - 1 - (2 * depth), type);
3603
3604         if (type == 1)
3605           ++info->video;
3606         else if (c.data[0] == 2)
3607           ++info->audio;
3608         else
3609           ++info->other;
3610         break;
3611       }
3612       case MATROSKA_STEREO_MODE:
3613         ++info->video_stereo;
3614         break;
3615       case MATROSKA_CLUSTER:
3616         GST_WARNING ("cluster, bailing out (should've found tracks by now)");
3617         return FALSE;
3618       default:
3619         break;
3620     }
3621     data_scan_ctx_advance (tf, &c, element_size);
3622     chunk_size -= element_size;
3623     ++info->chunks;
3624   }
3625
3626   return TRUE;
3627 }
3628
3629 static GstStaticCaps matroska_caps = GST_STATIC_CAPS ("video/x-matroska");
3630
3631 #define MATROSKA_CAPS (gst_static_caps_get(&matroska_caps))
3632 static void
3633 matroska_type_find (GstTypeFind * tf, gpointer ununsed)
3634 {
3635   GstTypeFindProbability prob;
3636   GstMatroskaInfo info = { 0, };
3637   const gchar *type_name;
3638   DataScanCtx c = { 0, NULL, 0 };
3639   gboolean is_audio;
3640   guint64 size;
3641   guint32 id, hdr_len;
3642
3643   if (!data_scan_ctx_ensure_data (tf, &c, 64))
3644     return;
3645
3646   if (GST_READ_UINT32_BE (c.data) != EBML_HEADER)
3647     return;
3648
3649   while (c.offset < EBML_MAX_LEN && data_scan_ctx_ensure_data (tf, &c, 64)) {
3650     hdr_len = ebml_read_chunk_header (tf, &c, c.size, &id, &size);
3651     if (hdr_len == 0)
3652       return;
3653
3654     GST_INFO ("=== top-level chunk %08x, size %" G_GUINT64_FORMAT
3655         " / %" G_GUINT64_FORMAT, id, size, size + hdr_len);
3656
3657     if (!ebml_parse_chunk (tf, &c, id, size, &info, 0))
3658       break;
3659     data_scan_ctx_advance (tf, &c, size);
3660     GST_INFO ("=== done with chunk %08x", id);
3661     if (id == MATROSKA_SEGMENT)
3662       break;
3663   }
3664
3665   GST_INFO ("audio=%u video=%u other=%u chunks=%u doctype=%d all_tracks=%d",
3666       info.audio, info.video, info.other, info.chunks, info.doctype,
3667       info.tracks_ok);
3668
3669   /* perhaps we should bail out if tracks_ok is FALSE and wait for more data?
3670    * (we would need new API to signal this properly and prevent other
3671    * typefinders from taking over the decision then) */
3672   is_audio = (info.audio > 0 && info.video == 0 && info.other == 0);
3673
3674   if (info.doctype == EBML_DOCTYPE_WEBM) {
3675     type_name = (is_audio) ? "audio/webm" : "video/webm";
3676   } else if (info.video > 0 && info.video_stereo) {
3677     type_name = "video/x-matroska-3d";
3678   } else {
3679     type_name = (is_audio) ? "audio/x-matroska" : "video/x-matroska";
3680   }
3681
3682   if (info.doctype == EBML_DOCTYPE_UNKNOWN)
3683     prob = GST_TYPE_FIND_LIKELY;
3684   else
3685     prob = GST_TYPE_FIND_MAXIMUM;
3686
3687   gst_type_find_suggest_simple (tf, prob, type_name, NULL);
3688 }
3689
3690 /*** application/mxf ***/
3691 static GstStaticCaps mxf_caps = GST_STATIC_CAPS ("application/mxf");
3692
3693 #define MXF_MAX_PROBE_LENGTH (1024 * 64)
3694 #define MXF_CAPS (gst_static_caps_get(&mxf_caps))
3695
3696 /*
3697  * MXF files start with a header partition pack key of 16 bytes which is defined
3698  * at SMPTE-377M 6.1. Before this there can be up to 64K of run-in which _must_
3699  * not contain the partition pack key.
3700  */
3701 static void
3702 mxf_type_find (GstTypeFind * tf, gpointer ununsed)
3703 {
3704   static const guint8 partition_pack_key[] =
3705       { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01,
3706     0x01
3707   };
3708   DataScanCtx c = { 0, NULL, 0 };
3709
3710   while (c.offset <= MXF_MAX_PROBE_LENGTH) {
3711     guint i;
3712     if (G_UNLIKELY (!data_scan_ctx_ensure_data (tf, &c, 1024)))
3713       break;
3714
3715     /* look over in chunks of 1kbytes to avoid too much overhead */
3716
3717     for (i = 0; i < 1024 - 16; i++) {
3718       /* Check first byte before calling more expensive memcmp function */
3719       if (G_UNLIKELY (c.data[i] == 0x06
3720               && memcmp (c.data + i, partition_pack_key, 13) == 0)) {
3721         /* Header partition pack? */
3722         if (c.data[i + 13] != 0x02)
3723           goto advance;
3724
3725         /* Partition status */
3726         if (c.data[i + 14] >= 0x05)
3727           goto advance;
3728
3729         /* Reserved, must be 0x00 */
3730         if (c.data[i + 15] != 0x00)
3731           goto advance;
3732
3733         gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, MXF_CAPS);
3734         return;
3735       }
3736     }
3737
3738   advance:
3739     data_scan_ctx_advance (tf, &c, 1024 - 16);
3740   }
3741 }
3742
3743 /*** video/x-dv ***/
3744
3745 static GstStaticCaps dv_caps = GST_STATIC_CAPS ("video/x-dv, "
3746     "systemstream = (boolean) true");
3747 #define DV_CAPS (gst_static_caps_get(&dv_caps))
3748 static void
3749 dv_type_find (GstTypeFind * tf, gpointer private)
3750 {
3751   const guint8 *data;
3752
3753   data = gst_type_find_peek (tf, 0, 5);
3754
3755   /* check for DIF  and DV flag */
3756   if (data && (data[0] == 0x1f) && (data[1] == 0x07) && (data[2] == 0x00)) {
3757     const gchar *format;
3758
3759     if (data[3] & 0x80) {
3760       format = "PAL";
3761     } else {
3762       format = "NTSC";
3763     }
3764
3765     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM, "video/x-dv",
3766         "systemstream", G_TYPE_BOOLEAN, TRUE,
3767         "format", G_TYPE_STRING, format, NULL);
3768   }
3769 }
3770
3771
3772 /*** Ogg variants ***/
3773 static GstStaticCaps ogg_caps =
3774     GST_STATIC_CAPS ("application/ogg;video/ogg;audio/ogg;application/kate");
3775
3776 #define OGG_CAPS (gst_static_caps_get(&ogg_caps))
3777
3778 typedef enum
3779 {
3780   OGG_AUDIO = 0,
3781   OGG_VIDEO,
3782   OGG_KATE,
3783   OGG_OTHER,
3784   OGG_SKELETON,
3785   OGG_ANNODEX,
3786   OGG_NUM
3787 } GstOggStreamType;
3788
3789 static void
3790 ogganx_type_find (GstTypeFind * tf, gpointer private)
3791 {
3792   const gchar *media_type;
3793   DataScanCtx c = { 0, NULL, 0 };
3794   guint ogg_syncs = 0;
3795   guint hdr_count[OGG_NUM] = { 0, };
3796   static const struct
3797   {
3798     const gchar marker[10];
3799     guint8 marker_size;
3800     GstOggStreamType stream_type;
3801   } markers[] = {
3802     {
3803     "\001vorbis", 7, OGG_AUDIO}, {
3804     "\200theora", 7, OGG_VIDEO}, {
3805     "fLaC", 4, OGG_AUDIO}, {
3806     "\177FLAC", 5, OGG_AUDIO}, {
3807     "Speex", 5, OGG_AUDIO}, {
3808     "CMML\0\0\0\0", 8, OGG_OTHER}, {
3809     "PCM     ", 8, OGG_AUDIO}, {
3810     "Annodex", 7, OGG_ANNODEX}, {
3811     "fishead", 7, OGG_SKELETON}, {
3812     "AnxData", 7, OGG_ANNODEX}, {
3813     "CELT    ", 8, OGG_AUDIO}, {
3814     "\200kate\0\0\0", 8, OGG_KATE}, {
3815     "BBCD\0", 5, OGG_VIDEO}, {
3816     "OVP80\1\1", 7, OGG_VIDEO}, {
3817     "OpusHead", 8, OGG_AUDIO}, {
3818     "\001audio\0\0\0", 9, OGG_AUDIO}, {
3819     "\001video\0\0\0", 9, OGG_VIDEO}, {
3820     "\001text\0\0\0", 9, OGG_OTHER}
3821   };
3822
3823   while (c.offset < 4096 && data_scan_ctx_ensure_data (tf, &c, 64)) {
3824     guint size, i;
3825
3826     if (memcmp (c.data, "OggS", 5) != 0)
3827       break;
3828
3829     ++ogg_syncs;
3830
3831     /* check if BOS */
3832     if (c.data[5] != 0x02)
3833       break;
3834
3835     /* headers should only have one segment */
3836     if (c.data[26] != 1)
3837       break;
3838
3839     size = c.data[27];
3840     if (size < 8)
3841       break;
3842
3843     data_scan_ctx_advance (tf, &c, 28);
3844
3845     if (!data_scan_ctx_ensure_data (tf, &c, MAX (size, 8)))
3846       break;
3847
3848     for (i = 0; i < G_N_ELEMENTS (markers); ++i) {
3849       if (memcmp (c.data, markers[i].marker, markers[i].marker_size) == 0) {
3850         ++hdr_count[markers[i].stream_type];
3851         break;
3852       }
3853     }
3854
3855     if (i == G_N_ELEMENTS (markers)) {
3856       GST_MEMDUMP ("unknown Ogg stream marker", c.data, size);
3857       ++hdr_count[OGG_OTHER];
3858     }
3859
3860     data_scan_ctx_advance (tf, &c, size);
3861   }
3862
3863   if (ogg_syncs == 0)
3864     return;
3865
3866   /* We don't bother with annodex types. FIXME: what about XSPF? */
3867   if (hdr_count[OGG_VIDEO] > 0) {
3868     media_type = "video/ogg";
3869   } else if (hdr_count[OGG_AUDIO] > 0) {
3870     media_type = "audio/ogg";
3871   } else if (hdr_count[OGG_KATE] > 0 && hdr_count[OGG_OTHER] == 0) {
3872     media_type = "application/kate";
3873   } else {
3874     media_type = "application/ogg";
3875   }
3876
3877   GST_INFO ("found %s (audio:%u, video:%u, annodex:%u, skeleton:%u, other:%u)",
3878       media_type, hdr_count[OGG_AUDIO], hdr_count[OGG_VIDEO],
3879       hdr_count[OGG_ANNODEX], hdr_count[OGG_SKELETON], hdr_count[OGG_OTHER]);
3880
3881   gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM, media_type, NULL);
3882 }
3883
3884 /*** audio/x-vorbis ***/
3885 static GstStaticCaps vorbis_caps = GST_STATIC_CAPS ("audio/x-vorbis");
3886
3887 #define VORBIS_CAPS (gst_static_caps_get(&vorbis_caps))
3888 static void
3889 vorbis_type_find (GstTypeFind * tf, gpointer private)
3890 {
3891   const guint8 *data = gst_type_find_peek (tf, 0, 30);
3892
3893   if (data) {
3894     guint blocksize_0;
3895     guint blocksize_1;
3896
3897     /* 1 byte packet type (identification=0x01)
3898        6 byte string "vorbis"
3899        4 byte vorbis version */
3900     if (memcmp (data, "\001vorbis\000\000\000\000", 11) != 0)
3901       return;
3902     data += 11;
3903     /* 1 byte channels must be != 0 */
3904     if (data[0] == 0)
3905       return;
3906     data++;
3907     /* 4 byte samplerate must be != 0 */
3908     if (GST_READ_UINT32_LE (data) == 0)
3909       return;
3910     data += 16;
3911     /* blocksize checks */
3912     blocksize_0 = data[0] & 0x0F;
3913     blocksize_1 = (data[0] & 0xF0) >> 4;
3914     if (blocksize_0 > blocksize_1)
3915       return;
3916     if (blocksize_0 < 6 || blocksize_0 > 13)
3917       return;
3918     if (blocksize_1 < 6 || blocksize_1 > 13)
3919       return;
3920     data++;
3921     /* framing bit */
3922     if ((data[0] & 0x01) != 1)
3923       return;
3924     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, VORBIS_CAPS);
3925   }
3926 }
3927
3928 /*** video/x-theora ***/
3929
3930 static GstStaticCaps theora_caps = GST_STATIC_CAPS ("video/x-theora");
3931
3932 #define THEORA_CAPS (gst_static_caps_get(&theora_caps))
3933 static void
3934 theora_type_find (GstTypeFind * tf, gpointer private)
3935 {
3936   const guint8 *data = gst_type_find_peek (tf, 0, 7);   //42);
3937
3938   if (data) {
3939     if (data[0] != 0x80)
3940       return;
3941     if (memcmp (&data[1], "theora", 6) != 0)
3942       return;
3943     /* FIXME: make this more reliable when specs are out */
3944
3945     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, THEORA_CAPS);
3946   }
3947 }
3948
3949 /*** kate ***/
3950 static void
3951 kate_type_find (GstTypeFind * tf, gpointer private)
3952 {
3953   const guint8 *data = gst_type_find_peek (tf, 0, 64);
3954   gchar category[16] = { 0, };
3955
3956   if (G_UNLIKELY (data == NULL))
3957     return;
3958
3959   /* see: http://wiki.xiph.org/index.php/OggKate#Format_specification */
3960   if (G_LIKELY (memcmp (data, "\200kate\0\0\0", 8) != 0))
3961     return;
3962
3963   /* make sure we always have a NUL-terminated string */
3964   memcpy (category, data + 48, 15);
3965   GST_LOG ("kate category: %s", category);
3966   /* canonical categories for subtitles: subtitles, spu-subtitles, SUB, K-SPU */
3967   if (strcmp (category, "subtitles") == 0 || strcmp (category, "SUB") == 0 ||
3968       strcmp (category, "spu-subtitles") == 0 ||
3969       strcmp (category, "K-SPU") == 0) {
3970     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM,
3971         "subtitle/x-kate", NULL);
3972   } else {
3973     gst_type_find_suggest_simple (tf, GST_TYPE_FIND_MAXIMUM,
3974         "application/x-kate", NULL);
3975   }
3976 }
3977
3978 /*** application/x-ogm-video or audio***/
3979
3980 static GstStaticCaps ogmvideo_caps =
3981 GST_STATIC_CAPS ("application/x-ogm-video");
3982 #define OGMVIDEO_CAPS (gst_static_caps_get(&ogmvideo_caps))
3983 static void
3984 ogmvideo_type_find (GstTypeFind * tf, gpointer private)
3985 {
3986   const guint8 *data = gst_type_find_peek (tf, 0, 9);
3987
3988   if (data) {
3989     if (memcmp (data, "\001video\000\000\000", 9) != 0)
3990       return;
3991     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, OGMVIDEO_CAPS);
3992   }
3993 }
3994
3995 static GstStaticCaps ogmaudio_caps =
3996 GST_STATIC_CAPS ("application/x-ogm-audio");
3997 #define OGMAUDIO_CAPS (gst_static_caps_get(&ogmaudio_caps))
3998 static void
3999 ogmaudio_type_find (GstTypeFind * tf, gpointer private)
4000 {
4001   const guint8 *data = gst_type_find_peek (tf, 0, 9);
4002
4003   if (data) {
4004     if (memcmp (data, "\001audio\000\000\000", 9) != 0)
4005       return;
4006     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, OGMAUDIO_CAPS);
4007   }
4008 }
4009
4010 static GstStaticCaps ogmtext_caps = GST_STATIC_CAPS ("application/x-ogm-text");
4011
4012 #define OGMTEXT_CAPS (gst_static_caps_get(&ogmtext_caps))
4013 static void
4014 ogmtext_type_find (GstTypeFind * tf, gpointer private)
4015 {
4016   const guint8 *data = gst_type_find_peek (tf, 0, 9);
4017
4018   if (data) {
4019     if (memcmp (data, "\001text\000\000\000\000", 9) != 0)
4020       return;
4021     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, OGMTEXT_CAPS);
4022   }
4023 }
4024
4025 /*** audio/x-speex ***/
4026
4027 static GstStaticCaps speex_caps = GST_STATIC_CAPS ("audio/x-speex");
4028
4029 #define SPEEX_CAPS (gst_static_caps_get(&speex_caps))
4030 static void
4031 speex_type_find (GstTypeFind * tf, gpointer private)
4032 {
4033   const guint8 *data = gst_type_find_peek (tf, 0, 80);
4034
4035   if (data) {
4036     /* 8 byte string "Speex   "
4037        24 byte speex version string + int */
4038     if (memcmp (data, "Speex   ", 8) != 0)
4039       return;
4040     data += 32;
4041
4042     /* 4 byte header size >= 80 */
4043     if (GST_READ_UINT32_LE (data) < 80)
4044       return;
4045     data += 4;
4046
4047     /* 4 byte sample rate <= 48000 */
4048     if (GST_READ_UINT32_LE (data) > 48000)
4049       return;
4050     data += 4;
4051
4052     /* currently there are only 3 speex modes. */
4053     if (GST_READ_UINT32_LE (data) > 3)
4054       return;
4055     data += 12;
4056
4057     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, SPEEX_CAPS);
4058   }
4059 }
4060
4061 /*** audio/x-celt ***/
4062
4063 static GstStaticCaps celt_caps = GST_STATIC_CAPS ("audio/x-celt");
4064
4065 #define CELT_CAPS (gst_static_caps_get(&celt_caps))
4066 static void
4067 celt_type_find (GstTypeFind * tf, gpointer private)
4068 {
4069   const guint8 *data = gst_type_find_peek (tf, 0, 8);
4070
4071   if (data) {
4072     /* 8 byte string "CELT   " */
4073     if (memcmp (data, "CELT    ", 8) != 0)
4074       return;
4075
4076     /* TODO: Check other values of the CELT header */
4077     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, CELT_CAPS);
4078   }
4079 }
4080
4081 /*** application/x-ogg-skeleton ***/
4082 static GstStaticCaps ogg_skeleton_caps =
4083 GST_STATIC_CAPS ("application/x-ogg-skeleton, parsed=(boolean)FALSE");
4084 #define OGG_SKELETON_CAPS (gst_static_caps_get(&ogg_skeleton_caps))
4085 static void
4086 oggskel_type_find (GstTypeFind * tf, gpointer private)
4087 {
4088   const guint8 *data = gst_type_find_peek (tf, 0, 12);
4089
4090   if (data) {
4091     /* 8 byte string "fishead\0" for the ogg skeleton stream */
4092     if (memcmp (data, "fishead\0", 8) != 0)
4093       return;
4094     data += 8;
4095
4096     /* Require that the header contains version 3.0 */
4097     if (GST_READ_UINT16_LE (data) != 3)
4098       return;
4099     data += 2;
4100     if (GST_READ_UINT16_LE (data) != 0)
4101       return;
4102
4103     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, OGG_SKELETON_CAPS);
4104   }
4105 }
4106
4107 static GstStaticCaps cmml_caps = GST_STATIC_CAPS ("text/x-cmml");
4108
4109 #define CMML_CAPS (gst_static_caps_get(&cmml_caps))
4110 static void
4111 cmml_type_find (GstTypeFind * tf, gpointer private)
4112 {
4113   /* Header is 12 bytes minimum (though we don't check the minor version */
4114   const guint8 *data = gst_type_find_peek (tf, 0, 12);
4115
4116   if (data) {
4117
4118     /* 8 byte string "CMML\0\0\0\0" for the magic number */
4119     if (memcmp (data, "CMML\0\0\0\0", 8) != 0)
4120       return;
4121     data += 8;
4122
4123     /* Require that the header contains at least version 2.0 */
4124     if (GST_READ_UINT16_LE (data) < 2)
4125       return;
4126
4127     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, CMML_CAPS);
4128   }
4129 }
4130
4131 /*** application/x-tar ***/
4132
4133 static GstStaticCaps tar_caps = GST_STATIC_CAPS ("application/x-tar");
4134
4135 #define TAR_CAPS (gst_static_caps_get(&tar_caps))
4136 #define OLDGNU_MAGIC "ustar  "  /* 7 chars and a NUL */
4137 #define NEWGNU_MAGIC "ustar"    /* 5 chars and a NUL */
4138 static void
4139 tar_type_find (GstTypeFind * tf, gpointer unused)
4140 {
4141   const guint8 *data = gst_type_find_peek (tf, 257, 8);
4142
4143   /* of course we are not certain, but we don't want other typefind funcs
4144    * to detect formats of files within the tar archive, e.g. mp3s */
4145   if (data) {
4146     if (memcmp (data, OLDGNU_MAGIC, 8) == 0) {  /* sic */
4147       gst_type_find_suggest (tf, GST_TYPE_FIND_NEARLY_CERTAIN, TAR_CAPS);
4148     } else if (memcmp (data, NEWGNU_MAGIC, 6) == 0 &&   /* sic */
4149         g_ascii_isdigit (data[6]) && g_ascii_isdigit (data[7])) {
4150       gst_type_find_suggest (tf, GST_TYPE_FIND_NEARLY_CERTAIN, TAR_CAPS);
4151     }
4152   }
4153 }
4154
4155 /*** application/x-ar ***/
4156
4157 static GstStaticCaps ar_caps = GST_STATIC_CAPS ("application/x-ar");
4158
4159 #define AR_CAPS (gst_static_caps_get(&ar_caps))
4160 static void
4161 ar_type_find (GstTypeFind * tf, gpointer unused)
4162 {
4163   const guint8 *data = gst_type_find_peek (tf, 0, 24);
4164
4165   if (data && memcmp (data, "!<arch>", 7) == 0) {
4166     gint i;
4167
4168     for (i = 7; i < 24; ++i) {
4169       if (!g_ascii_isprint (data[i]) && data[i] != '\n') {
4170         gst_type_find_suggest (tf, GST_TYPE_FIND_POSSIBLE, AR_CAPS);
4171       }
4172     }
4173
4174     gst_type_find_suggest (tf, GST_TYPE_FIND_NEARLY_CERTAIN, AR_CAPS);
4175   }
4176 }
4177
4178 /*** audio/x-au ***/
4179
4180 /* NOTE: we cannot replace this function with TYPE_FIND_REGISTER_START_WITH,
4181  * as it is only possible to register one typefind factory per 'name'
4182  * (which is in this case the caps), and the first one would be replaced by
4183  * the second one. */
4184 static GstStaticCaps au_caps = GST_STATIC_CAPS ("audio/x-au");
4185
4186 #define AU_CAPS (gst_static_caps_get(&au_caps))
4187 static void
4188 au_type_find (GstTypeFind * tf, gpointer unused)
4189 {
4190   const guint8 *data = gst_type_find_peek (tf, 0, 4);
4191
4192   if (data) {
4193     if (memcmp (data, ".snd", 4) == 0 || memcmp (data, "dns.", 4) == 0) {
4194       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, AU_CAPS);
4195     }
4196   }
4197 }
4198
4199
4200 /*** video/x-nuv ***/
4201
4202 /* NOTE: we cannot replace this function with TYPE_FIND_REGISTER_START_WITH,
4203  * as it is only possible to register one typefind factory per 'name'
4204  * (which is in this case the caps), and the first one would be replaced by
4205  * the second one. */
4206 static GstStaticCaps nuv_caps = GST_STATIC_CAPS ("video/x-nuv");
4207
4208 #define NUV_CAPS (gst_static_caps_get(&nuv_caps))
4209 static void
4210 nuv_type_find (GstTypeFind * tf, gpointer unused)
4211 {
4212   const guint8 *data = gst_type_find_peek (tf, 0, 11);
4213
4214   if (data) {
4215     if (memcmp (data, "MythTVVideo", 11) == 0
4216         || memcmp (data, "NuppelVideo", 11) == 0) {
4217       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, NUV_CAPS);
4218     }
4219   }
4220 }
4221
4222 /*** audio/x-paris ***/
4223 /* NOTE: do not replace this function with two TYPE_FIND_REGISTER_START_WITH */
4224 static GstStaticCaps paris_caps = GST_STATIC_CAPS ("audio/x-paris");
4225
4226 #define PARIS_CAPS (gst_static_caps_get(&paris_caps))
4227 static void
4228 paris_type_find (GstTypeFind * tf, gpointer unused)
4229 {
4230   const guint8 *data = gst_type_find_peek (tf, 0, 4);
4231
4232   if (data) {
4233     if (memcmp (data, " paf", 4) == 0 || memcmp (data, "fap ", 4) == 0) {
4234       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, PARIS_CAPS);
4235     }
4236   }
4237 }
4238
4239 /*** audio/iLBC-sh ***/
4240 /* NOTE: do not replace this function with two TYPE_FIND_REGISTER_START_WITH */
4241 static GstStaticCaps ilbc_caps = GST_STATIC_CAPS ("audio/iLBC-sh");
4242
4243 #define ILBC_CAPS (gst_static_caps_get(&ilbc_caps))
4244 static void
4245 ilbc_type_find (GstTypeFind * tf, gpointer unused)
4246 {
4247   const guint8 *data = gst_type_find_peek (tf, 0, 8);
4248
4249   if (data) {
4250     if (memcmp (data, "#!iLBC30", 8) == 0 || memcmp (data, "#!iLBC20", 8) == 0) {
4251       gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, ILBC_CAPS);
4252     }
4253   }
4254 }
4255
4256 /*** application/x-ms-dos-executable ***/
4257
4258 static GstStaticCaps msdos_caps =
4259 GST_STATIC_CAPS ("application/x-ms-dos-executable");
4260 #define MSDOS_CAPS (gst_static_caps_get(&msdos_caps))
4261 /* see http://www.madchat.org/vxdevl/papers/winsys/pefile/pefile.htm */
4262 static void
4263 msdos_type_find (GstTypeFind * tf, gpointer unused)
4264 {
4265   const guint8 *data = gst_type_find_peek (tf, 0, 64);
4266
4267   if (data && data[0] == 'M' && data[1] == 'Z' &&
4268       GST_READ_UINT16_LE (data + 8) == 4) {
4269     guint32 pe_offset = GST_READ_UINT32_LE (data + 60);
4270
4271     data = gst_type_find_peek (tf, pe_offset, 2);
4272     if (data && data[0] == 'P' && data[1] == 'E') {
4273       gst_type_find_suggest (tf, GST_TYPE_FIND_NEARLY_CERTAIN, MSDOS_CAPS);
4274     }
4275   }
4276 }
4277
4278 /*** application/x-mmsh ***/
4279
4280 static GstStaticCaps mmsh_caps = GST_STATIC_CAPS ("application/x-mmsh");
4281
4282 #define MMSH_CAPS gst_static_caps_get(&mmsh_caps)
4283
4284 /* This is to recognise mssh-over-http */
4285 static void
4286 mmsh_type_find (GstTypeFind * tf, gpointer unused)
4287 {
4288   static const guint8 asf_marker[16] = { 0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66,
4289     0xcf, 0x11, 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c
4290   };
4291
4292   const guint8 *data;
4293
4294   data = gst_type_find_peek (tf, 0, 2 + 2 + 4 + 2 + 2 + 16);
4295   if (data && data[0] == 0x24 && data[1] == 0x48 &&
4296       GST_READ_UINT16_LE (data + 2) > 2 + 2 + 4 + 2 + 2 + 16 &&
4297       memcmp (data + 2 + 2 + 4 + 2 + 2, asf_marker, 16) == 0) {
4298     gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, MMSH_CAPS);
4299   }
4300 }
4301
4302 /*** video/x-dirac ***/
4303
4304 /* NOTE: we cannot replace this function with TYPE_FIND_REGISTER_START_WITH,
4305  * as it is only possible to register one typefind factory per 'name'
4306  * (which is in this case the caps), and the first one would be replaced by
4307  * the second one. */
4308 static GstStaticCaps dirac_caps = GST_STATIC_CAPS ("video/x-dirac");
4309
4310 #define DIRAC_CAPS (gst_static_caps_get(&dirac_caps))
4311 static void
4312 dirac_type_find (GstTypeFind * tf, gpointer unused)
4313 {
4314   const guint8 *data = gst_type_find_peek (tf, 0, 8);
4315
4316   if (data) {
4317     if (memcmp (data, "BBCD", 4) == 0 || memcmp (data, "KW-DIRAC", 8) == 0) {
4318       gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, DIRAC_CAPS);
4319     }
4320   }
4321 }
4322
4323 /*** video/vivo ***/
4324
4325 static GstStaticCaps vivo_caps = GST_STATIC_CAPS ("video/vivo");
4326
4327 #define VIVO_CAPS gst_static_caps_get(&vivo_caps)
4328
4329 static void
4330 vivo_type_find (GstTypeFind * tf, gpointer unused)
4331 {
4332   static const guint8 vivo_marker[] = { 'V', 'e', 'r', 's', 'i', 'o', 'n',
4333     ':', 'V', 'i', 'v', 'o', '/'
4334   };
4335   const guint8 *data;
4336   guint hdr_len, pos;
4337
4338   data = gst_type_find_peek (tf, 0, 1024);
4339   if (data == NULL || data[0] != 0x00)
4340     return;
4341
4342   if ((data[1] & 0x80)) {
4343     if ((data[2] & 0x80))
4344       return;
4345     hdr_len = ((guint) (data[1] & 0x7f)) << 7;
4346     hdr_len += data[2];
4347     if (hdr_len > 2048)
4348       return;
4349     pos = 3;
4350   } else {
4351     hdr_len = data[1];
4352     pos = 2;
4353   }
4354
4355   /* 1008 = 1022 - strlen ("Version:Vivo/") - 1 */
4356   while (pos < 1008 && data[pos] == '\r' && data[pos + 1] == '\n')
4357     pos += 2;
4358
4359   if (memcmp (data + pos, vivo_marker, sizeof (vivo_marker)) == 0) {
4360     gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, VIVO_CAPS);
4361   }
4362 }
4363
4364 /*** XDG MIME typefinder (to avoid false positives mostly) ***/
4365
4366 #ifdef USE_GIO
4367 static void
4368 xdgmime_typefind (GstTypeFind * find, gpointer user_data)
4369 {
4370   gchar *mimetype;
4371   gsize length = 16384;
4372   guint64 tf_length;
4373   const guint8 *data;
4374   gchar *tmp;
4375
4376   if ((tf_length = gst_type_find_get_length (find)) > 0)
4377     length = MIN (length, tf_length);
4378
4379   if ((data = gst_type_find_peek (find, 0, length)) == NULL)
4380     return;
4381
4382   tmp = g_content_type_guess (NULL, data, length, NULL);
4383   if (tmp == NULL || g_content_type_is_unknown (tmp)) {
4384     g_free (tmp);
4385     return;
4386   }
4387
4388   mimetype = g_content_type_get_mime_type (tmp);
4389   g_free (tmp);
4390
4391   if (mimetype == NULL)
4392     return;
4393
4394   GST_DEBUG ("Got mimetype '%s'", mimetype);
4395
4396   /* Ignore audio/video types:
4397    *  - our own typefinders in -base are likely to be better at this
4398    *    (and if they're not, we really want to fix them, that's why we don't
4399    *    report xdg-detected audio/video types at all, not even with a low
4400    *    probability)
4401    *  - we want to detect GStreamer media types and not MIME types
4402    *  - the purpose of this xdg mime finder is mainly to prevent false
4403    *    positives of non-media formats, not to typefind audio/video formats */
4404   if (g_str_has_prefix (mimetype, "audio/") ||
4405       g_str_has_prefix (mimetype, "video/")) {
4406     GST_LOG ("Ignoring audio/video mime type");
4407     g_free (mimetype);
4408     return;
4409   }
4410
4411   /* Again, we mainly want the xdg typefinding to prevent false-positives on
4412    * non-media formats, so suggest the type with a probability that trumps
4413    * uncertain results of our typefinders, but not more than that. */
4414   GST_LOG ("Suggesting '%s' with probability POSSIBLE", mimetype);
4415   gst_type_find_suggest_simple (find, GST_TYPE_FIND_POSSIBLE, mimetype, NULL);
4416   g_free (mimetype);
4417 }
4418 #endif /* USE_GIO */
4419
4420 /*** Windows icon typefinder (to avoid false positives mostly) ***/
4421
4422 static void
4423 windows_icon_typefind (GstTypeFind * find, gpointer user_data)
4424 {
4425   const guint8 *data;
4426   gint64 datalen;
4427   guint16 type, nimages;
4428   gint32 size, offset;
4429
4430   datalen = gst_type_find_get_length (find);
4431   if ((data = gst_type_find_peek (find, 0, 6)) == NULL)
4432     return;
4433
4434   /* header - simple and not enough to rely on it alone */
4435   if (GST_READ_UINT16_LE (data) != 0)
4436     return;
4437   type = GST_READ_UINT16_LE (data + 2);
4438   if (type != 1 && type != 2)
4439     return;
4440   nimages = GST_READ_UINT16_LE (data + 4);
4441   if (nimages == 0)             /* we can assume we can't have an empty image file ? */
4442     return;
4443
4444   /* first image */
4445   if (data[6 + 3] != 0)
4446     return;
4447   if (type == 1) {
4448     guint16 planes = GST_READ_UINT16_LE (data + 6 + 4);
4449     if (planes > 1)
4450       return;
4451   }
4452   size = GST_READ_UINT32_LE (data + 6 + 8);
4453   offset = GST_READ_UINT32_LE (data + 6 + 12);
4454   if (offset < 0 || size <= 0 || size >= datalen || offset >= datalen
4455       || size + offset > datalen)
4456     return;
4457
4458   gst_type_find_suggest_simple (find, GST_TYPE_FIND_NEARLY_CERTAIN,
4459       "image/x-icon", NULL);
4460 }
4461
4462 /*** WAP WBMP typefinder ***/
4463
4464 static void
4465 wbmp_typefind (GstTypeFind * find, gpointer user_data)
4466 {
4467   const guint8 *data;
4468   gint64 datalen;
4469   guint w, h, size;
4470
4471   /* http://en.wikipedia.org/wiki/Wireless_Application_Protocol_Bitmap_Format */
4472   datalen = gst_type_find_get_length (find);
4473   if (datalen == 0)
4474     return;
4475
4476   data = gst_type_find_peek (find, 0, 5);
4477   if (data == NULL)
4478     return;
4479
4480   /* want 0x00 0x00 at start */
4481   if (*data++ != 0 || *data++ != 0)
4482     return;
4483
4484   /* min header size */
4485   size = 4;
4486
4487   /* let's assume max width/height is 65536 */
4488   w = *data++;
4489   if ((w & 0x80)) {
4490     w = (w << 8) | *data++;
4491     if ((w & 0x80))
4492       return;
4493     ++size;
4494     data = gst_type_find_peek (find, 4, 2);
4495     if (data == NULL)
4496       return;
4497   }
4498   h = *data++;
4499   if ((h & 0x80)) {
4500     h = (h << 8) | *data++;
4501     if ((h & 0x80))
4502       return;
4503     ++size;
4504   }
4505
4506   if (w == 0 || h == 0)
4507     return;
4508
4509   /* now add bitmap size */
4510   size += h * (GST_ROUND_UP_8 (w) / 8);
4511
4512   if (datalen == size) {
4513     gst_type_find_suggest_simple (find, GST_TYPE_FIND_POSSIBLE - 10,
4514         "image/vnd.wap.wbmp", NULL);
4515   }
4516 }
4517
4518 /*** DEGAS Atari images (also to avoid false positives, see #625129) ***/
4519 static void
4520 degas_type_find (GstTypeFind * tf, gpointer private)
4521 {
4522   /* No magic, but it should have a fixed size and a few invalid values */
4523   /* http://www.fileformat.info/format/atari/spec/6ecf9f6eb5be494284a47feb8a214687/view.htm */
4524   gint64 len;
4525   const guint8 *data;
4526   guint16 resolution;
4527   int n;
4528
4529   len = gst_type_find_get_length (tf);
4530   if (len < 34)                 /* smallest header of the lot */
4531     return;
4532   data = gst_type_find_peek (tf, 0, 4);
4533   if (G_UNLIKELY (data == NULL))
4534     return;
4535   resolution = GST_READ_UINT16_BE (data);
4536   if (len == 32034) {
4537     /* could be DEGAS */
4538     if (resolution <= 2)
4539       gst_type_find_suggest_simple (tf, GST_TYPE_FIND_POSSIBLE + 5,
4540           "image/x-degas", NULL);
4541   } else if (len == 32066) {
4542     /* could be DEGAS Elite */
4543     if (resolution <= 2) {
4544       data = gst_type_find_peek (tf, len - 16, 8);
4545       if (G_UNLIKELY (data == NULL))
4546         return;
4547       for (n = 0; n < 4; n++) {
4548         if (GST_READ_UINT16_BE (data + n * 2) > 2)
4549           return;
4550       }
4551       gst_type_find_suggest_simple (tf, GST_TYPE_FIND_POSSIBLE + 5,
4552           "image/x-degas", NULL);
4553     }
4554   } else if (len >= 66 && len < 32066) {
4555     /* could be compressed DEGAS Elite, but it's compressed and so we can't rely on size,
4556        it does have 4 16 bytes values near the end that are 0-2 though. */
4557     if ((resolution & 0x8000) && (resolution & 0x7fff) <= 2) {
4558       data = gst_type_find_peek (tf, len - 16, 8);
4559       if (G_UNLIKELY (data == NULL))
4560         return;
4561       for (n = 0; n < 4; n++) {
4562         if (GST_READ_UINT16_BE (data + n * 2) > 2)
4563           return;
4564       }
4565       gst_type_find_suggest_simple (tf, GST_TYPE_FIND_POSSIBLE + 5,
4566           "image/x-degas", NULL);
4567     }
4568   }
4569 }
4570
4571 /*** DVD ISO images (looks like H.264, see #674069) ***/
4572 static void
4573 dvdiso_type_find (GstTypeFind * tf, gpointer private)
4574 {
4575   /* 0x8000 bytes of zeros, then "\001CD001" */
4576   gint64 len;
4577   const guint8 *data;
4578
4579   len = gst_type_find_get_length (tf);
4580   if (len < 0x8006)
4581     return;
4582   data = gst_type_find_peek (tf, 0, 0x8006);
4583   if (G_UNLIKELY (data == NULL))
4584     return;
4585   for (len = 0; len < 0x8000; len++)
4586     if (data[len])
4587       return;
4588   /* Can the '1' be anything else ? My three samples all have '1'. */
4589   if (memcmp (data + 0x8000, "\001CD001", 6))
4590     return;
4591
4592   /* May need more inspection, we may be able to demux some of them */
4593   gst_type_find_suggest_simple (tf, GST_TYPE_FIND_LIKELY,
4594       "application/octet-stream", NULL);
4595 }
4596
4597 /*** generic typefind for streams that have some data at a specific position***/
4598 typedef struct
4599 {
4600   const guint8 *data;
4601   guint size;
4602   guint probability;
4603   GstCaps *caps;
4604 }
4605 GstTypeFindData;
4606
4607 static void
4608 start_with_type_find (GstTypeFind * tf, gpointer private)
4609 {
4610   GstTypeFindData *start_with = (GstTypeFindData *) private;
4611   const guint8 *data;
4612
4613   GST_LOG ("trying to find mime type %s with the first %u bytes of data",
4614       gst_structure_get_name (gst_caps_get_structure (start_with->caps, 0)),
4615       start_with->size);
4616   data = gst_type_find_peek (tf, 0, start_with->size);
4617   if (data && memcmp (data, start_with->data, start_with->size) == 0) {
4618     gst_type_find_suggest (tf, start_with->probability, start_with->caps);
4619   }
4620 }
4621
4622 static void
4623 sw_data_destroy (GstTypeFindData * sw_data)
4624 {
4625   if (G_LIKELY (sw_data->caps != NULL))
4626     gst_caps_unref (sw_data->caps);
4627   g_free (sw_data);
4628 }
4629
4630 #define TYPE_FIND_REGISTER_START_WITH(plugin,name,rank,ext,_data,_size,_probability)\
4631 G_BEGIN_DECLS{                                                          \
4632   GstTypeFindData *sw_data = g_new (GstTypeFindData, 1);                \
4633   sw_data->data = (const guint8 *)_data;                                \
4634   sw_data->size = _size;                                                \
4635   sw_data->probability = _probability;                                  \
4636   sw_data->caps = gst_caps_new_empty_simple (name);                     \
4637   if (!gst_type_find_register (plugin, name, rank, start_with_type_find,\
4638                      ext, sw_data->caps, sw_data,                       \
4639                      (GDestroyNotify) (sw_data_destroy))) {             \
4640     gst_caps_unref (sw_data->caps);                                     \
4641     g_free (sw_data);                                                   \
4642   }                                                                     \
4643 }G_END_DECLS
4644
4645 /*** same for riff types ***/
4646
4647 static void
4648 riff_type_find (GstTypeFind * tf, gpointer private)
4649 {
4650   GstTypeFindData *riff_data = (GstTypeFindData *) private;
4651   const guint8 *data = gst_type_find_peek (tf, 0, 12);
4652
4653   if (data && (memcmp (data, "RIFF", 4) == 0 || memcmp (data, "AVF0", 4) == 0)) {
4654     data += 8;
4655     if (memcmp (data, riff_data->data, 4) == 0)
4656       gst_type_find_suggest (tf, riff_data->probability, riff_data->caps);
4657   }
4658 }
4659
4660 #define TYPE_FIND_REGISTER_RIFF(plugin,name,rank,ext,_data)             \
4661 G_BEGIN_DECLS{                                                          \
4662   GstTypeFindData *sw_data = g_new (GstTypeFindData, 1);                \
4663   sw_data->data = (gpointer)_data;                                      \
4664   sw_data->size = 4;                                                    \
4665   sw_data->probability = GST_TYPE_FIND_MAXIMUM;                         \
4666   sw_data->caps = gst_caps_new_empty_simple (name);                     \
4667   if (!gst_type_find_register (plugin, name, rank, riff_type_find,      \
4668                       ext, sw_data->caps, sw_data,                      \
4669                       (GDestroyNotify) (sw_data_destroy))) {            \
4670     gst_caps_unref (sw_data->caps);                                     \
4671     g_free (sw_data);                                                   \
4672   }                                                                     \
4673 }G_END_DECLS
4674
4675
4676 /*** plugin initialization ***/
4677
4678 #define TYPE_FIND_REGISTER(plugin,name,rank,func,ext,caps,priv,notify) \
4679 G_BEGIN_DECLS{\
4680   if (!gst_type_find_register (plugin, name, rank, func, ext, caps, priv, notify))\
4681     return FALSE; \
4682 }G_END_DECLS
4683
4684
4685 static gboolean
4686 plugin_init (GstPlugin * plugin)
4687 {
4688   /* can't initialize this via a struct as caps can't be statically initialized */
4689
4690   GST_DEBUG_CATEGORY_INIT (type_find_debug, "typefindfunctions",
4691       GST_DEBUG_FG_GREEN | GST_DEBUG_BG_RED, "generic type find functions");
4692
4693   /* note: asx/wax/wmx are XML files, asf doesn't handle them */
4694   /* must use strings, macros don't accept initializers */
4695   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-ms-asf", GST_RANK_SECONDARY,
4696       "asf,wm,wma,wmv",
4697       "\060\046\262\165\216\146\317\021\246\331\000\252\000\142\316\154", 16,
4698       GST_TYPE_FIND_MAXIMUM);
4699   TYPE_FIND_REGISTER (plugin, "audio/x-musepack", GST_RANK_PRIMARY,
4700       musepack_type_find, "mpc,mpp,mp+", MUSEPACK_CAPS, NULL, NULL);
4701   TYPE_FIND_REGISTER (plugin, "audio/x-au", GST_RANK_MARGINAL,
4702       au_type_find, "au,snd", AU_CAPS, NULL, NULL);
4703   TYPE_FIND_REGISTER_RIFF (plugin, "video/x-msvideo", GST_RANK_PRIMARY,
4704       "avi", "AVI ");
4705   TYPE_FIND_REGISTER_RIFF (plugin, "audio/qcelp", GST_RANK_PRIMARY,
4706       "qcp", "QLCM");
4707   TYPE_FIND_REGISTER_RIFF (plugin, "video/x-cdxa", GST_RANK_PRIMARY,
4708       "dat", "CDXA");
4709   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-vcd", GST_RANK_PRIMARY,
4710       "dat", "\000\377\377\377\377\377\377\377\377\377\377\000", 12,
4711       GST_TYPE_FIND_MAXIMUM);
4712   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-imelody", GST_RANK_PRIMARY,
4713       "imy,ime,imelody", "BEGIN:IMELODY", 13, GST_TYPE_FIND_MAXIMUM);
4714 #if 0
4715   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-smoke", GST_RANK_PRIMARY,
4716       NULL, "\x80smoke\x00\x01\x00", 6, GST_TYPE_FIND_MAXIMUM);
4717 #endif
4718   TYPE_FIND_REGISTER (plugin, "audio/midi", GST_RANK_PRIMARY, mid_type_find,
4719       "mid,midi", MID_CAPS, NULL, NULL);
4720   TYPE_FIND_REGISTER_RIFF (plugin, "audio/riff-midi", GST_RANK_PRIMARY,
4721       "mid,midi", "RMID");
4722   TYPE_FIND_REGISTER (plugin, "audio/mobile-xmf", GST_RANK_PRIMARY,
4723       mxmf_type_find, "mxmf", MXMF_CAPS, NULL, NULL);
4724   TYPE_FIND_REGISTER (plugin, "video/x-fli", GST_RANK_MARGINAL, flx_type_find,
4725       "flc,fli", FLX_CAPS, NULL, NULL);
4726   TYPE_FIND_REGISTER (plugin, "application/x-id3v2", GST_RANK_PRIMARY + 103,
4727       id3v2_type_find, "mp3,mp2,mp1,mpga,ogg,flac,tta", ID3_CAPS, NULL, NULL);
4728   TYPE_FIND_REGISTER (plugin, "application/x-id3v1", GST_RANK_PRIMARY + 101,
4729       id3v1_type_find, "mp3,mp2,mp1,mpga,ogg,flac,tta", ID3_CAPS, NULL, NULL);
4730   TYPE_FIND_REGISTER (plugin, "application/x-apetag", GST_RANK_PRIMARY + 102,
4731       apetag_type_find, "mp3,ape,mpc,wv", APETAG_CAPS, NULL, NULL);
4732   TYPE_FIND_REGISTER (plugin, "audio/x-ttafile", GST_RANK_PRIMARY,
4733       tta_type_find, "tta", TTA_CAPS, NULL, NULL);
4734   TYPE_FIND_REGISTER (plugin, "audio/x-mod", GST_RANK_SECONDARY, mod_type_find,
4735       "669,amf,dsm,gdm,far,imf,it,med,mod,mtm,okt,sam,s3m,stm,stx,ult,xm",
4736       MOD_CAPS, NULL, NULL);
4737   TYPE_FIND_REGISTER (plugin, "audio/mpeg", GST_RANK_PRIMARY, mp3_type_find,
4738       "mp3,mp2,mp1,mpga", MP3_CAPS, NULL, NULL);
4739   TYPE_FIND_REGISTER (plugin, "audio/x-ac3", GST_RANK_PRIMARY, ac3_type_find,
4740       "ac3,eac3", AC3_CAPS, NULL, NULL);
4741   TYPE_FIND_REGISTER (plugin, "audio/x-dts", GST_RANK_SECONDARY, dts_type_find,
4742       "dts", DTS_CAPS, NULL, NULL);
4743   TYPE_FIND_REGISTER (plugin, "audio/x-gsm", GST_RANK_PRIMARY, NULL, "gsm",
4744       GSM_CAPS, NULL, NULL);
4745   TYPE_FIND_REGISTER (plugin, "video/mpeg-sys", GST_RANK_PRIMARY,
4746       mpeg_sys_type_find, "mpe,mpeg,mpg", MPEG_SYS_CAPS, NULL, NULL);
4747   TYPE_FIND_REGISTER (plugin, "video/mpegts", GST_RANK_PRIMARY,
4748       mpeg_ts_type_find, "ts,mts", MPEGTS_CAPS, NULL, NULL);
4749   TYPE_FIND_REGISTER (plugin, "application/ogg", GST_RANK_PRIMARY,
4750       ogganx_type_find, "ogg,oga,ogv,ogm,ogx,spx,anx,axa,axv", OGG_CAPS,
4751       NULL, NULL);
4752   TYPE_FIND_REGISTER (plugin, "video/mpeg-elementary", GST_RANK_MARGINAL,
4753       mpeg_video_stream_type_find, "mpv,mpeg,mpg", MPEG_VIDEO_CAPS, NULL, NULL);
4754   TYPE_FIND_REGISTER (plugin, "video/mpeg4", GST_RANK_PRIMARY,
4755       mpeg4_video_type_find, "m4v", MPEG_VIDEO_CAPS, NULL, NULL);
4756   TYPE_FIND_REGISTER (plugin, "video/x-h263", GST_RANK_SECONDARY,
4757       h263_video_type_find, "h263,263", H263_VIDEO_CAPS, NULL, NULL);
4758   TYPE_FIND_REGISTER (plugin, "video/x-h264", GST_RANK_PRIMARY,
4759       h264_video_type_find, "h264,x264,264", H264_VIDEO_CAPS, NULL, NULL);
4760   TYPE_FIND_REGISTER (plugin, "video/x-nuv", GST_RANK_SECONDARY, nuv_type_find,
4761       "nuv", NUV_CAPS, NULL, NULL);
4762
4763   /* ISO formats */
4764   TYPE_FIND_REGISTER (plugin, "audio/x-m4a", GST_RANK_PRIMARY, m4a_type_find,
4765       "m4a", M4A_CAPS, NULL, NULL);
4766   TYPE_FIND_REGISTER (plugin, "application/x-3gp", GST_RANK_PRIMARY,
4767       q3gp_type_find, "3gp", Q3GP_CAPS, NULL, NULL);
4768   TYPE_FIND_REGISTER (plugin, "video/quicktime", GST_RANK_SECONDARY,
4769       qt_type_find, "mov", QT_CAPS, NULL, NULL);
4770   TYPE_FIND_REGISTER (plugin, "image/x-quicktime", GST_RANK_SECONDARY,
4771       qtif_type_find, "qif,qtif,qti", QTIF_CAPS, NULL, NULL);
4772   TYPE_FIND_REGISTER (plugin, "image/jp2", GST_RANK_PRIMARY,
4773       jp2_type_find, "jp2", JP2_CAPS, NULL, NULL);
4774   TYPE_FIND_REGISTER (plugin, "video/mj2", GST_RANK_PRIMARY,
4775       jp2_type_find, "mj2", MJ2_CAPS, NULL, NULL);
4776
4777   TYPE_FIND_REGISTER (plugin, "text/html", GST_RANK_SECONDARY, html_type_find,
4778       "htm,html", HTML_CAPS, NULL, NULL);
4779   TYPE_FIND_REGISTER_START_WITH (plugin, "application/vnd.rn-realmedia",
4780       GST_RANK_SECONDARY, "ra,ram,rm,rmvb", ".RMF", 4, GST_TYPE_FIND_MAXIMUM);
4781   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-pn-realaudio",
4782       GST_RANK_SECONDARY, "ra,ram,rm,rmvb", ".ra\375", 4,
4783       GST_TYPE_FIND_MAXIMUM);
4784   TYPE_FIND_REGISTER (plugin, "application/x-shockwave-flash",
4785       GST_RANK_SECONDARY, swf_type_find, "swf,swfl", SWF_CAPS, NULL, NULL);
4786   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-flv", GST_RANK_SECONDARY,
4787       "flv", "FLV", 3, GST_TYPE_FIND_MAXIMUM);
4788   TYPE_FIND_REGISTER (plugin, "text/plain", GST_RANK_MARGINAL, utf8_type_find,
4789       "txt", UTF8_CAPS, NULL, NULL);
4790   TYPE_FIND_REGISTER (plugin, "text/utf-16", GST_RANK_MARGINAL, utf16_type_find,
4791       "txt", UTF16_CAPS, NULL, NULL);
4792   TYPE_FIND_REGISTER (plugin, "text/utf-32", GST_RANK_MARGINAL, utf32_type_find,
4793       "txt", UTF32_CAPS, NULL, NULL);
4794   TYPE_FIND_REGISTER (plugin, "text/uri-list", GST_RANK_MARGINAL, uri_type_find,
4795       "ram", URI_CAPS, NULL, NULL);
4796   TYPE_FIND_REGISTER (plugin, "application/x-hls", GST_RANK_MARGINAL,
4797       hls_type_find, "m3u8", HLS_CAPS, NULL, NULL);
4798   TYPE_FIND_REGISTER (plugin, "application/sdp", GST_RANK_SECONDARY,
4799       sdp_type_find, "sdp", SDP_CAPS, NULL, NULL);
4800   TYPE_FIND_REGISTER (plugin, "application/smil", GST_RANK_SECONDARY,
4801       smil_type_find, "smil", SMIL_CAPS, NULL, NULL);
4802   TYPE_FIND_REGISTER (plugin, "application/xml", GST_RANK_MARGINAL,
4803       xml_type_find, "xml", GENERIC_XML_CAPS, NULL, NULL);
4804   TYPE_FIND_REGISTER_RIFF (plugin, "audio/x-wav", GST_RANK_PRIMARY, "wav",
4805       "WAVE");
4806   TYPE_FIND_REGISTER (plugin, "audio/x-aiff", GST_RANK_SECONDARY,
4807       aiff_type_find, "aiff,aif,aifc", AIFF_CAPS, NULL, NULL);
4808   TYPE_FIND_REGISTER (plugin, "audio/x-svx", GST_RANK_SECONDARY, svx_type_find,
4809       "iff,svx", SVX_CAPS, NULL, NULL);
4810   TYPE_FIND_REGISTER (plugin, "audio/x-paris", GST_RANK_SECONDARY,
4811       paris_type_find, "paf", PARIS_CAPS, NULL, NULL);
4812   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-nist", GST_RANK_SECONDARY,
4813       "nist", "NIST", 4, GST_TYPE_FIND_MAXIMUM);
4814   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-voc", GST_RANK_SECONDARY,
4815       "voc", "Creative", 8, GST_TYPE_FIND_MAXIMUM);
4816   TYPE_FIND_REGISTER (plugin, "audio/x-sds", GST_RANK_SECONDARY, sds_type_find,
4817       "sds", SDS_CAPS, NULL, NULL);
4818   TYPE_FIND_REGISTER (plugin, "audio/x-ircam", GST_RANK_SECONDARY,
4819       ircam_type_find, "sf", IRCAM_CAPS, NULL, NULL);
4820   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-w64", GST_RANK_SECONDARY,
4821       "w64", "riff", 4, GST_TYPE_FIND_MAXIMUM);
4822   TYPE_FIND_REGISTER (plugin, "audio/x-shorten", GST_RANK_SECONDARY,
4823       shn_type_find, "shn", SHN_CAPS, NULL, NULL);
4824   TYPE_FIND_REGISTER (plugin, "application/x-ape", GST_RANK_SECONDARY,
4825       ape_type_find, "ape", APE_CAPS, NULL, NULL);
4826   TYPE_FIND_REGISTER (plugin, "image/jpeg", GST_RANK_PRIMARY + 15,
4827       jpeg_type_find, "jpg,jpe,jpeg", JPEG_CAPS, NULL, NULL);
4828   TYPE_FIND_REGISTER_START_WITH (plugin, "image/gif", GST_RANK_PRIMARY, "gif",
4829       "GIF8", 4, GST_TYPE_FIND_MAXIMUM);
4830   TYPE_FIND_REGISTER_START_WITH (plugin, "image/png", GST_RANK_PRIMARY + 14,
4831       "png", "\211PNG\015\012\032\012", 8, GST_TYPE_FIND_MAXIMUM);
4832   TYPE_FIND_REGISTER (plugin, "image/bmp", GST_RANK_PRIMARY, bmp_type_find,
4833       "bmp", BMP_CAPS, NULL, NULL);
4834   TYPE_FIND_REGISTER (plugin, "image/tiff", GST_RANK_PRIMARY, tiff_type_find,
4835       "tif,tiff", TIFF_CAPS, NULL, NULL);
4836   TYPE_FIND_REGISTER (plugin, "image/x-portable-pixmap", GST_RANK_SECONDARY,
4837       pnm_type_find, "pnm,ppm,pgm,pbm", PNM_CAPS, NULL, NULL);
4838   TYPE_FIND_REGISTER (plugin, "video/x-matroska", GST_RANK_PRIMARY,
4839       matroska_type_find, "mkv,mka,mk3d,webm", MATROSKA_CAPS, NULL, NULL);
4840   TYPE_FIND_REGISTER (plugin, "application/mxf", GST_RANK_PRIMARY,
4841       mxf_type_find, "mxf", MXF_CAPS, NULL, NULL);
4842   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-mve", GST_RANK_SECONDARY,
4843       "mve", "Interplay MVE File\032\000\032\000\000\001\063\021", 26,
4844       GST_TYPE_FIND_MAXIMUM);
4845   TYPE_FIND_REGISTER (plugin, "video/x-dv", GST_RANK_SECONDARY, dv_type_find,
4846       "dv,dif", DV_CAPS, NULL, NULL);
4847   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-amr-nb-sh", GST_RANK_PRIMARY,
4848       "amr", "#!AMR", 5, GST_TYPE_FIND_LIKELY);
4849   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-amr-wb-sh", GST_RANK_PRIMARY,
4850       "amr", "#!AMR-WB", 7, GST_TYPE_FIND_MAXIMUM);
4851   TYPE_FIND_REGISTER (plugin, "audio/iLBC-sh", GST_RANK_PRIMARY, ilbc_type_find,
4852       "ilbc", ILBC_CAPS, NULL, NULL);
4853   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-sid", GST_RANK_MARGINAL,
4854       "sid", "PSID", 4, GST_TYPE_FIND_MAXIMUM);
4855   TYPE_FIND_REGISTER_START_WITH (plugin, "image/x-xcf", GST_RANK_SECONDARY,
4856       "xcf", "gimp xcf", 8, GST_TYPE_FIND_MAXIMUM);
4857   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-mng", GST_RANK_SECONDARY,
4858       "mng", "\212MNG\015\012\032\012", 8, GST_TYPE_FIND_MAXIMUM);
4859   TYPE_FIND_REGISTER_START_WITH (plugin, "image/x-jng", GST_RANK_SECONDARY,
4860       "jng", "\213JNG\015\012\032\012", 8, GST_TYPE_FIND_MAXIMUM);
4861   TYPE_FIND_REGISTER_START_WITH (plugin, "image/x-xpixmap", GST_RANK_SECONDARY,
4862       "xpm", "/* XPM */", 9, GST_TYPE_FIND_MAXIMUM);
4863   TYPE_FIND_REGISTER_START_WITH (plugin, "image/x-sun-raster",
4864       GST_RANK_SECONDARY, "ras", "\131\246\152\225", 4, GST_TYPE_FIND_MAXIMUM);
4865   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-bzip",
4866       GST_RANK_SECONDARY, "bz2", "BZh", 3, GST_TYPE_FIND_LIKELY);
4867   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-gzip",
4868       GST_RANK_SECONDARY, "gz", "\037\213", 2, GST_TYPE_FIND_LIKELY);
4869   TYPE_FIND_REGISTER_START_WITH (plugin, "application/zip", GST_RANK_SECONDARY,
4870       "zip", "PK\003\004", 4, GST_TYPE_FIND_LIKELY);
4871   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-compress",
4872       GST_RANK_SECONDARY, "Z", "\037\235", 2, GST_TYPE_FIND_LIKELY);
4873   TYPE_FIND_REGISTER (plugin, "subtitle/x-kate", GST_RANK_MARGINAL,
4874       kate_type_find, NULL, NULL, NULL, NULL);
4875   TYPE_FIND_REGISTER (plugin, "audio/x-flac", GST_RANK_PRIMARY, flac_type_find,
4876       "flac", FLAC_CAPS, NULL, NULL);
4877   TYPE_FIND_REGISTER (plugin, "audio/x-vorbis", GST_RANK_PRIMARY,
4878       vorbis_type_find, NULL, VORBIS_CAPS, NULL, NULL);
4879   TYPE_FIND_REGISTER (plugin, "video/x-theora", GST_RANK_PRIMARY,
4880       theora_type_find, NULL, THEORA_CAPS, NULL, NULL);
4881   TYPE_FIND_REGISTER (plugin, "application/x-ogm-video", GST_RANK_PRIMARY,
4882       ogmvideo_type_find, NULL, OGMVIDEO_CAPS, NULL, NULL);
4883   TYPE_FIND_REGISTER (plugin, "application/x-ogm-audio", GST_RANK_PRIMARY,
4884       ogmaudio_type_find, NULL, OGMAUDIO_CAPS, NULL, NULL);
4885   TYPE_FIND_REGISTER (plugin, "application/x-ogm-text", GST_RANK_PRIMARY,
4886       ogmtext_type_find, NULL, OGMTEXT_CAPS, NULL, NULL);
4887   TYPE_FIND_REGISTER (plugin, "audio/x-speex", GST_RANK_PRIMARY,
4888       speex_type_find, NULL, SPEEX_CAPS, NULL, NULL);
4889   TYPE_FIND_REGISTER (plugin, "audio/x-celt", GST_RANK_PRIMARY, celt_type_find,
4890       NULL, CELT_CAPS, NULL, NULL);
4891   TYPE_FIND_REGISTER (plugin, "application/x-ogg-skeleton", GST_RANK_PRIMARY,
4892       oggskel_type_find, NULL, OGG_SKELETON_CAPS, NULL, NULL);
4893   TYPE_FIND_REGISTER (plugin, "text/x-cmml", GST_RANK_PRIMARY, cmml_type_find,
4894       NULL, CMML_CAPS, NULL, NULL);
4895   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-executable",
4896       GST_RANK_MARGINAL, NULL, "\177ELF", 4, GST_TYPE_FIND_MAXIMUM);
4897   TYPE_FIND_REGISTER (plugin, "audio/aac", GST_RANK_SECONDARY, aac_type_find,
4898       "aac,adts,adif,loas", AAC_CAPS, NULL, NULL);
4899   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-spc", GST_RANK_SECONDARY,
4900       "spc", "SNES-SPC700 Sound File Data", 27, GST_TYPE_FIND_MAXIMUM);
4901   TYPE_FIND_REGISTER (plugin, "audio/x-wavpack", GST_RANK_SECONDARY,
4902       wavpack_type_find, "wv,wvp", WAVPACK_CAPS, NULL, NULL);
4903   TYPE_FIND_REGISTER (plugin, "audio/x-wavpack-correction", GST_RANK_SECONDARY,
4904       wavpack_type_find, "wvc", WAVPACK_CORRECTION_CAPS, NULL, NULL);
4905   TYPE_FIND_REGISTER (plugin, "application/postscript", GST_RANK_SECONDARY,
4906       postscript_type_find, "ps", POSTSCRIPT_CAPS, NULL, NULL);
4907   TYPE_FIND_REGISTER (plugin, "image/svg+xml", GST_RANK_SECONDARY,
4908       svg_type_find, "svg", SVG_CAPS, NULL, NULL);
4909   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-rar",
4910       GST_RANK_SECONDARY, "rar", "Rar!", 4, GST_TYPE_FIND_LIKELY);
4911   TYPE_FIND_REGISTER (plugin, "application/x-tar", GST_RANK_SECONDARY,
4912       tar_type_find, "tar", TAR_CAPS, NULL, NULL);
4913   TYPE_FIND_REGISTER (plugin, "application/x-ar", GST_RANK_SECONDARY,
4914       ar_type_find, "a", AR_CAPS, NULL, NULL);
4915   TYPE_FIND_REGISTER (plugin, "application/x-ms-dos-executable",
4916       GST_RANK_SECONDARY, msdos_type_find, "dll,exe,ocx,sys,scr,msstyles,cpl",
4917       MSDOS_CAPS, NULL, NULL);
4918   TYPE_FIND_REGISTER (plugin, "video/x-dirac", GST_RANK_PRIMARY,
4919       dirac_type_find, NULL, DIRAC_CAPS, NULL, NULL);
4920   TYPE_FIND_REGISTER (plugin, "multipart/x-mixed-replace", GST_RANK_SECONDARY,
4921       multipart_type_find, NULL, MULTIPART_CAPS, NULL, NULL);
4922   TYPE_FIND_REGISTER (plugin, "application/x-mmsh", GST_RANK_SECONDARY,
4923       mmsh_type_find, NULL, MMSH_CAPS, NULL, NULL);
4924   TYPE_FIND_REGISTER (plugin, "video/vivo", GST_RANK_SECONDARY, vivo_type_find,
4925       "viv", VIVO_CAPS, NULL, NULL);
4926   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-nsf", GST_RANK_SECONDARY,
4927       "nsf", "NESM\x1a", 5, GST_TYPE_FIND_MAXIMUM);
4928   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-gym", GST_RANK_SECONDARY,
4929       "gym", "GYMX", 4, GST_TYPE_FIND_MAXIMUM);
4930   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-ay", GST_RANK_SECONDARY, "ay",
4931       "ZXAYEMUL", 8, GST_TYPE_FIND_MAXIMUM);
4932   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-gbs", GST_RANK_SECONDARY,
4933       "gbs", "GBS\x01", 4, GST_TYPE_FIND_MAXIMUM);
4934   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-vgm", GST_RANK_SECONDARY,
4935       "vgm", "Vgm\x20", 4, GST_TYPE_FIND_MAXIMUM);
4936   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-sap", GST_RANK_SECONDARY,
4937       "sap", "SAP\x0d\x0a" "AUTHOR\x20", 12, GST_TYPE_FIND_MAXIMUM);
4938   TYPE_FIND_REGISTER_START_WITH (plugin, "video/x-ivf", GST_RANK_SECONDARY,
4939       "ivf", "DKIF", 4, GST_TYPE_FIND_NEARLY_CERTAIN);
4940   TYPE_FIND_REGISTER_START_WITH (plugin, "audio/x-kss", GST_RANK_SECONDARY,
4941       "kss", "KSSX\0", 5, GST_TYPE_FIND_MAXIMUM);
4942   TYPE_FIND_REGISTER_START_WITH (plugin, "application/pdf", GST_RANK_SECONDARY,
4943       "pdf", "%PDF-", 5, GST_TYPE_FIND_LIKELY);
4944   TYPE_FIND_REGISTER_START_WITH (plugin, "application/msword",
4945       GST_RANK_SECONDARY, "doc", "\320\317\021\340\241\261\032\341", 8,
4946       GST_TYPE_FIND_LIKELY);
4947   /* Mac OS X .DS_Store files tend to be taken for video/mpeg */
4948   TYPE_FIND_REGISTER_START_WITH (plugin, "application/octet-stream",
4949       GST_RANK_SECONDARY, "DS_Store", "\000\000\000\001Bud1", 8,
4950       GST_TYPE_FIND_LIKELY);
4951   TYPE_FIND_REGISTER_START_WITH (plugin, "image/vnd.adobe.photoshop",
4952       GST_RANK_SECONDARY, "psd", "8BPS\000\001\000\000\000\000", 10,
4953       GST_TYPE_FIND_LIKELY);
4954   TYPE_FIND_REGISTER (plugin, "image/vnd.wap.wbmp", GST_RANK_MARGINAL,
4955       wbmp_typefind, NULL, NULL, NULL, NULL);
4956   TYPE_FIND_REGISTER_START_WITH (plugin, "application/x-yuv4mpeg",
4957       GST_RANK_SECONDARY, "y4m", "YUV4MPEG2 ", 10, GST_TYPE_FIND_LIKELY);
4958   TYPE_FIND_REGISTER (plugin, "image/x-icon", GST_RANK_MARGINAL,
4959       windows_icon_typefind, NULL, NULL, NULL, NULL);
4960
4961 #ifdef USE_GIO
4962   TYPE_FIND_REGISTER (plugin, "xdgmime-base", GST_RANK_MARGINAL,
4963       xdgmime_typefind, NULL, NULL, NULL, NULL);
4964 #endif
4965
4966   TYPE_FIND_REGISTER (plugin, "image/x-degas", GST_RANK_MARGINAL,
4967       degas_type_find, NULL, NULL, NULL, NULL);
4968   TYPE_FIND_REGISTER (plugin, "application/octet-stream", GST_RANK_MARGINAL,
4969       dvdiso_type_find, NULL, NULL, NULL, NULL);
4970
4971   return TRUE;
4972 }
4973
4974 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
4975     GST_VERSION_MINOR,
4976     typefindfunctions,
4977     "default typefind functions",
4978     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)