subparse: ensure serialized sending of segment event at proper time
[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  * Copyright (C) 2016 Philippe Normand <pnormand@igalia.com>
6  * Copyright (C) 2016 Jan Schmidt <jan@centricular.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <glib.h>
33
34 #include "gstsubparse.h"
35 #include "gstssaparse.h"
36 #include "samiparse.h"
37 #include "tmplayerparse.h"
38 #include "mpl2parse.h"
39 #include "qttextparse.h"
40
41 GST_DEBUG_CATEGORY (sub_parse_debug);
42
43 #define DEFAULT_ENCODING   NULL
44 #define ATTRIBUTE_REGEX "\\s?[a-zA-Z0-9\\. \t\\(\\)]*"
45 static const gchar *allowed_srt_tags[] = { "i", "b", "u", NULL };
46 static const gchar *allowed_vtt_tags[] =
47     { "i", "b", "c", "u", "v", "ruby", "rt", NULL };
48
49 enum
50 {
51   PROP_0,
52   PROP_ENCODING,
53   PROP_VIDEOFPS
54 };
55
56 static void
57 gst_sub_parse_set_property (GObject * object, guint prop_id,
58     const GValue * value, GParamSpec * pspec);
59 static void
60 gst_sub_parse_get_property (GObject * object, guint prop_id,
61     GValue * value, GParamSpec * pspec);
62
63
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         "application/x-subtitle-dks; application/x-subtitle-qttext;"
70         "application/x-subtitle-lrc; application/x-subtitle-vtt")
71     );
72
73 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
74     GST_PAD_SRC,
75     GST_PAD_ALWAYS,
76     GST_STATIC_CAPS ("text/x-raw, format= { pango-markup, utf8 }")
77     );
78
79
80 static gboolean gst_sub_parse_src_event (GstPad * pad, GstObject * parent,
81     GstEvent * event);
82 static gboolean gst_sub_parse_src_query (GstPad * pad, GstObject * parent,
83     GstQuery * query);
84 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstObject * parent,
85     GstEvent * event);
86
87 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
88     GstStateChange transition);
89
90 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent,
91     GstBuffer * buf);
92
93 #define gst_sub_parse_parent_class parent_class
94 G_DEFINE_TYPE (GstSubParse, gst_sub_parse, GST_TYPE_ELEMENT);
95
96 static void
97 gst_sub_parse_dispose (GObject * object)
98 {
99   GstSubParse *subparse = GST_SUBPARSE (object);
100
101   GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
102
103   if (subparse->encoding) {
104     g_free (subparse->encoding);
105     subparse->encoding = NULL;
106   }
107
108   if (subparse->detected_encoding) {
109     g_free (subparse->detected_encoding);
110     subparse->detected_encoding = NULL;
111   }
112
113   if (subparse->adapter) {
114     g_object_unref (subparse->adapter);
115     subparse->adapter = NULL;
116   }
117
118   if (subparse->textbuf) {
119     g_string_free (subparse->textbuf, TRUE);
120     subparse->textbuf = NULL;
121   }
122
123   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
124 }
125
126 static void
127 gst_sub_parse_class_init (GstSubParseClass * klass)
128 {
129   GObjectClass *object_class = G_OBJECT_CLASS (klass);
130   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
131
132   object_class->dispose = gst_sub_parse_dispose;
133   object_class->set_property = gst_sub_parse_set_property;
134   object_class->get_property = gst_sub_parse_get_property;
135
136   gst_element_class_add_static_pad_template (element_class, &sink_templ);
137   gst_element_class_add_static_pad_template (element_class, &src_templ);
138   gst_element_class_set_static_metadata (element_class,
139       "Subtitle parser", "Codec/Parser/Subtitle",
140       "Parses subtitle (.sub) files into text streams",
141       "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
142       "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
143
144   element_class->change_state = gst_sub_parse_change_state;
145
146   g_object_class_install_property (object_class, PROP_ENCODING,
147       g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
148           "Encoding to assume if input subtitles are not in UTF-8 or any other "
149           "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
150           "variable will be checked for an encoding to use. If that is not set "
151           "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
152           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
153
154   g_object_class_install_property (object_class, PROP_VIDEOFPS,
155       gst_param_spec_fraction ("video-fps", "Video framerate",
156           "Framerate of the video stream. This is needed by some subtitle "
157           "formats to synchronize subtitles and video properly. If not set "
158           "and the subtitle format requires it subtitles may be out of sync.",
159           0, 1, G_MAXINT, 1, 24000, 1001,
160           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
161 }
162
163 static void
164 gst_sub_parse_init (GstSubParse * subparse)
165 {
166   subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
167   gst_pad_set_chain_function (subparse->sinkpad,
168       GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
169   gst_pad_set_event_function (subparse->sinkpad,
170       GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
171   gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
172
173   subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
174   gst_pad_set_event_function (subparse->srcpad,
175       GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
176   gst_pad_set_query_function (subparse->srcpad,
177       GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
178   gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
179
180   subparse->textbuf = g_string_new (NULL);
181   subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
182   subparse->flushing = FALSE;
183   gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
184   subparse->need_segment = TRUE;
185   subparse->encoding = g_strdup (DEFAULT_ENCODING);
186   subparse->detected_encoding = NULL;
187   subparse->adapter = gst_adapter_new ();
188
189   subparse->fps_n = 24000;
190   subparse->fps_d = 1001;
191 }
192
193 /*
194  * Source pad functions.
195  */
196
197 static gboolean
198 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
199 {
200   GstSubParse *self = GST_SUBPARSE (parent);
201   gboolean ret = FALSE;
202
203   GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
204
205   switch (GST_QUERY_TYPE (query)) {
206     case GST_QUERY_POSITION:{
207       GstFormat fmt;
208
209       gst_query_parse_position (query, &fmt, NULL);
210       if (fmt != GST_FORMAT_TIME) {
211         ret = gst_pad_peer_query (self->sinkpad, query);
212       } else {
213         ret = TRUE;
214         gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
215       }
216       break;
217     }
218     case GST_QUERY_SEEKING:
219     {
220       GstFormat fmt;
221       gboolean seekable = FALSE;
222
223       ret = TRUE;
224
225       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
226       if (fmt == GST_FORMAT_TIME) {
227         GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
228
229         seekable = gst_pad_peer_query (self->sinkpad, peerquery);
230         if (seekable)
231           gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
232         gst_query_unref (peerquery);
233       }
234
235       gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
236       break;
237     }
238     default:
239       ret = gst_pad_query_default (pad, parent, query);
240       break;
241   }
242
243   return ret;
244 }
245
246 static gboolean
247 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
248 {
249   GstSubParse *self = GST_SUBPARSE (parent);
250   gboolean ret = FALSE;
251
252   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
253
254   switch (GST_EVENT_TYPE (event)) {
255     case GST_EVENT_SEEK:
256     {
257       GstFormat format;
258       GstSeekFlags flags;
259       GstSeekType start_type, stop_type;
260       gint64 start, stop;
261       gdouble rate;
262       gboolean update;
263
264       gst_event_parse_seek (event, &rate, &format, &flags,
265           &start_type, &start, &stop_type, &stop);
266
267       if (format != GST_FORMAT_TIME) {
268         GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
269         gst_event_unref (event);
270         goto beach;
271       }
272
273       /* Convert that seek to a seeking in bytes at position 0,
274          FIXME: could use an index */
275       ret = gst_pad_push_event (self->sinkpad,
276           gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
277               GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
278
279       if (ret) {
280         /* Apply the seek to our segment */
281         gst_segment_do_seek (&self->segment, rate, format, flags,
282             start_type, start, stop_type, stop, &update);
283
284         GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
285             &self->segment);
286
287         /* will mark need_segment when receiving segment from upstream,
288          * after FLUSH and all that has happened,
289          * rather than racing with chain */
290       } else {
291         GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
292       }
293
294       gst_event_unref (event);
295       break;
296     }
297     default:
298       ret = gst_pad_event_default (pad, parent, event);
299       break;
300   }
301
302 beach:
303   return ret;
304 }
305
306 static void
307 gst_sub_parse_set_property (GObject * object, guint prop_id,
308     const GValue * value, GParamSpec * pspec)
309 {
310   GstSubParse *subparse = GST_SUBPARSE (object);
311
312   GST_OBJECT_LOCK (subparse);
313   switch (prop_id) {
314     case PROP_ENCODING:
315       g_free (subparse->encoding);
316       subparse->encoding = g_value_dup_string (value);
317       GST_LOG_OBJECT (object, "subtitle encoding set to %s",
318           GST_STR_NULL (subparse->encoding));
319       break;
320     case PROP_VIDEOFPS:
321     {
322       subparse->fps_n = gst_value_get_fraction_numerator (value);
323       subparse->fps_d = gst_value_get_fraction_denominator (value);
324       GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
325           subparse->fps_d);
326
327       if (!subparse->state.have_internal_fps) {
328         subparse->state.fps_n = subparse->fps_n;
329         subparse->state.fps_d = subparse->fps_d;
330       }
331       break;
332     }
333     default:
334       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
335       break;
336   }
337   GST_OBJECT_UNLOCK (subparse);
338 }
339
340 static void
341 gst_sub_parse_get_property (GObject * object, guint prop_id,
342     GValue * value, GParamSpec * pspec)
343 {
344   GstSubParse *subparse = GST_SUBPARSE (object);
345
346   GST_OBJECT_LOCK (subparse);
347   switch (prop_id) {
348     case PROP_ENCODING:
349       g_value_set_string (value, subparse->encoding);
350       break;
351     case PROP_VIDEOFPS:
352       gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
353       break;
354     default:
355       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
356       break;
357   }
358   GST_OBJECT_UNLOCK (subparse);
359 }
360
361 static const gchar *
362 gst_sub_parse_get_format_description (GstSubParseFormat format)
363 {
364   switch (format) {
365     case GST_SUB_PARSE_FORMAT_MDVDSUB:
366       return "MicroDVD";
367     case GST_SUB_PARSE_FORMAT_SUBRIP:
368       return "SubRip";
369     case GST_SUB_PARSE_FORMAT_MPSUB:
370       return "MPSub";
371     case GST_SUB_PARSE_FORMAT_SAMI:
372       return "SAMI";
373     case GST_SUB_PARSE_FORMAT_TMPLAYER:
374       return "TMPlayer";
375     case GST_SUB_PARSE_FORMAT_MPL2:
376       return "MPL2";
377     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
378       return "SubViewer";
379     case GST_SUB_PARSE_FORMAT_DKS:
380       return "DKS";
381     case GST_SUB_PARSE_FORMAT_VTT:
382       return "WebVTT";
383     case GST_SUB_PARSE_FORMAT_QTTEXT:
384       return "QTtext";
385     case GST_SUB_PARSE_FORMAT_LRC:
386       return "LRC";
387     default:
388     case GST_SUB_PARSE_FORMAT_UNKNOWN:
389       break;
390   }
391   return NULL;
392 }
393
394 static gchar *
395 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
396     gsize * consumed, GError ** err)
397 {
398   gchar *ret = NULL;
399
400   *consumed = 0;
401   /* The char cast is necessary in glib < 2.24 */
402   ret =
403       g_convert_with_fallback (str, len, "UTF-8", encoding, (char *) "*",
404       consumed, NULL, err);
405   if (ret == NULL)
406     return ret;
407
408   /* + 3 to skip UTF-8 BOM if it was added */
409   len = strlen (ret);
410   if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
411       && (guint8) ret[2] == 0xBF)
412     memmove (ret, ret + 3, len + 1 - 3);
413
414   return ret;
415 }
416
417 static gchar *
418 detect_encoding (const gchar * str, gsize len)
419 {
420   if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
421       && (guint8) str[2] == 0xBF)
422     return g_strdup ("UTF-8");
423
424   if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
425     return g_strdup ("UTF-16BE");
426
427   if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
428     return g_strdup ("UTF-16LE");
429
430   if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
431       && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
432     return g_strdup ("UTF-32BE");
433
434   if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
435       && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
436     return g_strdup ("UTF-32LE");
437
438   return NULL;
439 }
440
441 static gchar *
442 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
443     gsize * consumed)
444 {
445   const gchar *encoding;
446   GError *err = NULL;
447   gchar *ret = NULL;
448
449   *consumed = 0;
450
451   /* First try any detected encoding */
452   if (self->detected_encoding) {
453     ret =
454         gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
455
456     if (!err)
457       return ret;
458
459     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
460         self->detected_encoding, err->message);
461     g_free (self->detected_encoding);
462     self->detected_encoding = NULL;
463     g_clear_error (&err);
464   }
465
466   /* Otherwise check if it's UTF8 */
467   if (self->valid_utf8) {
468     if (g_utf8_validate (str, len, NULL)) {
469       GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
470       *consumed = len;
471       return g_strndup (str, len);
472     }
473     GST_INFO_OBJECT (self, "invalid UTF-8!");
474     self->valid_utf8 = FALSE;
475   }
476
477   /* Else try fallback */
478   encoding = self->encoding;
479   if (encoding == NULL || *encoding == '\0') {
480     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
481   }
482   if (encoding == NULL || *encoding == '\0') {
483     /* if local encoding is UTF-8 and no encoding specified
484      * via the environment variable, assume ISO-8859-15 */
485     if (g_get_charset (&encoding)) {
486       encoding = "ISO-8859-15";
487     }
488   }
489
490   ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
491
492   if (err) {
493     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
494         encoding, err->message);
495     g_clear_error (&err);
496
497     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
498     ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
499   }
500
501   GST_LOG_OBJECT (self,
502       "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
503       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
504
505   return ret;
506 }
507
508 static gchar *
509 get_next_line (GstSubParse * self)
510 {
511   char *line = NULL;
512   const char *line_end;
513   int line_len;
514   gboolean have_r = FALSE;
515
516   line_end = strchr (self->textbuf->str, '\n');
517
518   if (!line_end) {
519     /* end-of-line not found; return for more data */
520     return NULL;
521   }
522
523   /* get rid of '\r' */
524   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
525     line_end--;
526     have_r = TRUE;
527   }
528
529   line_len = line_end - self->textbuf->str;
530   line = g_strndup (self->textbuf->str, line_len);
531   self->textbuf = g_string_erase (self->textbuf, 0,
532       line_len + (have_r ? 2 : 1));
533   return line;
534 }
535
536 static gchar *
537 parse_mdvdsub (ParserState * state, const gchar * line)
538 {
539   const gchar *line_split;
540   gchar *line_chunk;
541   guint start_frame, end_frame;
542   guint64 clip_start = 0, clip_stop = 0;
543   gboolean in_seg = FALSE;
544   GString *markup;
545   gchar *ret;
546
547   /* style variables */
548   gboolean italic;
549   gboolean bold;
550   guint fontsize;
551   gdouble fps = 0.0;
552
553   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
554     g_warning ("Parse of the following line, assumed to be in microdvd .sub"
555         " format, failed:\n%s", line);
556     return NULL;
557   }
558
559   /* skip the {%u}{%u} part */
560   line = strchr (line, '}') + 1;
561   line = strchr (line, '}') + 1;
562
563   /* see if there's a first line with a framerate */
564   if (start_frame == 1 && end_frame == 1) {
565     gchar *rest, *end = NULL;
566
567     rest = g_strdup (line);
568     g_strdelimit (rest, ",", '.');
569     fps = g_ascii_strtod (rest, &end);
570     if (end != rest) {
571       gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
572       GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
573           state->fps_d, rest);
574     }
575     g_free (rest);
576     return NULL;
577   }
578
579   state->start_time =
580       gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
581       state->fps_n);
582   state->duration =
583       gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
584       state->fps_n);
585
586   /* Check our segment start/stop */
587   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
588       state->start_time, state->start_time + state->duration, &clip_start,
589       &clip_stop);
590
591   /* No need to parse that text if it's out of segment */
592   if (in_seg) {
593     state->start_time = clip_start;
594     state->duration = clip_stop - clip_start;
595   } else {
596     return NULL;
597   }
598
599   markup = g_string_new (NULL);
600   while (1) {
601     italic = FALSE;
602     bold = FALSE;
603     fontsize = 0;
604     /* parse style markup */
605     if (strncmp (line, "{y:i}", 5) == 0) {
606       italic = TRUE;
607       line = strchr (line, '}') + 1;
608     }
609     if (strncmp (line, "{y:b}", 5) == 0) {
610       bold = TRUE;
611       line = strchr (line, '}') + 1;
612     }
613     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
614       line = strchr (line, '}') + 1;
615     }
616     /* forward slashes at beginning/end signify italics too */
617     if (g_str_has_prefix (line, "/")) {
618       italic = TRUE;
619       ++line;
620     }
621     if ((line_split = strchr (line, '|')))
622       line_chunk = g_markup_escape_text (line, line_split - line);
623     else
624       line_chunk = g_markup_escape_text (line, strlen (line));
625
626     /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
627      * always at the end of a line or can they span multiple lines?) */
628     if (g_str_has_suffix (line_chunk, "/")) {
629       line_chunk[strlen (line_chunk) - 1] = '\0';
630     }
631
632     markup = g_string_append (markup, "<span");
633     if (italic)
634       g_string_append (markup, " style=\"italic\"");
635     if (bold)
636       g_string_append (markup, " weight=\"bold\"");
637     if (fontsize)
638       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
639     g_string_append_printf (markup, ">%s</span>", line_chunk);
640     g_free (line_chunk);
641     if (line_split) {
642       g_string_append (markup, "\n");
643       line = line_split + 1;
644     } else {
645       break;
646     }
647   }
648   ret = markup->str;
649   g_string_free (markup, FALSE);
650   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
651       state->start_time / (double) GST_SECOND,
652       state->duration / (double) GST_SECOND, ret);
653   return ret;
654 }
655
656 static void
657 strip_trailing_newlines (gchar * txt)
658 {
659   if (txt) {
660     guint len;
661
662     len = strlen (txt);
663     while (len > 1 && txt[len - 1] == '\n') {
664       txt[len - 1] = '\0';
665       --len;
666     }
667   }
668 }
669
670 /* we want to escape text in general, but retain basic markup like
671  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
672  * just unescape a white list of allowed markups again after
673  * escaping everything (the text between these simple markers isn't
674  * necessarily escaped, so it seems best to do it like this) */
675 static void
676 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
677     gboolean allows_tag_attributes)
678 {
679   gchar *res;
680   GRegex *tag_regex;
681   gchar *allowed_tags_pattern, *search_pattern;
682   const gchar *replace_pattern;
683
684   /* No processing needed if no escaped tag marker found in the string. */
685   if (strstr (txt, "&lt;") == NULL)
686     return;
687
688   /* Build a list of alternates for our regexp.
689    * FIXME: Could be built once and stored */
690   allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
691   /* Look for starting/ending escaped tags with optional attributes. */
692   search_pattern = g_strdup_printf ("&lt;(/)?\\ *(%s)(%s)&gt;",
693       allowed_tags_pattern, ATTRIBUTE_REGEX);
694   /* And unescape appropriately */
695   if (allows_tag_attributes) {
696     replace_pattern = "<\\1\\2\\3>";
697   } else {
698     replace_pattern = "<\\1\\2>";
699   }
700
701   tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
702   res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
703       replace_pattern, 0, NULL);
704
705   /* res will always be shorter than the input or identical, so this
706    * copy is OK */
707   strcpy (txt, res);
708
709   g_free (res);
710   g_free (search_pattern);
711   g_free (allowed_tags_pattern);
712
713   g_regex_unref (tag_regex);
714 }
715
716
717 static gboolean
718 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
719 {
720   gchar *tag, saved;
721
722   tag = start + strlen ("&lt;");
723   if (*tag == '/')
724     ++tag;
725
726   if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
727     return FALSE;
728
729   saved = *stop;
730   *stop = '\0';
731   GST_LOG ("removing unhandled tag '%s'", start);
732   *stop = saved;
733   memmove (start, stop, strlen (stop) + 1);
734   return TRUE;
735 }
736
737 /* remove tags we haven't explicitly allowed earlier on, like font tags
738  * for example */
739 static void
740 subrip_remove_unhandled_tags (gchar * txt)
741 {
742   gchar *pos, *gt;
743
744   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
745     if (strncmp (pos, "&lt;", 4) == 0 && (gt = strstr (pos + 4, "&gt;"))) {
746       if (subrip_remove_unhandled_tag (pos, gt + strlen ("&gt;")))
747         --pos;
748     }
749   }
750 }
751
752 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
753  * take a simple approach. This code assumes the input has been
754  * escaped and subrip_unescape_formatting() has then been run over the
755  * input! This function adds missing closing markup tags and removes
756  * broken closing tags for tags that have never been opened. */
757 static void
758 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
759 {
760   gchar *cur, *next_tag;
761   gchar *open_tags[32];
762   guint num_open_tags = 0;
763   const gchar *iter_tag;
764   guint offset = 0;
765   guint index;
766   gchar *cur_tag;
767   gchar *end_tag;
768   GRegex *tag_regex;
769   GMatchInfo *match_info;
770   gchar **allowed_tags = (gchar **) allowed_tags_ptr;
771
772   g_assert (*p_txt != NULL);
773
774   cur = *p_txt;
775   while (*cur != '\0') {
776     next_tag = strchr (cur, '<');
777     if (next_tag == NULL)
778       break;
779     offset = 0;
780     index = 0;
781     while (index < g_strv_length (allowed_tags)) {
782       iter_tag = allowed_tags[index];
783       /* Look for a white listed tag */
784       cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
785       tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
786       (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
787
788       if (g_match_info_matches (match_info)) {
789         gint start_pos, end_pos;
790         gchar *word = g_match_info_fetch (match_info, 0);
791         g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
792         if (start_pos == 0) {
793           offset = strlen (word);
794         }
795         g_free (word);
796       }
797       g_match_info_free (match_info);
798       g_regex_unref (tag_regex);
799       g_free (cur_tag);
800       index++;
801       if (offset) {
802         /* OK we found a tag, let's keep track of it */
803         open_tags[num_open_tags] = g_strdup (iter_tag);
804         ++num_open_tags;
805         break;
806       }
807     }
808
809     if (offset) {
810       next_tag += offset;
811       cur = next_tag;
812       continue;
813     }
814
815     if (*next_tag == '<' && *(next_tag + 1) == '/') {
816       end_tag = strchr (cur, '>');
817       if (end_tag) {
818         if (num_open_tags == 0
819             || g_ascii_strncasecmp (end_tag - 1, open_tags[num_open_tags - 1],
820                 strlen (open_tags[num_open_tags - 1]))) {
821           GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
822           memmove (next_tag, end_tag + 1, strlen (end_tag) + 1);
823           next_tag -= strlen (end_tag);
824         } else {
825           --num_open_tags;
826           g_free (open_tags[num_open_tags]);
827         }
828       }
829     }
830     ++next_tag;
831     cur = next_tag;
832   }
833
834   if (num_open_tags > 0) {
835     GString *s;
836
837     s = g_string_new (*p_txt);
838     while (num_open_tags > 0) {
839       GST_LOG ("adding missing closing tag '%s'", open_tags[num_open_tags - 1]);
840       g_string_append_c (s, '<');
841       g_string_append_c (s, '/');
842       g_string_append (s, open_tags[num_open_tags - 1]);
843       g_string_append_c (s, '>');
844       g_free (open_tags[num_open_tags - 1]);
845       --num_open_tags;
846     }
847     g_free (*p_txt);
848     *p_txt = g_string_free (s, FALSE);
849   }
850 }
851
852 static gboolean
853 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
854 {
855   gchar s[128] = { '\0', };
856   gchar *end, *p;
857   guint hour, min, sec, msec, len;
858
859   while (*ts_string == ' ')
860     ++ts_string;
861
862   g_strlcpy (s, ts_string, sizeof (s));
863   if ((end = strstr (s, "-->")))
864     *end = '\0';
865   g_strchomp (s);
866
867   /* ms may be in these formats:
868    * hh:mm:ss,500 = 500ms
869    * hh:mm:ss,  5 =   5ms
870    * hh:mm:ss, 5  =  50ms
871    * hh:mm:ss, 50 =  50ms
872    * hh:mm:ss,5   = 500ms
873    * and the same with . instead of ,.
874    * sscanf() doesn't differentiate between '  5' and '5' so munge
875    * the white spaces within the timestamp to '0' (I'm sure there's a
876    * way to make sscanf() do this for us, but how?)
877    */
878   g_strdelimit (s, " ", '0');
879   g_strdelimit (s, ".", ',');
880
881   /* make sure we have exactly three digits after he comma */
882   p = strchr (s, ',');
883   g_assert (p != NULL);
884   ++p;
885   len = strlen (p);
886   if (len > 3) {
887     p[3] = '\0';
888   } else
889     while (len < 3) {
890       g_strlcat (&p[len], "0", 2);
891       ++len;
892     }
893
894   GST_LOG ("parsing timestamp '%s'", s);
895   if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
896     GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
897     return FALSE;
898   }
899
900   *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
901   return TRUE;
902 }
903
904 /* cue settings are part of the WebVTT specification. They are
905  * declared after the time interval in the first line of the
906  * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
907  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
908  */
909 static void
910 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
911 {
912   gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
913   gint i = 0;
914   gint16 text_position, text_size;
915   gint16 line_position;
916   gboolean vertical_found = FALSE;
917   gboolean alignment_found = FALSE;
918
919   while (i < g_strv_length (splitted_settings)) {
920     gboolean valid_tag = FALSE;
921     switch (splitted_settings[i][0]) {
922       case 'T':
923         if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
924                 &text_position) > 0) {
925           state->text_position = (guint8) text_position;
926           valid_tag = TRUE;
927         }
928         break;
929       case 'D':
930         if (strlen (splitted_settings[i]) > 2) {
931           vertical_found = TRUE;
932           g_free (state->vertical);
933           state->vertical = g_strdup (splitted_settings[i] + 2);
934           valid_tag = TRUE;
935         }
936         break;
937       case 'L':
938         if (g_str_has_suffix (splitted_settings[i], "%")) {
939           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
940                   &line_position) > 0) {
941             state->line_position = line_position;
942             valid_tag = TRUE;
943           }
944         } else {
945           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
946                   &line_position) > 0) {
947             state->line_number = line_position;
948             valid_tag = TRUE;
949           }
950         }
951         break;
952       case 'S':
953         if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
954                 &text_size) > 0) {
955           state->text_size = (guint8) text_size;
956           valid_tag = TRUE;
957         }
958         break;
959       case 'A':
960         if (strlen (splitted_settings[i]) > 2) {
961           g_free (state->alignment);
962           state->alignment = g_strdup (splitted_settings[i] + 2);
963           alignment_found = TRUE;
964           valid_tag = TRUE;
965         }
966         break;
967       default:
968         break;
969     }
970     if (!valid_tag) {
971       GST_LOG ("Invalid or unrecognised setting found: %s",
972           splitted_settings[i]);
973     }
974     i++;
975   }
976   g_strfreev (splitted_settings);
977   if (!vertical_found) {
978     g_free (state->vertical);
979     state->vertical = g_strdup ("");
980   }
981   if (!alignment_found) {
982     g_free (state->alignment);
983     state->alignment = g_strdup ("");
984   }
985 }
986
987 static gchar *
988 parse_subrip (ParserState * state, const gchar * line)
989 {
990   gchar *ret;
991
992   switch (state->state) {
993     case 0:{
994       char *endptr;
995       guint64 id;
996
997       /* looking for a single integer as a Cue ID, but we
998        * don't actually use it */
999       errno = 0;
1000       id = g_ascii_strtoull (line, &endptr, 10);
1001       if (id == G_MAXUINT64 && errno == ERANGE)
1002         state->state = 1;
1003       else if (id == 0 && errno == EINVAL)
1004         state->state = 1;
1005       else if (endptr != line && *endptr == '\0')
1006         state->state = 1;
1007       return NULL;
1008     }
1009     case 1:
1010     {
1011       GstClockTime ts_start, ts_end;
1012       gchar *end_time;
1013
1014       /* looking for start_time --> end_time */
1015       if ((end_time = strstr (line, " --> ")) &&
1016           parse_subrip_time (line, &ts_start) &&
1017           parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1018           state->start_time <= ts_end) {
1019         state->state = 2;
1020         state->start_time = ts_start;
1021         state->duration = ts_end - ts_start;
1022       } else {
1023         GST_DEBUG ("error parsing subrip time line '%s'", line);
1024         state->state = 0;
1025       }
1026       return NULL;
1027     }
1028     case 2:
1029     {
1030       /* No need to parse that text if it's out of segment */
1031       guint64 clip_start = 0, clip_stop = 0;
1032       gboolean in_seg = FALSE;
1033
1034       /* Check our segment start/stop */
1035       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1036           state->start_time, state->start_time + state->duration,
1037           &clip_start, &clip_stop);
1038
1039       if (in_seg) {
1040         state->start_time = clip_start;
1041         state->duration = clip_stop - clip_start;
1042       } else {
1043         state->state = 0;
1044         return NULL;
1045       }
1046     }
1047       /* looking for subtitle text; empty line ends this subtitle entry */
1048       if (state->buf->len)
1049         g_string_append_c (state->buf, '\n');
1050       g_string_append (state->buf, line);
1051       if (strlen (line) == 0) {
1052         ret = g_markup_escape_text (state->buf->str, state->buf->len);
1053         g_string_truncate (state->buf, 0);
1054         state->state = 0;
1055         subrip_unescape_formatting (ret, state->allowed_tags,
1056             state->allows_tag_attributes);
1057         subrip_remove_unhandled_tags (ret);
1058         strip_trailing_newlines (ret);
1059         subrip_fix_up_markup (&ret, state->allowed_tags);
1060         return ret;
1061       }
1062       return NULL;
1063     default:
1064       g_return_val_if_reached (NULL);
1065   }
1066 }
1067
1068 static gchar *
1069 parse_lrc (ParserState * state, const gchar * line)
1070 {
1071   gint m, s, c;
1072   const gchar *start;
1073   gint milli;
1074
1075   if (line[0] != '[')
1076     return NULL;
1077
1078   if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1079       sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1080     return NULL;
1081
1082   start = strchr (line, ']');
1083   if (start - line == 9)
1084     milli = 10;
1085   else
1086     milli = 1;
1087
1088   state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1089       + gst_util_uint64_scale (s, GST_SECOND, 1)
1090       + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1091   state->duration = GST_CLOCK_TIME_NONE;
1092
1093   return g_strdup (start + 1);
1094 }
1095
1096 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1097  * element. This format is similar to Subrip, the biggest differences
1098  * are that there can be cue settings detailing how to display the cue
1099  * text and more markup tags are allowed.
1100  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1101  */
1102 static gchar *
1103 parse_webvtt (ParserState * state, const gchar * line)
1104 {
1105   /* Cue IDs are optional in WebVTT, but not in subrip,
1106    * so when in state 0 (cue ID), also check if we're
1107    * already at the start --> end time marker */
1108   if (state->state == 0 || state->state == 1) {
1109     GstClockTime ts_start, ts_end;
1110     gchar *end_time;
1111     gchar *cue_settings = NULL;
1112
1113     /* looking for start_time --> end_time */
1114     if ((end_time = strstr (line, " --> ")) &&
1115         parse_subrip_time (line, &ts_start) &&
1116         parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1117         state->start_time <= ts_end) {
1118       state->state = 2;
1119       state->start_time = ts_start;
1120       state->duration = ts_end - ts_start;
1121       cue_settings = strstr (end_time + strlen (" --> "), " ");
1122     } else {
1123       GST_DEBUG ("error parsing subrip time line '%s'", line);
1124       state->state = 0;
1125     }
1126
1127     state->text_position = 0;
1128     state->text_size = 0;
1129     state->line_position = 0;
1130     state->line_number = 0;
1131
1132     if (cue_settings)
1133       parse_webvtt_cue_settings (state, cue_settings + 1);
1134     else {
1135       g_free (state->vertical);
1136       state->vertical = g_strdup ("");
1137       g_free (state->alignment);
1138       state->alignment = g_strdup ("");
1139     }
1140
1141     return NULL;
1142   } else
1143     return parse_subrip (state, line);
1144 }
1145
1146 static void
1147 unescape_newlines_br (gchar * read)
1148 {
1149   gchar *write = read;
1150
1151   /* Replace all occurences of '[br]' with a newline as version 2
1152    * of the subviewer format uses this for newlines */
1153
1154   if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1155     return;
1156
1157   do {
1158     if (strncmp (read, "[br]", 4) == 0) {
1159       *write = '\n';
1160       read += 4;
1161     } else {
1162       *write = *read;
1163       read++;
1164     }
1165     write++;
1166   } while (*read);
1167
1168   *write = '\0';
1169 }
1170
1171 static gchar *
1172 parse_subviewer (ParserState * state, const gchar * line)
1173 {
1174   guint h1, m1, s1, ms1;
1175   guint h2, m2, s2, ms2;
1176   gchar *ret;
1177
1178   /* TODO: Maybe also parse the fields in the header, especially DELAY.
1179    * For examples see the unit test or
1180    * http://www.doom9.org/index.html?/sub.htm */
1181
1182   switch (state->state) {
1183     case 0:
1184       /* looking for start_time,end_time */
1185       if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1186               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1187         state->state = 1;
1188         state->start_time =
1189             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1190             ms1 * GST_MSECOND;
1191         state->duration =
1192             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1193             ms2 * GST_MSECOND - state->start_time;
1194       }
1195       return NULL;
1196     case 1:
1197     {
1198       /* No need to parse that text if it's out of segment */
1199       guint64 clip_start = 0, clip_stop = 0;
1200       gboolean in_seg = FALSE;
1201
1202       /* Check our segment start/stop */
1203       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1204           state->start_time, state->start_time + state->duration,
1205           &clip_start, &clip_stop);
1206
1207       if (in_seg) {
1208         state->start_time = clip_start;
1209         state->duration = clip_stop - clip_start;
1210       } else {
1211         state->state = 0;
1212         return NULL;
1213       }
1214     }
1215       /* looking for subtitle text; empty line ends this subtitle entry */
1216       if (state->buf->len)
1217         g_string_append_c (state->buf, '\n');
1218       g_string_append (state->buf, line);
1219       if (strlen (line) == 0) {
1220         ret = g_strdup (state->buf->str);
1221         unescape_newlines_br (ret);
1222         strip_trailing_newlines (ret);
1223         g_string_truncate (state->buf, 0);
1224         state->state = 0;
1225         return ret;
1226       }
1227       return NULL;
1228     default:
1229       g_assert_not_reached ();
1230       return NULL;
1231   }
1232 }
1233
1234 static gchar *
1235 parse_mpsub (ParserState * state, const gchar * line)
1236 {
1237   gchar *ret;
1238   float t1, t2;
1239
1240   switch (state->state) {
1241     case 0:
1242       /* looking for two floats (offset, duration) */
1243       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1244         state->state = 1;
1245         state->start_time += state->duration + GST_SECOND * t1;
1246         state->duration = GST_SECOND * t2;
1247       }
1248       return NULL;
1249     case 1:
1250     {                           /* No need to parse that text if it's out of segment */
1251       guint64 clip_start = 0, clip_stop = 0;
1252       gboolean in_seg = FALSE;
1253
1254       /* Check our segment start/stop */
1255       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1256           state->start_time, state->start_time + state->duration,
1257           &clip_start, &clip_stop);
1258
1259       if (in_seg) {
1260         state->start_time = clip_start;
1261         state->duration = clip_stop - clip_start;
1262       } else {
1263         state->state = 0;
1264         return NULL;
1265       }
1266     }
1267       /* looking for subtitle text; empty line ends this
1268        * subtitle entry */
1269       if (state->buf->len)
1270         g_string_append_c (state->buf, '\n');
1271       g_string_append (state->buf, line);
1272       if (strlen (line) == 0) {
1273         ret = g_strdup (state->buf->str);
1274         g_string_truncate (state->buf, 0);
1275         state->state = 0;
1276         return ret;
1277       }
1278       return NULL;
1279     default:
1280       g_assert_not_reached ();
1281       return NULL;
1282   }
1283 }
1284
1285 static const gchar *
1286 dks_skip_timestamp (const gchar * line)
1287 {
1288   while (*line && *line != ']')
1289     line++;
1290   if (*line == ']')
1291     line++;
1292   return line;
1293 }
1294
1295 static gchar *
1296 parse_dks (ParserState * state, const gchar * line)
1297 {
1298   guint h, m, s;
1299
1300   switch (state->state) {
1301     case 0:
1302       /* Looking for the start time and text */
1303       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1304         const gchar *text;
1305         state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1306         text = dks_skip_timestamp (line);
1307         if (*text) {
1308           state->state = 1;
1309           g_string_append (state->buf, text);
1310         }
1311       }
1312       return NULL;
1313     case 1:
1314     {
1315       guint64 clip_start = 0, clip_stop = 0;
1316       gboolean in_seg;
1317       gchar *ret;
1318
1319       /* Looking for the end time */
1320       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1321         state->state = 0;
1322         state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1323             state->start_time;
1324       } else {
1325         GST_WARNING ("Failed to parse subtitle end time");
1326         return NULL;
1327       }
1328
1329       /* Check if this subtitle is out of the current segment */
1330       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1331           state->start_time, state->start_time + state->duration,
1332           &clip_start, &clip_stop);
1333
1334       if (!in_seg) {
1335         return NULL;
1336       }
1337
1338       state->start_time = clip_start;
1339       state->duration = clip_stop - clip_start;
1340
1341       ret = g_strdup (state->buf->str);
1342       g_string_truncate (state->buf, 0);
1343       unescape_newlines_br (ret);
1344       return ret;
1345     }
1346     default:
1347       g_assert_not_reached ();
1348       return NULL;
1349   }
1350 }
1351
1352 static void
1353 parser_state_init (ParserState * state)
1354 {
1355   GST_DEBUG ("initialising parser");
1356
1357   if (state->buf) {
1358     g_string_truncate (state->buf, 0);
1359   } else {
1360     state->buf = g_string_new (NULL);
1361   }
1362
1363   state->start_time = 0;
1364   state->duration = 0;
1365   state->max_duration = 0;      /* no limit */
1366   state->state = 0;
1367   state->segment = NULL;
1368 }
1369
1370 static void
1371 parser_state_dispose (GstSubParse * self, ParserState * state)
1372 {
1373   if (state->buf) {
1374     g_string_free (state->buf, TRUE);
1375     state->buf = NULL;
1376   }
1377
1378   g_free (state->vertical);
1379   state->vertical = NULL;
1380   g_free (state->alignment);
1381   state->alignment = NULL;
1382
1383   if (state->user_data) {
1384     switch (self->parser_type) {
1385       case GST_SUB_PARSE_FORMAT_QTTEXT:
1386         qttext_context_deinit (state);
1387         break;
1388       case GST_SUB_PARSE_FORMAT_SAMI:
1389         sami_context_deinit (state);
1390         break;
1391       default:
1392         break;
1393     }
1394   }
1395   state->allowed_tags = NULL;
1396 }
1397
1398 /* regex type enum */
1399 typedef enum
1400 {
1401   GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1402   GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1403   GST_SUB_PARSE_REGEX_SUBRIP = 2,
1404   GST_SUB_PARSE_REGEX_DKS = 3,
1405   GST_SUB_PARSE_REGEX_VTT = 4,
1406 } GstSubParseRegex;
1407
1408 static gpointer
1409 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1410 {
1411   gpointer result = NULL;
1412   GError *gerr = NULL;
1413   switch (regtype) {
1414     case GST_SUB_PARSE_REGEX_MDVDSUB:
1415       result =
1416           (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}",
1417           G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1418       if (result == NULL) {
1419         g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1420         g_clear_error (&gerr);
1421       }
1422       break;
1423     case GST_SUB_PARSE_REGEX_SUBRIP:
1424       result = (gpointer)
1425           g_regex_new ("^[\\s\\n]*[\\n]? {0,3}[ 0-9]{1,4}\\s*(\x0d)?\x0a"
1426           " ?[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,3}"
1427           " +--> +[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,2}",
1428           G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1429       if (result == NULL) {
1430         g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1431         g_clear_error (&gerr);
1432       }
1433       break;
1434     case GST_SUB_PARSE_REGEX_DKS:
1435       result = (gpointer) g_regex_new ("^\\[[0-9]+:[0-9]+:[0-9]+\\].*",
1436           G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1437       if (result == NULL) {
1438         g_warning ("Compilation of dks regex failed: %s", gerr->message);
1439         g_clear_error (&gerr);
1440       }
1441       break;
1442     case GST_SUB_PARSE_REGEX_VTT:
1443       result = (gpointer)
1444           g_regex_new ("^(\\xef\\xbb\\xbf)?WEBVTT[\\xa\\xd\\x20\\x9]", 0, 0,
1445           &gerr);
1446       if (result == NULL) {
1447         g_warning ("Compilation of vtt regex failed: %s", gerr->message);
1448         g_error_free (gerr);
1449       }
1450       break;
1451
1452     default:
1453       GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1454   }
1455   return result;
1456 }
1457
1458 /*
1459  * FIXME: maybe we should pass along a second argument, the preceding
1460  * text buffer, because that is how this originally worked, even though
1461  * I don't really see the use of that.
1462  */
1463
1464 static GstSubParseFormat
1465 gst_sub_parse_data_format_autodetect (gchar * match_str)
1466 {
1467   guint n1, n2, n3;
1468
1469   static GOnce mdvd_rx_once = G_ONCE_INIT;
1470   static GOnce subrip_rx_once = G_ONCE_INIT;
1471   static GOnce dks_rx_once = G_ONCE_INIT;
1472   static GOnce vtt_rx_once = G_ONCE_INIT;
1473
1474   GRegex *mdvd_grx;
1475   GRegex *subrip_grx;
1476   GRegex *dks_grx;
1477   GRegex *vtt_grx;
1478
1479   g_once (&mdvd_rx_once,
1480       (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1481       (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1482   g_once (&subrip_rx_once,
1483       (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1484       (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1485   g_once (&dks_rx_once,
1486       (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1487       (gpointer) GST_SUB_PARSE_REGEX_DKS);
1488   g_once (&vtt_rx_once,
1489       (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1490       (gpointer) GST_SUB_PARSE_REGEX_VTT);
1491
1492   mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1493   subrip_grx = (GRegex *) subrip_rx_once.retval;
1494   dks_grx = (GRegex *) dks_rx_once.retval;
1495   vtt_grx = (GRegex *) vtt_rx_once.retval;
1496
1497   if (g_regex_match (mdvd_grx, match_str, 0, NULL)) {
1498     GST_LOG ("MicroDVD (frame based) format detected");
1499     return GST_SUB_PARSE_FORMAT_MDVDSUB;
1500   }
1501   if (g_regex_match (subrip_grx, match_str, 0, NULL)) {
1502     GST_LOG ("SubRip (time based) format detected");
1503     return GST_SUB_PARSE_FORMAT_SUBRIP;
1504   }
1505   if (g_regex_match (dks_grx, match_str, 0, NULL)) {
1506     GST_LOG ("DKS (time based) format detected");
1507     return GST_SUB_PARSE_FORMAT_DKS;
1508   }
1509   if (g_regex_match (vtt_grx, match_str, 0, NULL) == TRUE) {
1510     GST_LOG ("WebVTT (time based) format detected");
1511     return GST_SUB_PARSE_FORMAT_VTT;
1512   }
1513
1514   if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1515     GST_LOG ("MPSub (time based) format detected");
1516     return GST_SUB_PARSE_FORMAT_MPSUB;
1517   }
1518   if (strstr (match_str, "<SAMI>") != NULL ||
1519       strstr (match_str, "<sami>") != NULL) {
1520     GST_LOG ("SAMI (time based) format detected");
1521     return GST_SUB_PARSE_FORMAT_SAMI;
1522   }
1523   /* we're boldly assuming the first subtitle appears within the first hour */
1524   if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1525       sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1526       sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1527       sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1528       sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1529     GST_LOG ("TMPlayer (time based) format detected");
1530     return GST_SUB_PARSE_FORMAT_TMPLAYER;
1531   }
1532   if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1533     GST_LOG ("MPL2 (time based) format detected");
1534     return GST_SUB_PARSE_FORMAT_MPL2;
1535   }
1536   if (strstr (match_str, "[INFORMATION]") != NULL) {
1537     GST_LOG ("SubViewer (time based) format detected");
1538     return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1539   }
1540   if (strstr (match_str, "{QTtext}") != NULL) {
1541     GST_LOG ("QTtext (time based) format detected");
1542     return GST_SUB_PARSE_FORMAT_QTTEXT;
1543   }
1544   /* We assume the LRC file starts immediately */
1545   if (match_str[0] == '[') {
1546     gboolean all_lines_good = TRUE;
1547     gchar **split;
1548     gchar **ptr;
1549
1550     ptr = split = g_strsplit (match_str, "\n", -1);
1551     while (*ptr && *(ptr + 1)) {
1552       gchar *str = *ptr;
1553       gint len = strlen (str);
1554
1555       if (sscanf (str, "[%u:%02u.%02u]", &n1, &n2, &n3) == 3 ||
1556           sscanf (str, "[%u:%02u.%03u]", &n1, &n2, &n3) == 3) {
1557         all_lines_good = TRUE;
1558       } else if (str[len - 1] == ']' && strchr (str, ':') != NULL) {
1559         all_lines_good = TRUE;
1560       } else {
1561         all_lines_good = FALSE;
1562         break;
1563       }
1564
1565       ptr++;
1566     }
1567     g_strfreev (split);
1568
1569     if (all_lines_good)
1570       return GST_SUB_PARSE_FORMAT_LRC;
1571   }
1572
1573   GST_DEBUG ("no subtitle format detected");
1574   return GST_SUB_PARSE_FORMAT_UNKNOWN;
1575 }
1576
1577 static GstCaps *
1578 gst_sub_parse_format_autodetect (GstSubParse * self)
1579 {
1580   gchar *data;
1581   GstSubParseFormat format;
1582
1583   if (strlen (self->textbuf->str) < 30) {
1584     GST_DEBUG ("File too small to be a subtitles file");
1585     return NULL;
1586   }
1587
1588   data = g_strndup (self->textbuf->str, 35);
1589   format = gst_sub_parse_data_format_autodetect (data);
1590   g_free (data);
1591
1592   self->parser_type = format;
1593   self->subtitle_codec = gst_sub_parse_get_format_description (format);
1594   parser_state_init (&self->state);
1595   self->state.allowed_tags = NULL;
1596
1597   switch (format) {
1598     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1599       self->parse_line = parse_mdvdsub;
1600       return gst_caps_new_simple ("text/x-raw",
1601           "format", G_TYPE_STRING, "pango-markup", NULL);
1602     case GST_SUB_PARSE_FORMAT_SUBRIP:
1603       self->state.allowed_tags = (gpointer) allowed_srt_tags;
1604       self->state.allows_tag_attributes = FALSE;
1605       self->parse_line = parse_subrip;
1606       return gst_caps_new_simple ("text/x-raw",
1607           "format", G_TYPE_STRING, "pango-markup", NULL);
1608     case GST_SUB_PARSE_FORMAT_MPSUB:
1609       self->parse_line = parse_mpsub;
1610       return gst_caps_new_simple ("text/x-raw",
1611           "format", G_TYPE_STRING, "utf8", NULL);
1612     case GST_SUB_PARSE_FORMAT_SAMI:
1613       self->parse_line = parse_sami;
1614       sami_context_init (&self->state);
1615       return gst_caps_new_simple ("text/x-raw",
1616           "format", G_TYPE_STRING, "pango-markup", NULL);
1617     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1618       self->parse_line = parse_tmplayer;
1619       self->state.max_duration = 5 * GST_SECOND;
1620       return gst_caps_new_simple ("text/x-raw",
1621           "format", G_TYPE_STRING, "utf8", NULL);
1622     case GST_SUB_PARSE_FORMAT_MPL2:
1623       self->parse_line = parse_mpl2;
1624       return gst_caps_new_simple ("text/x-raw",
1625           "format", G_TYPE_STRING, "pango-markup", NULL);
1626     case GST_SUB_PARSE_FORMAT_DKS:
1627       self->parse_line = parse_dks;
1628       return gst_caps_new_simple ("text/x-raw",
1629           "format", G_TYPE_STRING, "utf8", NULL);
1630     case GST_SUB_PARSE_FORMAT_VTT:
1631       self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1632       self->state.allows_tag_attributes = TRUE;
1633       self->parse_line = parse_webvtt;
1634       return gst_caps_new_simple ("text/x-raw",
1635           "format", G_TYPE_STRING, "pango-markup", NULL);
1636     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1637       self->parse_line = parse_subviewer;
1638       return gst_caps_new_simple ("text/x-raw",
1639           "format", G_TYPE_STRING, "utf8", NULL);
1640     case GST_SUB_PARSE_FORMAT_QTTEXT:
1641       self->parse_line = parse_qttext;
1642       qttext_context_init (&self->state);
1643       return gst_caps_new_simple ("text/x-raw",
1644           "format", G_TYPE_STRING, "pango-markup", NULL);
1645     case GST_SUB_PARSE_FORMAT_LRC:
1646       self->parse_line = parse_lrc;
1647       return gst_caps_new_simple ("text/x-raw",
1648           "format", G_TYPE_STRING, "utf8", NULL);
1649     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1650     default:
1651       GST_DEBUG ("no subtitle format detected");
1652       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1653           ("The input is not a valid/supported subtitle file"), (NULL));
1654       return NULL;
1655   }
1656 }
1657
1658 static void
1659 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1660 {
1661   gboolean discont;
1662   gsize consumed;
1663   gchar *input = NULL;
1664   const guint8 *data;
1665   gsize avail;
1666
1667   discont = GST_BUFFER_IS_DISCONT (buf);
1668
1669   if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1670       GST_BUFFER_OFFSET (buf) != self->offset) {
1671     self->offset = GST_BUFFER_OFFSET (buf);
1672     discont = TRUE;
1673   }
1674
1675   if (discont) {
1676     GST_INFO ("discontinuity");
1677     /* flush the parser state */
1678     parser_state_init (&self->state);
1679     g_string_truncate (self->textbuf, 0);
1680     gst_adapter_clear (self->adapter);
1681     if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1682       sami_context_reset (&self->state);
1683     /* we could set a flag to make sure that the next buffer we push out also
1684      * has the DISCONT flag set, but there's no point really given that it's
1685      * subtitles which are discontinuous by nature. */
1686   }
1687
1688   self->offset += gst_buffer_get_size (buf);
1689
1690   gst_adapter_push (self->adapter, buf);
1691
1692   avail = gst_adapter_available (self->adapter);
1693   data = gst_adapter_map (self->adapter, avail);
1694   input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1695
1696   if (input && consumed > 0) {
1697     self->textbuf = g_string_append (self->textbuf, input);
1698     gst_adapter_unmap (self->adapter);
1699     gst_adapter_flush (self->adapter, consumed);
1700   } else {
1701     gst_adapter_unmap (self->adapter);
1702   }
1703
1704   g_free (input);
1705 }
1706
1707 static GstFlowReturn
1708 handle_buffer (GstSubParse * self, GstBuffer * buf)
1709 {
1710   GstFlowReturn ret = GST_FLOW_OK;
1711   GstCaps *caps = NULL;
1712   gchar *line, *subtitle;
1713   gboolean need_tags = FALSE;
1714
1715   if (self->first_buffer) {
1716     GstMapInfo map;
1717
1718     gst_buffer_map (buf, &map, GST_MAP_READ);
1719     self->detected_encoding = detect_encoding ((gchar *) map.data, map.size);
1720     gst_buffer_unmap (buf, &map);
1721     self->first_buffer = FALSE;
1722     self->state.fps_n = self->fps_n;
1723     self->state.fps_d = self->fps_d;
1724   }
1725
1726   feed_textbuf (self, buf);
1727
1728   /* make sure we know the format */
1729   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1730     if (!(caps = gst_sub_parse_format_autodetect (self))) {
1731       return GST_FLOW_EOS;
1732     }
1733     if (!gst_pad_set_caps (self->srcpad, caps)) {
1734       gst_caps_unref (caps);
1735       return GST_FLOW_EOS;
1736     }
1737     gst_caps_unref (caps);
1738     need_tags = TRUE;
1739   }
1740
1741   /* Push newsegment if needed */
1742   if (self->need_segment) {
1743     GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1744         &self->segment);
1745
1746     gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1747     self->need_segment = FALSE;
1748   }
1749
1750   if (need_tags) {
1751     /* push tags */
1752     if (self->subtitle_codec != NULL) {
1753       GstTagList *tags;
1754
1755       tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1756           NULL);
1757       gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1758     }
1759   }
1760
1761   while (!self->flushing && (line = get_next_line (self))) {
1762     guint offset = 0;
1763
1764     /* Set segment on our parser state machine */
1765     self->state.segment = &self->segment;
1766     /* Now parse the line, out of segment lines will just return NULL */
1767     GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1768         line + offset);
1769     subtitle = self->parse_line (&self->state, line + offset);
1770     g_free (line);
1771
1772     if (subtitle) {
1773       guint subtitle_len = strlen (subtitle);
1774
1775       /* +1 for terminating NUL character */
1776       buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1777
1778       /* copy terminating NUL character as well */
1779       gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1780       gst_buffer_set_size (buf, subtitle_len);
1781
1782       GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1783       GST_BUFFER_DURATION (buf) = self->state.duration;
1784
1785       /* in some cases (e.g. tmplayer) we can only determine the duration
1786        * of a text chunk from the timestamp of the next text chunk; in those
1787        * cases, we probably want to limit the duration to something
1788        * reasonable, so we don't end up showing some text for e.g. 40 seconds
1789        * just because nothing else is being said during that time */
1790       if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1791         if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1792           GST_BUFFER_DURATION (buf) = self->state.max_duration;
1793       }
1794
1795       self->segment.position = self->state.start_time;
1796
1797       GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1798           GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1799           GST_TIME_ARGS (self->state.duration));
1800
1801       g_free (self->state.vertical);
1802       self->state.vertical = NULL;
1803       g_free (self->state.alignment);
1804       self->state.alignment = NULL;
1805
1806       ret = gst_pad_push (self->srcpad, buf);
1807
1808       /* move this forward (the tmplayer parser needs this) */
1809       if (self->state.duration != GST_CLOCK_TIME_NONE)
1810         self->state.start_time += self->state.duration;
1811
1812       g_free (subtitle);
1813       subtitle = NULL;
1814
1815       if (ret != GST_FLOW_OK) {
1816         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1817         break;
1818       }
1819     }
1820   }
1821
1822   return ret;
1823 }
1824
1825 static GstFlowReturn
1826 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1827 {
1828   GstFlowReturn ret;
1829   GstSubParse *self;
1830
1831   self = GST_SUBPARSE (parent);
1832
1833   ret = handle_buffer (self, buf);
1834
1835   return ret;
1836 }
1837
1838 static gboolean
1839 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1840 {
1841   GstSubParse *self = GST_SUBPARSE (parent);
1842   gboolean ret = FALSE;
1843
1844   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1845
1846   switch (GST_EVENT_TYPE (event)) {
1847     case GST_EVENT_EOS:{
1848       /* Make sure the last subrip chunk is pushed out even
1849        * if the file does not have an empty line at the end */
1850       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1851           self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1852           self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1853           self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT) {
1854         gchar term_chars[] = { '\n', '\n', '\0' };
1855         GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1856
1857         GST_DEBUG ("EOS. Pushing remaining text (if any)");
1858         gst_buffer_fill (buf, 0, term_chars, 3);
1859         gst_buffer_set_size (buf, 2);
1860
1861         GST_BUFFER_OFFSET (buf) = self->offset;
1862         gst_sub_parse_chain (pad, parent, buf);
1863       }
1864       ret = gst_pad_event_default (pad, parent, event);
1865       break;
1866     }
1867     case GST_EVENT_SEGMENT:
1868     {
1869       const GstSegment *s;
1870       gst_event_parse_segment (event, &s);
1871       if (s->format == GST_FORMAT_TIME)
1872         gst_event_copy_segment (event, &self->segment);
1873       GST_DEBUG_OBJECT (self, "newsegment (%s)",
1874           gst_format_get_name (self->segment.format));
1875
1876       /* if not time format, we'll either start with a 0 timestamp anyway or
1877        * it's following a seek in which case we'll have saved the requested
1878        * seek segment and don't want to overwrite it (remember that on a seek
1879        * we always just seek back to the start in BYTES format and just throw
1880        * away all text that's before the requested position; if the subtitles
1881        * come from an upstream demuxer, it won't be able to handle our BYTES
1882        * seek request and instead send us a newsegment from the seek request
1883        * it received via its video pads instead, so all is fine then too) */
1884       ret = TRUE;
1885       gst_event_unref (event);
1886       /* in either case, let's not simply discard this event;
1887        * trigger sending of the saved requested seek segment
1888        * or the one taken here from upstream */
1889       self->need_segment = TRUE;
1890       break;
1891     }
1892     case GST_EVENT_FLUSH_START:
1893     {
1894       self->flushing = TRUE;
1895
1896       ret = gst_pad_event_default (pad, parent, event);
1897       break;
1898     }
1899     case GST_EVENT_FLUSH_STOP:
1900     {
1901       self->flushing = FALSE;
1902
1903       ret = gst_pad_event_default (pad, parent, event);
1904       break;
1905     }
1906     default:
1907       ret = gst_pad_event_default (pad, parent, event);
1908       break;
1909   }
1910
1911   return ret;
1912 }
1913
1914
1915 static GstStateChangeReturn
1916 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1917 {
1918   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1919   GstSubParse *self = GST_SUBPARSE (element);
1920
1921   switch (transition) {
1922     case GST_STATE_CHANGE_READY_TO_PAUSED:
1923       /* format detection will init the parser state */
1924       self->offset = 0;
1925       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1926       self->valid_utf8 = TRUE;
1927       self->first_buffer = TRUE;
1928       g_free (self->detected_encoding);
1929       self->detected_encoding = NULL;
1930       g_string_truncate (self->textbuf, 0);
1931       gst_adapter_clear (self->adapter);
1932       break;
1933     default:
1934       break;
1935   }
1936
1937   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1938   if (ret == GST_STATE_CHANGE_FAILURE)
1939     return ret;
1940
1941   switch (transition) {
1942     case GST_STATE_CHANGE_PAUSED_TO_READY:
1943       parser_state_dispose (self, &self->state);
1944       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1945       break;
1946     default:
1947       break;
1948   }
1949
1950   return ret;
1951 }
1952
1953 /*
1954  * Typefind support.
1955  */
1956
1957 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1958  * also, give different  subtitle formats really different types */
1959 static GstStaticCaps mpl2_caps =
1960 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1961 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1962
1963 static GstStaticCaps tmp_caps =
1964 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1965 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1966
1967 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1968 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1969
1970 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1971 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1972
1973 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
1974 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
1975
1976 static GstStaticCaps vtt_caps = GST_STATIC_CAPS ("application/x-subtitle-vtt");
1977 #define VTT_CAPS (gst_static_caps_get (&vtt_caps))
1978
1979 static GstStaticCaps qttext_caps =
1980 GST_STATIC_CAPS ("application/x-subtitle-qttext");
1981 #define QTTEXT_CAPS (gst_static_caps_get (&qttext_caps))
1982
1983 static GstStaticCaps lrc_caps = GST_STATIC_CAPS ("application/x-subtitle-lrc");
1984 #define LRC_CAPS (gst_static_caps_get (&lrc_caps))
1985
1986 static void
1987 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1988 {
1989   GstSubParseFormat format;
1990   const guint8 *data;
1991   GstCaps *caps;
1992   gchar *str;
1993   gchar *encoding = NULL;
1994   const gchar *end;
1995
1996   if (!(data = gst_type_find_peek (tf, 0, 129)))
1997     return;
1998
1999   /* make sure string passed to _autodetect() is NUL-terminated */
2000   str = g_malloc0 (129);
2001   memcpy (str, data, 128);
2002
2003   if ((encoding = detect_encoding (str, 128)) != NULL) {
2004     gchar *converted_str;
2005     GError *err = NULL;
2006     gsize tmp;
2007
2008     converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
2009     if (converted_str == NULL) {
2010       GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
2011           err->message);
2012       g_clear_error (&err);
2013     } else {
2014       g_free (str);
2015       str = converted_str;
2016     }
2017     g_free (encoding);
2018   }
2019
2020   /* Check if at least the first 120 chars are valid UTF8,
2021    * otherwise convert as always */
2022   if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
2023     gchar *converted_str;
2024     gsize tmp;
2025     const gchar *enc;
2026
2027     enc = g_getenv ("GST_SUBTITLE_ENCODING");
2028     if (enc == NULL || *enc == '\0') {
2029       /* if local encoding is UTF-8 and no encoding specified
2030        * via the environment variable, assume ISO-8859-15 */
2031       if (g_get_charset (&enc)) {
2032         enc = "ISO-8859-15";
2033       }
2034     }
2035     converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, NULL);
2036     if (converted_str != NULL) {
2037       g_free (str);
2038       str = converted_str;
2039     }
2040   }
2041
2042   format = gst_sub_parse_data_format_autodetect (str);
2043   g_free (str);
2044
2045   switch (format) {
2046     case GST_SUB_PARSE_FORMAT_MDVDSUB:
2047       GST_DEBUG ("MicroDVD format detected");
2048       caps = SUB_CAPS;
2049       break;
2050     case GST_SUB_PARSE_FORMAT_SUBRIP:
2051       GST_DEBUG ("SubRip format detected");
2052       caps = SUB_CAPS;
2053       break;
2054     case GST_SUB_PARSE_FORMAT_MPSUB:
2055       GST_DEBUG ("MPSub format detected");
2056       caps = SUB_CAPS;
2057       break;
2058     case GST_SUB_PARSE_FORMAT_SAMI:
2059       GST_DEBUG ("SAMI (time-based) format detected");
2060       caps = SAMI_CAPS;
2061       break;
2062     case GST_SUB_PARSE_FORMAT_TMPLAYER:
2063       GST_DEBUG ("TMPlayer (time based) format detected");
2064       caps = TMP_CAPS;
2065       break;
2066       /* FIXME: our MPL2 typefinding is not really good enough to warrant
2067        * returning a high probability (however, since we registered our
2068        * typefinder here with a rank of MARGINAL we should pretty much only
2069        * be called if most other typefinders have already run */
2070     case GST_SUB_PARSE_FORMAT_MPL2:
2071       GST_DEBUG ("MPL2 (time based) format detected");
2072       caps = MPL2_CAPS;
2073       break;
2074     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
2075       GST_DEBUG ("SubViewer format detected");
2076       caps = SUB_CAPS;
2077       break;
2078     case GST_SUB_PARSE_FORMAT_DKS:
2079       GST_DEBUG ("DKS format detected");
2080       caps = DKS_CAPS;
2081       break;
2082     case GST_SUB_PARSE_FORMAT_QTTEXT:
2083       GST_DEBUG ("QTtext format detected");
2084       caps = QTTEXT_CAPS;
2085       break;
2086     case GST_SUB_PARSE_FORMAT_LRC:
2087       GST_DEBUG ("LRC format detected");
2088       caps = LRC_CAPS;
2089       break;
2090     case GST_SUB_PARSE_FORMAT_VTT:
2091       GST_DEBUG ("WebVTT format detected");
2092       caps = VTT_CAPS;
2093       break;
2094     default:
2095     case GST_SUB_PARSE_FORMAT_UNKNOWN:
2096       GST_DEBUG ("no subtitle format detected");
2097       return;
2098   }
2099
2100   /* if we're here, it's ok */
2101   gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
2102 }
2103
2104 static gboolean
2105 plugin_init (GstPlugin * plugin)
2106 {
2107   GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
2108
2109   if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
2110           gst_subparse_type_find, "srt,sub,mpsub,mdvd,smi,txt,dks,vtt",
2111           SUB_CAPS, NULL, NULL))
2112     return FALSE;
2113
2114   if (!gst_element_register (plugin, "subparse",
2115           GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
2116       !gst_element_register (plugin, "ssaparse",
2117           GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
2118     return FALSE;
2119   }
2120
2121   return TRUE;
2122 }
2123
2124 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2125     GST_VERSION_MINOR,
2126     subparse,
2127     "Subtitle parsing",
2128     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)