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