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