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