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