Add support for subtitle files with UTF-8 BOM at the beginning by simple stripping...
[platform/upstream/gstreamer.git] / gst / subparse / gstsubparse.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) 2004 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
4  * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <string.h>
27 #include <stdlib.h>
28 #include <sys/types.h>
29 #include <regex.h>
30
31 #include "gstsubparse.h"
32 #include "gstssaparse.h"
33 #include "samiparse.h"
34 #include "tmplayerparse.h"
35 #include "mpl2parse.h"
36
37 GST_DEBUG_CATEGORY (sub_parse_debug);
38
39 #define DEFAULT_ENCODING   NULL
40
41 enum
42 {
43   PROP_0,
44   PROP_ENCODING
45 };
46
47 static void
48 gst_sub_parse_set_property (GObject * object, guint prop_id,
49     const GValue * value, GParamSpec * pspec);
50 static void
51 gst_sub_parse_get_property (GObject * object, guint prop_id,
52     GValue * value, GParamSpec * pspec);
53
54
55 static const GstElementDetails sub_parse_details =
56 GST_ELEMENT_DETAILS ("Subtitle parser",
57     "Codec/Parser/Subtitle",
58     "Parses subtitle (.sub) files into text streams",
59     "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
60     "Ronald S. Bultje <rbultje@ronald.bitfreak.net>");
61
62 #ifndef GST_DISABLE_XML
63 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
64     GST_PAD_SINK,
65     GST_PAD_ALWAYS,
66     GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
67         "application/x-subtitle-tmplayer; application/x-subtitle-mpl2")
68     );
69 #else
70 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
71     GST_PAD_SINK,
72     GST_PAD_ALWAYS,
73     GST_STATIC_CAPS ("application/x-subtitle")
74     );
75 #endif
76
77 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
78     GST_PAD_SRC,
79     GST_PAD_ALWAYS,
80     GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
81     );
82
83 static void gst_sub_parse_base_init (GstSubParseClass * klass);
84 static void gst_sub_parse_class_init (GstSubParseClass * klass);
85 static void gst_sub_parse_init (GstSubParse * subparse);
86
87 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
88 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
89
90 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
91     GstStateChange transition);
92
93 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
94
95 static GstElementClass *parent_class = NULL;
96
97 GType
98 gst_sub_parse_get_type (void)
99 {
100   static GType sub_parse_type = 0;
101
102   if (!sub_parse_type) {
103     static const GTypeInfo sub_parse_info = {
104       sizeof (GstSubParseClass),
105       (GBaseInitFunc) gst_sub_parse_base_init,
106       NULL,
107       (GClassInitFunc) gst_sub_parse_class_init,
108       NULL,
109       NULL,
110       sizeof (GstSubParse),
111       0,
112       (GInstanceInitFunc) gst_sub_parse_init,
113     };
114
115     sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
116         "GstSubParse", &sub_parse_info, 0);
117   }
118
119   return sub_parse_type;
120 }
121
122 static void
123 gst_sub_parse_base_init (GstSubParseClass * klass)
124 {
125   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
126
127   gst_element_class_add_pad_template (element_class,
128       gst_static_pad_template_get (&sink_templ));
129   gst_element_class_add_pad_template (element_class,
130       gst_static_pad_template_get (&src_templ));
131   gst_element_class_set_details (element_class, &sub_parse_details);
132 }
133
134 static void
135 gst_sub_parse_dispose (GObject * object)
136 {
137   GstSubParse *subparse = GST_SUBPARSE (object);
138
139   GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
140
141   if (subparse->encoding) {
142     g_free (subparse->encoding);
143     subparse->encoding = NULL;
144   }
145   if (subparse->textbuf) {
146     g_string_free (subparse->textbuf, TRUE);
147     subparse->textbuf = NULL;
148   }
149 #ifndef GST_DISABLE_XML
150   sami_context_deinit (&subparse->state);
151 #endif
152
153   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
154 }
155
156 static void
157 gst_sub_parse_class_init (GstSubParseClass * klass)
158 {
159   GObjectClass *object_class = G_OBJECT_CLASS (klass);
160   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
161
162   parent_class = g_type_class_peek_parent (klass);
163
164   object_class->dispose = gst_sub_parse_dispose;
165   object_class->set_property = gst_sub_parse_set_property;
166   object_class->get_property = gst_sub_parse_get_property;
167
168   element_class->change_state = gst_sub_parse_change_state;
169
170   g_object_class_install_property (object_class, PROP_ENCODING,
171       g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
172           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
173           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
174           "be checked for an encoding to use. If that is not set either, "
175           "ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
176           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
177 }
178
179 static void
180 gst_sub_parse_init (GstSubParse * subparse)
181 {
182   subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
183   gst_pad_set_chain_function (subparse->sinkpad,
184       GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
185   gst_pad_set_event_function (subparse->sinkpad,
186       GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
187   gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
188
189   subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
190   gst_pad_set_event_function (subparse->srcpad,
191       GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
192   gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
193
194   subparse->textbuf = g_string_new (NULL);
195   subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
196   subparse->flushing = FALSE;
197   gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
198   subparse->need_segment = TRUE;
199   subparse->encoding = g_strdup (DEFAULT_ENCODING);
200 }
201
202 /*
203  * Source pad functions.
204  */
205
206 static gboolean
207 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
208 {
209   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
210   gboolean ret = FALSE;
211
212   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
213
214   switch (GST_EVENT_TYPE (event)) {
215     case GST_EVENT_SEEK:
216     {
217       GstFormat format;
218       GstSeekType start_type, stop_type;
219       gint64 start, stop;
220       gdouble rate;
221       gboolean update;
222
223       gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
224           &start_type, &start, &stop_type, &stop);
225
226       if (format != GST_FORMAT_TIME) {
227         GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
228         gst_event_unref (event);
229         goto beach;
230       }
231
232       /* Convert that seek to a seeking in bytes at position 0,
233          FIXME: could use an index */
234       ret = gst_pad_push_event (self->sinkpad,
235           gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
236               GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
237
238       if (ret) {
239         /* Apply the seek to our segment */
240         gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
241             start_type, start, stop_type, stop, &update);
242
243         GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
244             &self->segment);
245
246         self->next_offset = 0;
247
248         self->need_segment = TRUE;
249       } else {
250         GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
251       }
252
253       gst_event_unref (event);
254       break;
255     }
256     default:
257       ret = gst_pad_event_default (pad, event);
258       break;
259   }
260
261 beach:
262   gst_object_unref (self);
263
264   return ret;
265 }
266
267 static void
268 gst_sub_parse_set_property (GObject * object, guint prop_id,
269     const GValue * value, GParamSpec * pspec)
270 {
271   GstSubParse *subparse = GST_SUBPARSE (object);
272
273   GST_OBJECT_LOCK (subparse);
274   switch (prop_id) {
275     case PROP_ENCODING:
276       g_free (subparse->encoding);
277       subparse->encoding = g_value_dup_string (value);
278       GST_LOG_OBJECT (object, "subtitle encoding set to %s",
279           GST_STR_NULL (subparse->encoding));
280       break;
281     default:
282       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
283       break;
284   }
285   GST_OBJECT_UNLOCK (subparse);
286 }
287
288 static void
289 gst_sub_parse_get_property (GObject * object, guint prop_id,
290     GValue * value, GParamSpec * pspec)
291 {
292   GstSubParse *subparse = GST_SUBPARSE (object);
293
294   GST_OBJECT_LOCK (subparse);
295   switch (prop_id) {
296     case PROP_ENCODING:
297       g_value_set_string (value, subparse->encoding);
298       break;
299     default:
300       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
301       break;
302   }
303   GST_OBJECT_UNLOCK (subparse);
304 }
305
306 static gchar *
307 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
308 {
309   const gchar *encoding;
310   GError *err = NULL;
311   gchar *ret;
312
313   if (self->valid_utf8) {
314     if (g_utf8_validate (str, len, NULL)) {
315       GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
316       return g_strndup (str, len);
317     }
318     GST_INFO_OBJECT (self, "invalid UTF-8!");
319     self->valid_utf8 = FALSE;
320   }
321
322   encoding = self->encoding;
323   if (encoding == NULL || *encoding == '\0') {
324     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
325   }
326   if (encoding == NULL || *encoding == '\0') {
327     /* if local encoding is UTF-8 and no encoding specified
328      * via the environment variable, assume ISO-8859-15 */
329     if (g_get_charset (&encoding)) {
330       encoding = "ISO-8859-15";
331     }
332   }
333
334   ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
335       NULL, &err);
336
337   if (err) {
338     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
339         encoding, err->message);
340     g_error_free (err);
341
342     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
343     ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
344         NULL, NULL, NULL);
345   }
346
347   GST_LOG_OBJECT (self,
348       "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
349       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
350
351   return ret;
352 }
353
354 static gchar *
355 get_next_line (GstSubParse * self)
356 {
357   char *line = NULL;
358   const char *line_end;
359   int line_len;
360   gboolean have_r = FALSE;
361
362   line_end = strchr (self->textbuf->str, '\n');
363
364   if (!line_end) {
365     /* end-of-line not found; return for more data */
366     return NULL;
367   }
368
369   /* get rid of '\r' */
370   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
371     line_end--;
372     have_r = TRUE;
373   }
374
375   line_len = line_end - self->textbuf->str;
376   line = convert_encoding (self, self->textbuf->str, line_len);
377   self->textbuf = g_string_erase (self->textbuf, 0,
378       line_len + (have_r ? 2 : 1));
379   return line;
380 }
381
382 static gchar *
383 parse_mdvdsub (ParserState * state, const gchar * line)
384 {
385   const gchar *line_split;
386   gchar *line_chunk;
387   guint start_frame, end_frame;
388   gint64 clip_start = 0, clip_stop = 0;
389   gboolean in_seg = FALSE;
390   GString *markup;
391   gchar *ret;
392
393   /* style variables */
394   gboolean italic;
395   gboolean bold;
396   guint fontsize;
397
398   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
399     g_warning ("Parse of the following line, assumed to be in microdvd .sub"
400         " format, failed:\n%s", line);
401     return NULL;
402   }
403
404   /* skip the {%u}{%u} part */
405   line = strchr (line, '}') + 1;
406   line = strchr (line, '}') + 1;
407
408   /* see if there's a first line with a framerate */
409   if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
410     gchar *rest, *end = NULL;
411
412     rest = g_strdup (line);
413     g_strdelimit (rest, ",", '.');
414     state->fps = g_ascii_strtod (rest, &end);
415     if (end == rest)
416       state->fps = 0.0;
417     GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
418     g_free (rest);
419     return NULL;
420   }
421
422   if (state->fps == 0.0) {
423     /* FIXME: hardcoded for now, is there a better way/assumption? */
424     state->fps = 24000.0 / 1001.0;
425     GST_INFO ("no framerate specified, assuming %f", state->fps);
426   }
427
428   state->start_time = start_frame / state->fps * GST_SECOND;
429   state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
430
431   /* Check our segment start/stop */
432   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
433       state->start_time, state->start_time + state->duration, &clip_start,
434       &clip_stop);
435
436   /* No need to parse that text if it's out of segment */
437   if (in_seg) {
438     state->start_time = clip_start;
439     state->duration = clip_stop - clip_start;
440   } else {
441     return NULL;
442   }
443
444   markup = g_string_new (NULL);
445   while (1) {
446     italic = FALSE;
447     bold = FALSE;
448     fontsize = 0;
449     /* parse style markup */
450     if (strncmp (line, "{y:i}", 5) == 0) {
451       italic = TRUE;
452       line = strchr (line, '}') + 1;
453     }
454     if (strncmp (line, "{y:b}", 5) == 0) {
455       bold = TRUE;
456       line = strchr (line, '}') + 1;
457     }
458     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
459       line = strchr (line, '}') + 1;
460     }
461     /* forward slashes at beginning/end signify italics too */
462     if (g_str_has_prefix (line, "/")) {
463       italic = TRUE;
464       ++line;
465     }
466     if ((line_split = strchr (line, '|')))
467       line_chunk = g_markup_escape_text (line, line_split - line);
468     else
469       line_chunk = g_markup_escape_text (line, strlen (line));
470
471     /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
472      * always at the end of a line or can they span multiple lines?) */
473     if (g_str_has_suffix (line_chunk, "/")) {
474       line_chunk[strlen (line_chunk) - 1] = '\0';
475     }
476
477     markup = g_string_append (markup, "<span");
478     if (italic)
479       g_string_append (markup, " style=\"italic\"");
480     if (bold)
481       g_string_append (markup, " weight=\"bold\"");
482     if (fontsize)
483       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
484     g_string_append_printf (markup, ">%s</span>", line_chunk);
485     g_free (line_chunk);
486     if (line_split) {
487       g_string_append (markup, "\n");
488       line = line_split + 1;
489     } else {
490       break;
491     }
492   }
493   ret = markup->str;
494   g_string_free (markup, FALSE);
495   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
496       state->start_time / (double) GST_SECOND,
497       state->duration / (double) GST_SECOND, ret);
498   return ret;
499 }
500
501 static void
502 strip_trailing_newlines (gchar * txt)
503 {
504   if (txt) {
505     guint len;
506
507     len = strlen (txt);
508     while (len > 1 && txt[len - 1] == '\n') {
509       txt[len - 1] = '\0';
510       --len;
511     }
512   }
513 }
514
515 /* we want to escape text in general, but retain basic markup like
516  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
517  * just unescape a white list of allowed markups again after
518  * escaping everything (the text between these simple markers isn't
519  * necessarily escaped, so it seems best to do it like this) */
520 static void
521 subrip_unescape_formatting (gchar * txt)
522 {
523   gchar *pos;
524
525   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
526     if (g_ascii_strncasecmp (pos, "&lt;u&gt;", 9) == 0 ||
527         g_ascii_strncasecmp (pos, "&lt;i&gt;", 9) == 0 ||
528         g_ascii_strncasecmp (pos, "&lt;b&gt;", 9) == 0) {
529       pos[0] = '<';
530       pos[1] = g_ascii_tolower (pos[4]);
531       pos[2] = '>';
532       /* move NUL terminator as well */
533       g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
534       pos += 2;
535     }
536   }
537
538   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
539     if (g_ascii_strncasecmp (pos, "&lt;/u&gt;", 10) == 0 ||
540         g_ascii_strncasecmp (pos, "&lt;/i&gt;", 10) == 0 ||
541         g_ascii_strncasecmp (pos, "&lt;/b&gt;", 10) == 0) {
542       pos[0] = '<';
543       pos[1] = '/';
544       pos[2] = g_ascii_tolower (pos[5]);
545       pos[3] = '>';
546       /* move NUL terminator as well */
547       g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
548       pos += 3;
549     }
550   }
551 }
552
553
554 static gboolean
555 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
556 {
557   gchar *tag, saved;
558
559   tag = start + strlen ("&lt;");
560   if (*tag == '/')
561     ++tag;
562
563   if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
564     return FALSE;
565
566   saved = *stop;
567   *stop = '\0';
568   GST_LOG ("removing unhandled tag '%s'", start);
569   *stop = saved;
570   g_memmove (start, stop, strlen (stop) + 1);
571   return TRUE;
572 }
573
574 /* remove tags we haven't explicitly allowed earlier on, like font tags
575  * for example */
576 static void
577 subrip_remove_unhandled_tags (gchar * txt)
578 {
579   gchar *pos, *gt;
580
581   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
582     if (strncmp (pos, "&lt;", 4) == 0 && (gt = strstr (pos + 4, "&gt;"))) {
583       if (subrip_remove_unhandled_tag (pos, gt + strlen ("&gt;")))
584         --pos;
585     }
586   }
587 }
588
589 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
590  * assumes the input has been escaped and subrip_unescape_formatting() has then
591  * been run over the input! This function adds missing closing markup tags and
592  * removes broken closing tags for tags that have never been opened. */
593 static void
594 subrip_fix_up_markup (gchar ** p_txt)
595 {
596   gchar *cur, *next_tag;
597   gchar open_tags[32];
598   guint num_open_tags = 0;
599
600   g_assert (*p_txt != NULL);
601
602   cur = *p_txt;
603   while (*cur != '\0') {
604     next_tag = strchr (cur, '<');
605     if (next_tag == NULL)
606       break;
607     ++next_tag;
608     switch (*next_tag) {
609       case '/':{
610         ++next_tag;
611         if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
612           GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
613           g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
614           next_tag -= 2;
615         } else {
616           /* it's all good, closing tag which is open */
617           --num_open_tags;
618         }
619         break;
620       }
621       case 'i':
622       case 'b':
623       case 'u':
624         if (num_open_tags == G_N_ELEMENTS (open_tags))
625           return;               /* something dodgy is going on, stop parsing */
626         open_tags[num_open_tags] = *next_tag;
627         ++num_open_tags;
628         break;
629       default:
630         GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
631         g_assert_not_reached ();
632         break;
633     }
634     cur = next_tag;
635   }
636
637   if (num_open_tags > 0) {
638     GString *s;
639
640     s = g_string_new (*p_txt);
641     while (num_open_tags > 0) {
642       GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
643       g_string_append_c (s, '<');
644       g_string_append_c (s, '/');
645       g_string_append_c (s, open_tags[num_open_tags - 1]);
646       g_string_append_c (s, '>');
647       --num_open_tags;
648     }
649     g_free (*p_txt);
650     *p_txt = g_string_free (s, FALSE);
651   }
652 }
653
654 static gchar *
655 parse_subrip (ParserState * state, const gchar * line)
656 {
657   guint h1, m1, s1, ms1;
658   guint h2, m2, s2, ms2;
659   int subnum;
660   gchar *ret;
661
662   switch (state->state) {
663     case 0:
664       /* looking for a single integer */
665       if (sscanf (line, "%u", &subnum) == 1)
666         state->state = 1;
667       return NULL;
668     case 1:
669       /* looking for start_time --> end_time */
670       if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
671               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
672         state->state = 2;
673         state->start_time =
674             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
675             ms1 * GST_MSECOND;
676         state->duration =
677             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
678             ms2 * GST_MSECOND - state->start_time;
679       } else {
680         GST_DEBUG ("error parsing subrip time line");
681         state->state = 0;
682       }
683       return NULL;
684     case 2:
685     {
686       /* No need to parse that text if it's out of segment */
687       gint64 clip_start = 0, clip_stop = 0;
688       gboolean in_seg = FALSE;
689
690       /* Check our segment start/stop */
691       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
692           state->start_time, state->start_time + state->duration,
693           &clip_start, &clip_stop);
694
695       if (in_seg) {
696         state->start_time = clip_start;
697         state->duration = clip_stop - clip_start;
698       } else {
699         state->state = 0;
700         return NULL;
701       }
702     }
703       /* looking for subtitle text; empty line ends this subtitle entry */
704       if (state->buf->len)
705         g_string_append_c (state->buf, '\n');
706       g_string_append (state->buf, line);
707       if (strlen (line) == 0) {
708         ret = g_markup_escape_text (state->buf->str, state->buf->len);
709         g_string_truncate (state->buf, 0);
710         state->state = 0;
711         subrip_unescape_formatting (ret);
712         subrip_remove_unhandled_tags (ret);
713         strip_trailing_newlines (ret);
714         subrip_fix_up_markup (&ret);
715         return ret;
716       }
717       return NULL;
718     default:
719       g_return_val_if_reached (NULL);
720   }
721 }
722
723 static void
724 subviewer_unescape_newlines (gchar * read)
725 {
726   gchar *write = read;
727
728   /* Replace all occurences of '[br]' with a newline as version 2
729    * of the subviewer format uses this for newlines */
730
731   if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
732     return;
733
734   do {
735     if (strncmp (read, "[br]", 4) == 0) {
736       *write = '\n';
737       read += 4;
738     } else {
739       *write = *read;
740       read++;
741     }
742     write++;
743   } while (*read);
744
745   *write = '\0';
746 }
747
748 static gchar *
749 parse_subviewer (ParserState * state, const gchar * line)
750 {
751   guint h1, m1, s1, ms1;
752   guint h2, m2, s2, ms2;
753   gchar *ret;
754
755   /* TODO: Maybe also parse the fields in the header, especially DELAY.
756    * For examples see the unit test or
757    * http://www.doom9.org/index.html?/sub.htm */
758
759   switch (state->state) {
760     case 0:
761       /* looking for start_time,end_time */
762       if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
763               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
764         state->state = 1;
765         state->start_time =
766             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
767             ms1 * GST_MSECOND;
768         state->duration =
769             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
770             ms2 * GST_MSECOND - state->start_time;
771       }
772       return NULL;
773     case 1:
774     {
775       /* No need to parse that text if it's out of segment */
776       gint64 clip_start = 0, clip_stop = 0;
777       gboolean in_seg = FALSE;
778
779       /* Check our segment start/stop */
780       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
781           state->start_time, state->start_time + state->duration,
782           &clip_start, &clip_stop);
783
784       if (in_seg) {
785         state->start_time = clip_start;
786         state->duration = clip_stop - clip_start;
787       } else {
788         state->state = 0;
789         return NULL;
790       }
791     }
792       /* looking for subtitle text; empty line ends this subtitle entry */
793       if (state->buf->len)
794         g_string_append_c (state->buf, '\n');
795       g_string_append (state->buf, line);
796       if (strlen (line) == 0) {
797         ret = g_strdup (state->buf->str);
798         subviewer_unescape_newlines (ret);
799         strip_trailing_newlines (ret);
800         g_string_truncate (state->buf, 0);
801         state->state = 0;
802         return ret;
803       }
804       return NULL;
805     default:
806       g_assert_not_reached ();
807       return NULL;
808   }
809 }
810
811 static gchar *
812 parse_mpsub (ParserState * state, const gchar * line)
813 {
814   gchar *ret;
815   float t1, t2;
816
817   switch (state->state) {
818     case 0:
819       /* looking for two floats (offset, duration) */
820       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
821         state->state = 1;
822         state->start_time += state->duration + GST_SECOND * t1;
823         state->duration = GST_SECOND * t2;
824       }
825       return NULL;
826     case 1:
827     {                           /* No need to parse that text if it's out of segment */
828       gint64 clip_start = 0, clip_stop = 0;
829       gboolean in_seg = FALSE;
830
831       /* Check our segment start/stop */
832       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
833           state->start_time, state->start_time + state->duration,
834           &clip_start, &clip_stop);
835
836       if (in_seg) {
837         state->start_time = clip_start;
838         state->duration = clip_stop - clip_start;
839       } else {
840         state->state = 0;
841         return NULL;
842       }
843     }
844       /* looking for subtitle text; empty line ends this
845        * subtitle entry */
846       if (state->buf->len)
847         g_string_append_c (state->buf, '\n');
848       g_string_append (state->buf, line);
849       if (strlen (line) == 0) {
850         ret = g_strdup (state->buf->str);
851         g_string_truncate (state->buf, 0);
852         state->state = 0;
853         return ret;
854       }
855       return NULL;
856     default:
857       g_assert_not_reached ();
858       return NULL;
859   }
860 }
861
862 static void
863 parser_state_init (ParserState * state)
864 {
865   GST_DEBUG ("initialising parser");
866
867   if (state->buf) {
868     g_string_truncate (state->buf, 0);
869   } else {
870     state->buf = g_string_new (NULL);
871   }
872
873   state->start_time = 0;
874   state->duration = 0;
875   state->max_duration = 0;      /* no limit */
876   state->state = 0;
877   state->segment = NULL;
878 }
879
880 static void
881 parser_state_dispose (ParserState * state)
882 {
883   if (state->buf) {
884     g_string_free (state->buf, TRUE);
885     state->buf = NULL;
886   }
887 #ifndef GST_DISABLE_XML
888   if (state->user_data) {
889     sami_context_reset (state);
890   }
891 #endif
892 }
893
894 /*
895  * FIXME: maybe we should pass along a second argument, the preceding
896  * text buffer, because that is how this originally worked, even though
897  * I don't really see the use of that.
898  */
899
900 static GstSubParseFormat
901 gst_sub_parse_data_format_autodetect (gchar * match_str)
902 {
903   static gboolean need_init_regexps = TRUE;
904   static regex_t mdvd_rx;
905   static regex_t subrip_rx;
906   guint n1, n2, n3;
907
908   /* initialize the regexps used the first time around */
909   if (need_init_regexps) {
910     int err;
911     char errstr[128];
912
913     need_init_regexps = FALSE;
914     if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
915                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
916         (err = regcomp (&subrip_rx, "^([ 0-9]){0,3}[0-9](\x0d)?\x0a"
917                 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]"
918                 " --> ([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]",
919                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
920       regerror (err, &subrip_rx, errstr, 127);
921       GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
922     }
923   }
924
925   /* If the string contains a UTF-8 BOM drop it */
926   if ((guint8) match_str[0] == 0xEF && (guint8) match_str[1] == 0xBB
927       && (guint8) match_str[2] == 0xBF)
928     match_str += 3;
929
930   if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
931     GST_LOG ("MicroDVD (frame based) format detected");
932     return GST_SUB_PARSE_FORMAT_MDVDSUB;
933   }
934   if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
935     GST_LOG ("SubRip (time based) format detected");
936     return GST_SUB_PARSE_FORMAT_SUBRIP;
937   }
938
939   if (!strncmp (match_str, "FORMAT=TIME", 11)) {
940     GST_LOG ("MPSub (time based) format detected");
941     return GST_SUB_PARSE_FORMAT_MPSUB;
942   }
943 #ifndef GST_DISABLE_XML
944   if (strstr (match_str, "<SAMI>") != NULL ||
945       strstr (match_str, "<sami>") != NULL) {
946     GST_LOG ("SAMI (time based) format detected");
947     return GST_SUB_PARSE_FORMAT_SAMI;
948   }
949 #endif
950   /* we're boldly assuming the first subtitle appears within the first hour */
951   if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
952       sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
953       sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
954       sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
955       sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
956     GST_LOG ("TMPlayer (time based) format detected");
957     return GST_SUB_PARSE_FORMAT_TMPLAYER;
958   }
959   if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
960     GST_LOG ("MPL2 (time based) format detected");
961     return GST_SUB_PARSE_FORMAT_MPL2;
962   }
963   if (strstr (match_str, "[INFORMATION]") != NULL) {
964     GST_LOG ("SubViewer (time based) format detected");
965     return GST_SUB_PARSE_FORMAT_SUBVIEWER;
966   }
967
968   GST_DEBUG ("no subtitle format detected");
969   return GST_SUB_PARSE_FORMAT_UNKNOWN;
970 }
971
972 static GstCaps *
973 gst_sub_parse_format_autodetect (GstSubParse * self)
974 {
975   gchar *data;
976   GstSubParseFormat format;
977
978   if (strlen (self->textbuf->str) < 35) {
979     GST_DEBUG ("File too small to be a subtitles file");
980     return NULL;
981   }
982
983   data = g_strndup (self->textbuf->str, 35);
984   format = gst_sub_parse_data_format_autodetect (data);
985   g_free (data);
986
987   self->parser_type = format;
988   parser_state_init (&self->state);
989
990   switch (format) {
991     case GST_SUB_PARSE_FORMAT_MDVDSUB:
992       self->parse_line = parse_mdvdsub;
993       return gst_caps_new_simple ("text/x-pango-markup", NULL);
994     case GST_SUB_PARSE_FORMAT_SUBRIP:
995       self->parse_line = parse_subrip;
996       return gst_caps_new_simple ("text/x-pango-markup", NULL);
997     case GST_SUB_PARSE_FORMAT_MPSUB:
998       self->parse_line = parse_mpsub;
999       return gst_caps_new_simple ("text/plain", NULL);
1000 #ifndef GST_DISABLE_XML
1001     case GST_SUB_PARSE_FORMAT_SAMI:
1002       self->parse_line = parse_sami;
1003       sami_context_init (&self->state);
1004       return gst_caps_new_simple ("text/x-pango-markup", NULL);
1005 #endif
1006     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1007       self->parse_line = parse_tmplayer;
1008       self->state.max_duration = 5 * GST_SECOND;
1009       return gst_caps_new_simple ("text/plain", NULL);
1010     case GST_SUB_PARSE_FORMAT_MPL2:
1011       self->parse_line = parse_mpl2;
1012       return gst_caps_new_simple ("text/x-pango-markup", NULL);
1013     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1014       self->parse_line = parse_subviewer;
1015       return gst_caps_new_simple ("text/plain", NULL);
1016     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1017     default:
1018       GST_DEBUG ("no subtitle format detected");
1019       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1020           ("The input is not a valid/supported subtitle file"), (NULL));
1021       return NULL;
1022   }
1023 }
1024
1025 static void
1026 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1027 {
1028   gboolean discont;
1029
1030   discont = GST_BUFFER_IS_DISCONT (buf);
1031
1032   if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1033       GST_BUFFER_OFFSET (buf) != self->offset) {
1034     self->offset = GST_BUFFER_OFFSET (buf);
1035     discont = TRUE;
1036   }
1037
1038   if (discont) {
1039     GST_INFO ("discontinuity");
1040     /* flush the parser state */
1041     parser_state_init (&self->state);
1042     g_string_truncate (self->textbuf, 0);
1043 #ifndef GST_DISABLE_XML
1044     sami_context_reset (&self->state);
1045 #endif
1046     /* we could set a flag to make sure that the next buffer we push out also
1047      * has the DISCONT flag set, but there's no point really given that it's
1048      * subtitles which are discontinuous by nature. */
1049   }
1050
1051   self->textbuf = g_string_append_len (self->textbuf,
1052       (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1053   self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1054   self->next_offset = self->offset;
1055
1056   gst_buffer_unref (buf);
1057 }
1058
1059 static GstFlowReturn
1060 handle_buffer (GstSubParse * self, GstBuffer * buf)
1061 {
1062   GstFlowReturn ret = GST_FLOW_OK;
1063   GstCaps *caps = NULL;
1064   gchar *line, *subtitle;
1065
1066   feed_textbuf (self, buf);
1067
1068   /* make sure we know the format */
1069   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1070     if (!(caps = gst_sub_parse_format_autodetect (self))) {
1071       return GST_FLOW_UNEXPECTED;
1072     }
1073     if (!gst_pad_set_caps (self->srcpad, caps)) {
1074       gst_caps_unref (caps);
1075       return GST_FLOW_UNEXPECTED;
1076     }
1077     gst_caps_unref (caps);
1078   }
1079
1080   while ((line = get_next_line (self)) && !self->flushing) {
1081     guint offset = 0;
1082
1083     /* If this is the first line and it contains a UTF-8 BOM drop it */
1084     if (self->first_line && strlen (line) >= 3 &&
1085         (guint8) line[0] == 0xEF && (guint8) line[1] == 0xBB
1086         && (guint8) line[2] == 0xBF) {
1087       offset = 3;
1088     }
1089
1090     self->first_line = FALSE;
1091
1092     /* Set segment on our parser state machine */
1093     self->state.segment = &self->segment;
1094     /* Now parse the line, out of segment lines will just return NULL */
1095     GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1096     subtitle = self->parse_line (&self->state, line + offset);
1097     g_free (line);
1098
1099     if (subtitle) {
1100       guint subtitle_len = strlen (subtitle);
1101
1102       /* +1 for terminating NUL character */
1103       ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1104           GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1105           GST_PAD_CAPS (self->srcpad), &buf);
1106
1107       if (ret == GST_FLOW_OK) {
1108         /* copy terminating NUL character as well */
1109         memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1110         GST_BUFFER_SIZE (buf) = subtitle_len;
1111         GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1112         GST_BUFFER_DURATION (buf) = self->state.duration;
1113
1114         /* in some cases (e.g. tmplayer) we can only determine the duration
1115          * of a text chunk from the timestamp of the next text chunk; in those
1116          * cases, we probably want to limit the duration to something
1117          * reasonable, so we don't end up showing some text for e.g. 40 seconds
1118          * just because nothing else is being said during that time */
1119         if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1120           if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1121             GST_BUFFER_DURATION (buf) = self->state.max_duration;
1122         }
1123
1124         gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1125             self->state.start_time);
1126
1127         GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1128             GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1129             GST_TIME_ARGS (self->state.duration));
1130
1131         ret = gst_pad_push (self->srcpad, buf);
1132       }
1133
1134       /* move this forward (the tmplayer parser needs this) */
1135       if (self->state.duration != GST_CLOCK_TIME_NONE)
1136         self->state.start_time += self->state.duration;
1137
1138       g_free (subtitle);
1139       subtitle = NULL;
1140
1141       if (ret != GST_FLOW_OK) {
1142         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1143         break;
1144       }
1145     }
1146   }
1147
1148   return ret;
1149 }
1150
1151 static GstFlowReturn
1152 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1153 {
1154   GstFlowReturn ret;
1155   GstSubParse *self;
1156
1157   self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1158
1159   /* Push newsegment if needed */
1160   if (self->need_segment) {
1161     GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1162         &self->segment);
1163
1164     gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1165             self->segment.rate, self->segment.format,
1166             self->segment.last_stop, self->segment.stop, self->segment.time));
1167     self->need_segment = FALSE;
1168   }
1169
1170   ret = handle_buffer (self, buf);
1171
1172   return ret;
1173 }
1174
1175 static gboolean
1176 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1177 {
1178   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1179   gboolean ret = FALSE;
1180
1181   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1182
1183   switch (GST_EVENT_TYPE (event)) {
1184     case GST_EVENT_EOS:{
1185       /* Make sure the last subrip chunk is pushed out even
1186        * if the file does not have an empty line at the end */
1187       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1188           self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1189           self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1190         GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1191
1192         GST_DEBUG ("EOS. Pushing remaining text (if any)");
1193         GST_BUFFER_DATA (buf)[0] = '\n';
1194         GST_BUFFER_DATA (buf)[1] = '\n';
1195         GST_BUFFER_DATA (buf)[2] = '\0';        /* play it safe */
1196         GST_BUFFER_SIZE (buf) = 2;
1197         GST_BUFFER_OFFSET (buf) = self->offset;
1198         gst_sub_parse_chain (pad, buf);
1199       }
1200       ret = gst_pad_event_default (pad, event);
1201       break;
1202     }
1203     case GST_EVENT_NEWSEGMENT:
1204     {
1205       GstFormat format;
1206       gdouble rate;
1207       gint64 start, stop, time;
1208       gboolean update;
1209
1210       gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1211           &stop, &time);
1212
1213       GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1214
1215       if (format == GST_FORMAT_TIME) {
1216         gst_segment_set_newsegment (&self->segment, update, rate, format,
1217             start, stop, time);
1218       } else {
1219         /* if not time format, we'll either start with a 0 timestamp anyway or
1220          * it's following a seek in which case we'll have saved the requested
1221          * seek segment and don't want to overwrite it (remember that on a seek
1222          * we always just seek back to the start in BYTES format and just throw
1223          * away all text that's before the requested position; if the subtitles
1224          * come from an upstream demuxer, it won't be able to handle our BYTES
1225          * seek request and instead send us a newsegment from the seek request
1226          * it received via its video pads instead, so all is fine then too) */
1227       }
1228
1229       ret = TRUE;
1230       gst_event_unref (event);
1231       break;
1232     }
1233     case GST_EVENT_FLUSH_START:
1234     {
1235       self->flushing = TRUE;
1236
1237       ret = gst_pad_event_default (pad, event);
1238       break;
1239     }
1240     case GST_EVENT_FLUSH_STOP:
1241     {
1242       self->flushing = FALSE;
1243
1244       ret = gst_pad_event_default (pad, event);
1245       break;
1246     }
1247     default:
1248       ret = gst_pad_event_default (pad, event);
1249       break;
1250   }
1251
1252   gst_object_unref (self);
1253
1254   return ret;
1255 }
1256
1257
1258 static GstStateChangeReturn
1259 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1260 {
1261   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1262   GstSubParse *self = GST_SUBPARSE (element);
1263
1264   switch (transition) {
1265     case GST_STATE_CHANGE_READY_TO_PAUSED:
1266       /* format detection will init the parser state */
1267       self->offset = 0;
1268       self->next_offset = 0;
1269       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1270       self->valid_utf8 = TRUE;
1271       self->first_line = TRUE;
1272       g_string_truncate (self->textbuf, 0);
1273       break;
1274     default:
1275       break;
1276   }
1277
1278   ret = parent_class->change_state (element, transition);
1279   if (ret == GST_STATE_CHANGE_FAILURE)
1280     return ret;
1281
1282   switch (transition) {
1283     case GST_STATE_CHANGE_PAUSED_TO_READY:
1284       parser_state_dispose (&self->state);
1285       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1286       break;
1287     default:
1288       break;
1289   }
1290
1291   return ret;
1292 }
1293
1294 /*
1295  * Typefind support.
1296  */
1297
1298 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1299  * also, give different  subtitle formats really different types */
1300 static GstStaticCaps mpl2_caps =
1301 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1302 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1303
1304 static GstStaticCaps tmp_caps =
1305 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1306 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1307
1308 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1309 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1310
1311 #ifndef GST_DISABLE_XML
1312 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1313 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1314 #endif
1315
1316 static void
1317 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1318 {
1319   GstSubParseFormat format;
1320   const guint8 *data;
1321   GstCaps *caps;
1322   gchar *str;
1323
1324   if (!(data = gst_type_find_peek (tf, 0, 36)))
1325     return;
1326
1327   /* make sure string passed to _autodetect() is NUL-terminated */
1328   str = g_strndup ((gchar *) data, 35);
1329   format = gst_sub_parse_data_format_autodetect (str);
1330   g_free (str);
1331
1332   switch (format) {
1333     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1334       GST_DEBUG ("MicroDVD format detected");
1335       caps = SUB_CAPS;
1336       break;
1337     case GST_SUB_PARSE_FORMAT_SUBRIP:
1338       GST_DEBUG ("SubRip format detected");
1339       caps = SUB_CAPS;
1340       break;
1341     case GST_SUB_PARSE_FORMAT_MPSUB:
1342       GST_DEBUG ("MPSub format detected");
1343       caps = SUB_CAPS;
1344       break;
1345 #ifndef GST_DISABLE_XML
1346     case GST_SUB_PARSE_FORMAT_SAMI:
1347       GST_DEBUG ("SAMI (time-based) format detected");
1348       caps = SAMI_CAPS;
1349       break;
1350 #endif
1351     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1352       GST_DEBUG ("TMPlayer (time based) format detected");
1353       caps = TMP_CAPS;
1354       break;
1355       /* FIXME: our MPL2 typefinding is not really good enough to warrant
1356        * returning a high probability (however, since we registered our
1357        * typefinder here with a rank of MARGINAL we should pretty much only
1358        * be called if most other typefinders have already run */
1359     case GST_SUB_PARSE_FORMAT_MPL2:
1360       GST_DEBUG ("MPL2 (time based) format detected");
1361       caps = MPL2_CAPS;
1362       break;
1363     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1364       GST_DEBUG ("SubViewer format detected");
1365       caps = SUB_CAPS;
1366       break;
1367     default:
1368     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1369       GST_DEBUG ("no subtitle format detected");
1370       return;
1371   }
1372
1373   /* if we're here, it's ok */
1374   gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1375 }
1376
1377 static gboolean
1378 plugin_init (GstPlugin * plugin)
1379 {
1380   static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1381     NULL
1382   };
1383
1384   GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1385
1386   if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1387           gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1388     return FALSE;
1389
1390   if (!gst_element_register (plugin, "subparse",
1391           GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1392       !gst_element_register (plugin, "ssaparse",
1393           GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1394     return FALSE;
1395   }
1396
1397   return TRUE;
1398 }
1399
1400 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1401     GST_VERSION_MINOR,
1402     "subparse",
1403     "Subtitle parsing",
1404     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)