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