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