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