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