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