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