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