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