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