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