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