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