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