gst/subparse/gstsubparse.c: Break out of loop in chain function as soon as possible...
[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 <string.h>
27 #include <stdlib.h>
28 #include <sys/types.h>
29 #include <regex.h>
30
31 #include "gstsubparse.h"
32 #include "gstssaparse.h"
33 #include "samiparse.h"
34 #include "tmplayerparse.h"
35
36 GST_DEBUG_CATEGORY (sub_parse_debug);
37
38 #define DEFAULT_ENCODING   NULL
39
40 enum
41 {
42   PROP_0,
43   PROP_ENCODING
44 };
45
46 static void
47 gst_sub_parse_set_property (GObject * object, guint prop_id,
48     const GValue * value, GParamSpec * pspec);
49 static void
50 gst_sub_parse_get_property (GObject * object, guint prop_id,
51     GValue * value, GParamSpec * pspec);
52
53
54 static const GstElementDetails sub_parse_details =
55 GST_ELEMENT_DETAILS ("Subtitle parser",
56     "Codec/Parser/Subtitle",
57     "Parses subtitle (.sub) files into text streams",
58     "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
59     "Ronald S. Bultje <rbultje@ronald.bitfreak.net>");
60
61 #ifndef GST_DISABLE_LOADSAVE_REGISTRY
62 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
63     GST_PAD_SINK,
64     GST_PAD_ALWAYS,
65     GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
66         "application/x-subtitle-tmplayer")
67     );
68 #else
69 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
70     GST_PAD_SINK,
71     GST_PAD_ALWAYS,
72     GST_STATIC_CAPS ("application/x-subtitle")
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/plain; text/x-pango-markup")
80     );
81
82 static void gst_sub_parse_base_init (GstSubParseClass * klass);
83 static void gst_sub_parse_class_init (GstSubParseClass * klass);
84 static void gst_sub_parse_init (GstSubParse * subparse);
85
86 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
87 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
88
89 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
90     GstStateChange transition);
91
92 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
93
94 static GstElementClass *parent_class = NULL;
95
96 GType
97 gst_sub_parse_get_type (void)
98 {
99   static GType sub_parse_type = 0;
100
101   if (!sub_parse_type) {
102     static const GTypeInfo sub_parse_info = {
103       sizeof (GstSubParseClass),
104       (GBaseInitFunc) gst_sub_parse_base_init,
105       NULL,
106       (GClassInitFunc) gst_sub_parse_class_init,
107       NULL,
108       NULL,
109       sizeof (GstSubParse),
110       0,
111       (GInstanceInitFunc) gst_sub_parse_init,
112     };
113
114     sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
115         "GstSubParse", &sub_parse_info, 0);
116   }
117
118   return sub_parse_type;
119 }
120
121 static void
122 gst_sub_parse_base_init (GstSubParseClass * klass)
123 {
124   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
125
126   gst_element_class_add_pad_template (element_class,
127       gst_static_pad_template_get (&sink_templ));
128   gst_element_class_add_pad_template (element_class,
129       gst_static_pad_template_get (&src_templ));
130   gst_element_class_set_details (element_class, &sub_parse_details);
131 }
132
133 static void
134 gst_sub_parse_dispose (GObject * object)
135 {
136   GstSubParse *subparse = GST_SUBPARSE (object);
137
138   GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
139
140   if (subparse->segment) {
141     gst_segment_free (subparse->segment);
142     subparse->segment = NULL;
143   }
144   if (subparse->encoding) {
145     g_free (subparse->encoding);
146     subparse->encoding = NULL;
147   }
148   if (subparse->textbuf) {
149     g_string_free (subparse->textbuf, TRUE);
150     subparse->textbuf = NULL;
151   }
152   sami_context_deinit (&subparse->state);
153
154   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
155 }
156
157 static void
158 gst_sub_parse_class_init (GstSubParseClass * klass)
159 {
160   GObjectClass *object_class = G_OBJECT_CLASS (klass);
161   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
162
163   parent_class = g_type_class_peek_parent (klass);
164
165   object_class->dispose = gst_sub_parse_dispose;
166   object_class->set_property = gst_sub_parse_set_property;
167   object_class->get_property = gst_sub_parse_get_property;
168
169   element_class->change_state = gst_sub_parse_change_state;
170
171   g_object_class_install_property (object_class, PROP_ENCODING,
172       g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
173           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
174           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
175           "be checked for an encoding to use. If that is not set either, "
176           "ISO-8859-15 will be assumed.", DEFAULT_ENCODING, G_PARAM_READWRITE));
177 }
178
179 static void
180 gst_sub_parse_init (GstSubParse * subparse)
181 {
182   subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
183   gst_pad_set_chain_function (subparse->sinkpad,
184       GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
185   gst_pad_set_event_function (subparse->sinkpad,
186       GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
187   gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
188
189   subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
190   gst_pad_set_event_function (subparse->srcpad,
191       GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
192   gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
193
194   subparse->textbuf = g_string_new (NULL);
195   subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
196   subparse->flushing = FALSE;
197   subparse->segment = gst_segment_new ();
198   if (subparse->segment) {
199     gst_segment_init (subparse->segment, GST_FORMAT_TIME);
200     subparse->need_segment = TRUE;
201   } else {
202     GST_WARNING_OBJECT (subparse, "segment creation failed");
203     g_assert_not_reached ();
204   }
205   subparse->encoding = g_strdup (DEFAULT_ENCODING);
206 }
207
208 /*
209  * Source pad functions.
210  */
211
212 static gboolean
213 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
214 {
215   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
216   gboolean ret = FALSE;
217
218   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
219
220   switch (GST_EVENT_TYPE (event)) {
221     case GST_EVENT_SEEK:
222     {
223       GstFormat format;
224       GstSeekType start_type, stop_type;
225       gint64 start, stop;
226       gdouble rate;
227       gboolean update;
228
229       gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
230           &start_type, &start, &stop_type, &stop);
231
232       if (format != GST_FORMAT_TIME) {
233         GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
234         gst_event_unref (event);
235         goto beach;
236       }
237
238       /* Convert that seek to a seeking in bytes at position 0,
239          FIXME: could use an index */
240       ret = gst_pad_push_event (self->sinkpad,
241           gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
242               GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
243
244       if (ret) {
245         /* Apply the seek to our segment */
246         gst_segment_set_seek (self->segment, rate, format, self->segment_flags,
247             start_type, start, stop_type, stop, &update);
248
249         GST_DEBUG_OBJECT (self, "segment configured from %" GST_TIME_FORMAT
250             " to %" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT,
251             GST_TIME_ARGS (self->segment->start),
252             GST_TIME_ARGS (self->segment->stop),
253             GST_TIME_ARGS (self->segment->last_stop));
254
255         self->next_offset = 0;
256
257         self->need_segment = TRUE;
258       } else {
259         GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
260       }
261
262       gst_event_unref (event);
263       break;
264     }
265     default:
266       ret = gst_pad_event_default (pad, event);
267       break;
268   }
269
270 beach:
271   gst_object_unref (self);
272
273   return ret;
274 }
275
276 static void
277 gst_sub_parse_set_property (GObject * object, guint prop_id,
278     const GValue * value, GParamSpec * pspec)
279 {
280   GstSubParse *subparse = GST_SUBPARSE (object);
281
282   GST_OBJECT_LOCK (subparse);
283   switch (prop_id) {
284     case PROP_ENCODING:
285       g_free (subparse->encoding);
286       subparse->encoding = g_value_dup_string (value);
287       GST_LOG_OBJECT (object, "subtitle encoding set to %s",
288           GST_STR_NULL (subparse->encoding));
289       break;
290     default:
291       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
292       break;
293   }
294   GST_OBJECT_UNLOCK (subparse);
295 }
296
297 static void
298 gst_sub_parse_get_property (GObject * object, guint prop_id,
299     GValue * value, GParamSpec * pspec)
300 {
301   GstSubParse *subparse = GST_SUBPARSE (object);
302
303   GST_OBJECT_LOCK (subparse);
304   switch (prop_id) {
305     case PROP_ENCODING:
306       g_value_set_string (value, subparse->encoding);
307       break;
308     default:
309       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
310       break;
311   }
312   GST_OBJECT_UNLOCK (subparse);
313 }
314
315 static gchar *
316 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
317 {
318   const gchar *encoding;
319   GError *err = NULL;
320   gchar *ret;
321
322   if (self->valid_utf8) {
323     if (g_utf8_validate (str, len, NULL)) {
324       GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
325       return g_strndup (str, len);
326     }
327     GST_INFO_OBJECT (self, "invalid UTF-8!");
328     self->valid_utf8 = FALSE;
329   }
330
331   encoding = self->encoding;
332   if (encoding == NULL || *encoding == '\0') {
333     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
334   }
335   if (encoding == NULL || *encoding == '\0') {
336     /* if local encoding is UTF-8 and no encoding specified
337      * via the environment variable, assume ISO-8859-15 */
338     if (g_get_charset (&encoding)) {
339       encoding = "ISO-8859-15";
340     }
341   }
342
343   ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
344       NULL, &err);
345
346   if (err) {
347     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
348         encoding, err->message);
349     g_error_free (err);
350
351     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
352     ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
353         NULL, NULL, NULL);
354   }
355
356   GST_LOG_OBJECT (self,
357       "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
358       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
359
360   return ret;
361 }
362
363 static gchar *
364 get_next_line (GstSubParse * self)
365 {
366   char *line = NULL;
367   const char *line_end;
368   int line_len;
369   gboolean have_r = FALSE;
370
371   line_end = strchr (self->textbuf->str, '\n');
372
373   if (!line_end) {
374     /* end-of-line not found; return for more data */
375     return NULL;
376   }
377
378   /* get rid of '\r' */
379   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
380     line_end--;
381     have_r = TRUE;
382   }
383
384   line_len = line_end - self->textbuf->str;
385   line = convert_encoding (self, self->textbuf->str, line_len);
386   self->textbuf = g_string_erase (self->textbuf, 0,
387       line_len + (have_r ? 2 : 1));
388   return line;
389 }
390
391 static gchar *
392 parse_mdvdsub (ParserState * state, const gchar * line)
393 {
394   const gchar *line_split;
395   gchar *line_chunk;
396   guint start_frame, end_frame;
397   gint64 clip_start = 0, clip_stop = 0;
398   gboolean in_seg = FALSE;
399   GString *markup;
400   gchar *ret;
401
402   /* style variables */
403   gboolean italic;
404   gboolean bold;
405   guint fontsize;
406
407   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
408     g_warning ("Parse of the following line, assumed to be in microdvd .sub"
409         " format, failed:\n%s", line);
410     return NULL;
411   }
412
413   /* skip the {%u}{%u} part */
414   line = strchr (line, '}') + 1;
415   line = strchr (line, '}') + 1;
416
417   /* see if there's a first line with a framerate */
418   if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
419     gchar *rest, *end = NULL;
420
421     rest = g_strdup (line);
422     g_strdelimit (rest, ",", '.');
423     state->fps = g_ascii_strtod (rest, &end);
424     if (end == rest)
425       state->fps = 0.0;
426     GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
427     g_free (rest);
428     return NULL;
429   }
430
431   if (state->fps == 0.0) {
432     /* FIXME: hardcoded for now, is there a better way/assumption? */
433     state->fps = 24000.0 / 1001.0;
434     GST_INFO ("no framerate specified, assuming %f", state->fps);
435   }
436
437   state->start_time = start_frame / state->fps * GST_SECOND;
438   state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
439
440   /* Check our segment start/stop */
441   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
442       state->start_time, state->start_time + state->duration, &clip_start,
443       &clip_stop);
444
445   /* No need to parse that text if it's out of segment */
446   if (in_seg) {
447     state->start_time = clip_start;
448     state->duration = clip_stop - clip_start;
449   } else {
450     return NULL;
451   }
452
453   markup = g_string_new (NULL);
454   while (1) {
455     italic = FALSE;
456     bold = FALSE;
457     fontsize = 0;
458     /* parse style markup */
459     if (strncmp (line, "{y:i}", 5) == 0) {
460       italic = TRUE;
461       line = strchr (line, '}') + 1;
462     }
463     if (strncmp (line, "{y:b}", 5) == 0) {
464       bold = TRUE;
465       line = strchr (line, '}') + 1;
466     }
467     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
468       line = strchr (line, '}') + 1;
469     }
470     if ((line_split = strchr (line, '|')))
471       line_chunk = g_markup_escape_text (line, line_split - line);
472     else
473       line_chunk = g_markup_escape_text (line, strlen (line));
474     markup = g_string_append (markup, "<span");
475     if (italic)
476       g_string_append (markup, " style=\"italic\"");
477     if (bold)
478       g_string_append (markup, " weight=\"bold\"");
479     if (fontsize)
480       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
481     g_string_append_printf (markup, ">%s</span>", line_chunk);
482     g_free (line_chunk);
483     if (line_split) {
484       g_string_append (markup, "\n");
485       line = line_split + 1;
486     } else {
487       break;
488     }
489   }
490   ret = markup->str;
491   g_string_free (markup, FALSE);
492   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
493       state->start_time / (double) GST_SECOND,
494       state->duration / (double) GST_SECOND, ret);
495   return ret;
496 }
497
498 static void
499 strip_trailing_newlines (gchar * txt)
500 {
501   if (txt) {
502     guint len;
503
504     len = strlen (txt);
505     while (len > 1 && txt[len - 1] == '\n') {
506       txt[len - 1] = '\0';
507       --len;
508     }
509   }
510 }
511
512 /* we want to escape text in general, but retain basic markup like
513  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
514  * just unescape a white list of allowed markups again after
515  * escaping everything (the text between these simple markers isn't
516  * necessarily escaped, so it seems best to do it like this) */
517 static void
518 subrip_unescape_formatting (gchar * txt)
519 {
520   gchar *pos;
521
522   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
523     if (g_ascii_strncasecmp (pos, "&lt;u&gt;", 9) == 0 ||
524         g_ascii_strncasecmp (pos, "&lt;i&gt;", 9) == 0 ||
525         g_ascii_strncasecmp (pos, "&lt;b&gt;", 9) == 0) {
526       pos[0] = '<';
527       pos[1] = g_ascii_tolower (pos[4]);
528       pos[2] = '>';
529       /* move NUL terminator as well */
530       g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
531       pos += 2;
532     }
533   }
534
535   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
536     if (g_ascii_strncasecmp (pos, "&lt;/u&gt;", 10) == 0 ||
537         g_ascii_strncasecmp (pos, "&lt;/i&gt;", 10) == 0 ||
538         g_ascii_strncasecmp (pos, "&lt;/b&gt;", 10) == 0) {
539       pos[0] = '<';
540       pos[1] = '/';
541       pos[2] = g_ascii_tolower (pos[5]);
542       pos[3] = '>';
543       /* move NUL terminator as well */
544       g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
545       pos += 3;
546     }
547   }
548 }
549
550
551 static gboolean
552 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
553 {
554   gchar *tag, saved;
555
556   tag = start + strlen ("&lt;");
557   if (*tag == '/')
558     ++tag;
559
560   if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
561     return FALSE;
562
563   saved = *stop;
564   *stop = '\0';
565   GST_LOG ("removing unhandled tag '%s'", start);
566   *stop = saved;
567   g_memmove (start, stop, strlen (stop) + 1);
568   return TRUE;
569 }
570
571 /* remove tags we haven't explicitly allowed earlier on, like font tags
572  * for example */
573 static void
574 subrip_remove_unhandled_tags (gchar * txt)
575 {
576   gchar *pos, *gt;
577
578   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
579     if (strncmp (pos, "&lt;", 4) == 0 && (gt = strstr (pos + 4, "&gt;"))) {
580       if (subrip_remove_unhandled_tag (pos, gt + strlen ("&gt;")))
581         --pos;
582     }
583   }
584 }
585
586 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
587  * assumes the input has been escaped and subrip_unescape_formatting() has then
588  * been run over the input! This function adds missing closing markup tags and
589  * removes broken closing tags for tags that have never been opened. */
590 static void
591 subrip_fix_up_markup (gchar ** p_txt)
592 {
593   gchar *cur, *next_tag;
594   gchar open_tags[32];
595   guint num_open_tags = 0;
596
597   g_assert (*p_txt != NULL);
598
599   cur = *p_txt;
600   while (*cur != '\0') {
601     next_tag = strchr (cur, '<');
602     if (next_tag == NULL)
603       break;
604     ++next_tag;
605     switch (*next_tag) {
606       case '/':{
607         ++next_tag;
608         if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
609           GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
610           g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
611           next_tag -= 2;
612         } else {
613           /* it's all good, closing tag which is open */
614           --num_open_tags;
615         }
616         break;
617       }
618       case 'i':
619       case 'b':
620       case 'u':
621         if (num_open_tags == G_N_ELEMENTS (open_tags))
622           return;               /* something dodgy is going on, stop parsing */
623         open_tags[num_open_tags] = *next_tag;
624         ++num_open_tags;
625         break;
626       default:
627         GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
628         g_assert_not_reached ();
629         break;
630     }
631     cur = next_tag;
632   }
633
634   if (num_open_tags > 0) {
635     GString *s;
636
637     s = g_string_new (*p_txt);
638     while (num_open_tags > 0) {
639       GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
640       g_string_append_c (s, '<');
641       g_string_append_c (s, '/');
642       g_string_append_c (s, open_tags[num_open_tags - 1]);
643       g_string_append_c (s, '>');
644       --num_open_tags;
645     }
646     g_free (*p_txt);
647     *p_txt = g_string_free (s, FALSE);
648   }
649 }
650
651 static gchar *
652 parse_subrip (ParserState * state, const gchar * line)
653 {
654   guint h1, m1, s1, ms1;
655   guint h2, m2, s2, ms2;
656   int subnum;
657   gchar *ret;
658
659   switch (state->state) {
660     case 0:
661       /* looking for a single integer */
662       if (sscanf (line, "%u", &subnum) == 1)
663         state->state = 1;
664       return NULL;
665     case 1:
666       /* looking for start_time --> end_time */
667       if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
668               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
669         state->state = 2;
670         state->start_time =
671             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
672             ms1 * GST_MSECOND;
673         state->duration =
674             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
675             ms2 * GST_MSECOND - state->start_time;
676       } else {
677         GST_DEBUG ("error parsing subrip time line");
678         state->state = 0;
679       }
680       return NULL;
681     case 2:
682     {                           /* No need to parse that text if it's out of segment */
683       gint64 clip_start = 0, clip_stop = 0;
684       gboolean in_seg = FALSE;
685
686       /* Check our segment start/stop */
687       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
688           state->start_time, state->start_time + state->duration,
689           &clip_start, &clip_stop);
690
691       if (in_seg) {
692         state->start_time = clip_start;
693         state->duration = clip_stop - clip_start;
694       } else {
695         state->state = 0;
696         return NULL;
697       }
698     }
699       /* looking for subtitle text; empty line ends this
700        * subtitle entry */
701       if (state->buf->len)
702         g_string_append_c (state->buf, '\n');
703       g_string_append (state->buf, line);
704       if (strlen (line) == 0) {
705         ret = g_markup_escape_text (state->buf->str, state->buf->len);
706         g_string_truncate (state->buf, 0);
707         state->state = 0;
708         subrip_unescape_formatting (ret);
709         subrip_remove_unhandled_tags (ret);
710         strip_trailing_newlines (ret);
711         subrip_fix_up_markup (&ret);
712         return ret;
713       }
714       return NULL;
715     default:
716       g_return_val_if_reached (NULL);
717   }
718 }
719
720 static gchar *
721 parse_mpsub (ParserState * state, const gchar * line)
722 {
723   gchar *ret;
724   float t1, t2;
725
726   switch (state->state) {
727     case 0:
728       /* looking for two floats (offset, duration) */
729       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
730         state->state = 1;
731         state->start_time += state->duration + GST_SECOND * t1;
732         state->duration = GST_SECOND * t2;
733       }
734       return NULL;
735     case 1:
736     {                           /* No need to parse that text if it's out of segment */
737       gint64 clip_start = 0, clip_stop = 0;
738       gboolean in_seg = FALSE;
739
740       /* Check our segment start/stop */
741       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
742           state->start_time, state->start_time + state->duration,
743           &clip_start, &clip_stop);
744
745       if (in_seg) {
746         state->start_time = clip_start;
747         state->duration = clip_stop - clip_start;
748       } else {
749         state->state = 0;
750         return NULL;
751       }
752     }
753       /* looking for subtitle text; empty line ends this
754        * subtitle entry */
755       if (state->buf->len)
756         g_string_append_c (state->buf, '\n');
757       g_string_append (state->buf, line);
758       if (strlen (line) == 0) {
759         ret = g_strdup (state->buf->str);
760         g_string_truncate (state->buf, 0);
761         state->state = 0;
762         return ret;
763       }
764       return NULL;
765     default:
766       g_assert_not_reached ();
767       return NULL;
768   }
769 }
770
771 static void
772 parser_state_init (ParserState * state)
773 {
774   GST_DEBUG ("initialising parser");
775
776   if (state->buf) {
777     g_string_truncate (state->buf, 0);
778   } else {
779     state->buf = g_string_new (NULL);
780   }
781
782   state->start_time = 0;
783   state->duration = 0;
784   state->state = 0;
785   state->segment = NULL;
786 }
787
788 static void
789 parser_state_dispose (ParserState * state)
790 {
791   if (state->buf) {
792     g_string_free (state->buf, TRUE);
793     state->buf = NULL;
794   }
795   if (state->user_data) {
796     sami_context_reset (state);
797   }
798 }
799
800 /*
801  * FIXME: maybe we should pass along a second argument, the preceding
802  * text buffer, because that is how this originally worked, even though
803  * I don't really see the use of that.
804  */
805
806 static GstSubParseFormat
807 gst_sub_parse_data_format_autodetect (gchar * match_str)
808 {
809   static gboolean need_init_regexps = TRUE;
810   static regex_t mdvd_rx;
811   static regex_t subrip_rx;
812   guint n1, n2, n3;
813
814   /* initialize the regexps used the first time around */
815   if (need_init_regexps) {
816     int err;
817     char errstr[128];
818
819     need_init_regexps = FALSE;
820     if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
821                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
822         (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
823                 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
824                 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
825                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
826       regerror (err, &subrip_rx, errstr, 127);
827       GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
828     }
829   }
830
831   if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
832     GST_LOG ("MicroDVD (frame based) format detected");
833     return GST_SUB_PARSE_FORMAT_MDVDSUB;
834   }
835   if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
836     GST_LOG ("SubRip (time based) format detected");
837     return GST_SUB_PARSE_FORMAT_SUBRIP;
838   }
839   if (!strncmp (match_str, "FORMAT=TIME", 11)) {
840     GST_LOG ("MPSub (time based) format detected");
841     return GST_SUB_PARSE_FORMAT_MPSUB;
842   }
843   if (strstr (match_str, "<SAMI>") != NULL ||
844       strstr (match_str, "<sami>") != NULL) {
845     GST_LOG ("SAMI (time based) format detected");
846     return GST_SUB_PARSE_FORMAT_SAMI;
847   }
848   /* we're boldly assuming the first subtitle appears within the first hour */
849   if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
850       sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
851       sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
852       sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
853       sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
854     GST_LOG ("TMPlayer (time based) format detected");
855     return GST_SUB_PARSE_FORMAT_TMPLAYER;
856   }
857
858   GST_DEBUG ("no subtitle format detected");
859   return GST_SUB_PARSE_FORMAT_UNKNOWN;
860 }
861
862 static GstCaps *
863 gst_sub_parse_format_autodetect (GstSubParse * self)
864 {
865   gchar *data;
866   GstSubParseFormat format;
867
868   if (strlen (self->textbuf->str) < 35) {
869     GST_DEBUG ("File too small to be a subtitles file");
870     return NULL;
871   }
872
873   data = g_strndup (self->textbuf->str, 35);
874   format = gst_sub_parse_data_format_autodetect (data);
875   g_free (data);
876
877   self->parser_type = format;
878   parser_state_init (&self->state);
879
880   switch (format) {
881     case GST_SUB_PARSE_FORMAT_MDVDSUB:
882       self->parse_line = parse_mdvdsub;
883       return gst_caps_new_simple ("text/x-pango-markup", NULL);
884     case GST_SUB_PARSE_FORMAT_SUBRIP:
885       self->parse_line = parse_subrip;
886       return gst_caps_new_simple ("text/x-pango-markup", NULL);
887     case GST_SUB_PARSE_FORMAT_MPSUB:
888       self->parse_line = parse_mpsub;
889       return gst_caps_new_simple ("text/plain", NULL);
890     case GST_SUB_PARSE_FORMAT_SAMI:
891       self->parse_line = parse_sami;
892       sami_context_init (&self->state);
893       return gst_caps_new_simple ("text/x-pango-markup", NULL);
894     case GST_SUB_PARSE_FORMAT_TMPLAYER:
895       self->parse_line = parse_tmplayer;
896       return gst_caps_new_simple ("text/plain", NULL);
897     case GST_SUB_PARSE_FORMAT_UNKNOWN:
898     default:
899       GST_DEBUG ("no subtitle format detected");
900       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
901           ("The input is not a valid/supported subtitle file"), (NULL));
902       return NULL;
903   }
904 }
905
906 static void
907 feed_textbuf (GstSubParse * self, GstBuffer * buf)
908 {
909   if (GST_BUFFER_OFFSET (buf) != self->offset) {
910     /* flush the parser state */
911     parser_state_init (&self->state);
912     g_string_truncate (self->textbuf, 0);
913     sami_context_reset (&self->state);
914   }
915
916   self->textbuf = g_string_append_len (self->textbuf,
917       (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
918   self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
919   self->next_offset = self->offset;
920
921   gst_buffer_unref (buf);
922 }
923
924 static GstFlowReturn
925 handle_buffer (GstSubParse * self, GstBuffer * buf)
926 {
927   GstFlowReturn ret = GST_FLOW_OK;
928   GstCaps *caps = NULL;
929   gchar *line, *subtitle;
930
931   feed_textbuf (self, buf);
932
933   /* make sure we know the format */
934   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
935     if (!(caps = gst_sub_parse_format_autodetect (self))) {
936       return GST_FLOW_UNEXPECTED;
937     }
938     if (!gst_pad_set_caps (self->srcpad, caps)) {
939       gst_caps_unref (caps);
940       return GST_FLOW_UNEXPECTED;
941     }
942     gst_caps_unref (caps);
943   }
944
945   while ((line = get_next_line (self)) && !self->flushing) {
946     /* Set segment on our parser state machine */
947     self->state.segment = self->segment;
948     /* Now parse the line, out of segment lines will just return NULL */
949     GST_LOG_OBJECT (self, "Parsing line '%s'", line);
950     subtitle = self->parse_line (&self->state, line);
951     g_free (line);
952
953     if (subtitle) {
954       guint subtitle_len = strlen (subtitle);
955
956       /* +1 for terminating NUL character */
957       ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
958           GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
959           GST_PAD_CAPS (self->srcpad), &buf);
960
961       if (ret == GST_FLOW_OK) {
962         /* copy terminating NUL character as well */
963         memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
964         GST_BUFFER_SIZE (buf) = subtitle_len;
965         GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
966         GST_BUFFER_DURATION (buf) = self->state.duration;
967
968         gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
969             self->state.start_time);
970
971         GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
972             GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
973             GST_TIME_ARGS (self->state.duration));
974
975         ret = gst_pad_push (self->srcpad, buf);
976       }
977
978       g_free (subtitle);
979       subtitle = NULL;
980
981       if (ret != GST_FLOW_OK) {
982         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
983         break;
984       }
985     }
986   }
987
988   return ret;
989 }
990
991 static GstFlowReturn
992 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
993 {
994   GstFlowReturn ret;
995   GstSubParse *self;
996
997   self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
998
999   /* Push newsegment if needed */
1000   if (self->need_segment) {
1001     gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1002             self->segment->rate, self->segment->format,
1003             self->segment->last_stop, self->segment->stop,
1004             self->segment->time));
1005     self->need_segment = FALSE;
1006   }
1007
1008   ret = handle_buffer (self, buf);
1009
1010   return ret;
1011 }
1012
1013 static gboolean
1014 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1015 {
1016   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1017   gboolean ret = FALSE;
1018
1019   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1020
1021   switch (GST_EVENT_TYPE (event)) {
1022     case GST_EVENT_EOS:{
1023       /* Make sure the last subrip chunk is pushed out even
1024        * if the file does not have an empty line at the end */
1025       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
1026         GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
1027
1028         GST_DEBUG ("EOS. Pushing remaining text (if any)");
1029         GST_BUFFER_DATA (buf)[0] = '\n';
1030         GST_BUFFER_DATA (buf)[1] = '\0';        /* play it safe */
1031         GST_BUFFER_SIZE (buf) = 1;
1032         GST_BUFFER_OFFSET (buf) = self->offset;
1033         gst_sub_parse_chain (pad, buf);
1034       }
1035       ret = gst_pad_event_default (pad, event);
1036       break;
1037     }
1038     case GST_EVENT_NEWSEGMENT:
1039     {
1040       GstFormat format;
1041       gdouble rate;
1042       gint64 start, stop, time;
1043       gboolean update;
1044
1045       GST_DEBUG_OBJECT (self, "received new segment");
1046
1047       gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1048           &stop, &time);
1049
1050       /* now copy over the values */
1051       gst_segment_set_newsegment (self->segment, update, rate, format,
1052           start, stop, time);
1053
1054       ret = TRUE;
1055       gst_event_unref (event);
1056       break;
1057     }
1058     case GST_EVENT_FLUSH_START:
1059     {
1060       self->flushing = TRUE;
1061
1062       ret = gst_pad_event_default (pad, event);
1063       break;
1064     }
1065     case GST_EVENT_FLUSH_STOP:
1066     {
1067       self->flushing = FALSE;
1068
1069       ret = gst_pad_event_default (pad, event);
1070       break;
1071     }
1072     default:
1073       ret = gst_pad_event_default (pad, event);
1074       break;
1075   }
1076
1077   gst_object_unref (self);
1078
1079   return ret;
1080 }
1081
1082
1083 static GstStateChangeReturn
1084 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1085 {
1086   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1087   GstSubParse *self = GST_SUBPARSE (element);
1088
1089   switch (transition) {
1090     case GST_STATE_CHANGE_READY_TO_PAUSED:
1091       /* format detection will init the parser state */
1092       self->offset = 0;
1093       self->next_offset = 0;
1094       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1095       self->valid_utf8 = TRUE;
1096       g_string_truncate (self->textbuf, 0);
1097       break;
1098     default:
1099       break;
1100   }
1101
1102   ret = parent_class->change_state (element, transition);
1103   if (ret == GST_STATE_CHANGE_FAILURE)
1104     return ret;
1105
1106   switch (transition) {
1107     case GST_STATE_CHANGE_PAUSED_TO_READY:
1108       parser_state_dispose (&self->state);
1109       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1110       break;
1111     default:
1112       break;
1113   }
1114
1115   return ret;
1116 }
1117
1118 /*
1119  * Typefind support.
1120  */
1121
1122 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1123  * also, give different  subtitle formats really different types */
1124 static GstStaticCaps tmp_caps =
1125 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1126 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1127 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1128
1129 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1130 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1131 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1132
1133 static void
1134 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1135 {
1136   GstSubParseFormat format;
1137   const guint8 *data;
1138   GstCaps *caps;
1139   gchar *str;
1140
1141   if (!(data = gst_type_find_peek (tf, 0, 36)))
1142     return;
1143
1144   /* make sure string passed to _autodetect() is NUL-terminated */
1145   str = g_strndup ((gchar *) data, 35);
1146   format = gst_sub_parse_data_format_autodetect (str);
1147   g_free (str);
1148
1149   switch (format) {
1150     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1151       GST_DEBUG ("MicroDVD format detected");
1152       caps = SUB_CAPS;
1153       break;
1154     case GST_SUB_PARSE_FORMAT_SUBRIP:
1155       GST_DEBUG ("SubRip format detected");
1156       caps = SUB_CAPS;
1157       break;
1158     case GST_SUB_PARSE_FORMAT_MPSUB:
1159       GST_DEBUG ("MPSub format detected");
1160       caps = SUB_CAPS;
1161       break;
1162     case GST_SUB_PARSE_FORMAT_SAMI:
1163       GST_DEBUG ("SAMI (time-based) format detected");
1164       caps = SAMI_CAPS;
1165       break;
1166     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1167       GST_DEBUG ("TMPlayer (time based) format detected");
1168       caps = TMP_CAPS;
1169       break;
1170     default:
1171     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1172       GST_DEBUG ("no subtitle format detected");
1173       return;
1174   }
1175
1176   /* if we're here, it's ok */
1177   gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1178 }
1179
1180 static gboolean
1181 plugin_init (GstPlugin * plugin)
1182 {
1183   static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1184     NULL
1185   };
1186
1187   GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1188
1189   if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1190           gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1191     return FALSE;
1192
1193   if (!gst_element_register (plugin, "subparse",
1194           GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1195       !gst_element_register (plugin, "ssaparse",
1196           GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1197     return FALSE;
1198   }
1199
1200   return TRUE;
1201 }
1202
1203 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1204     GST_VERSION_MINOR,
1205     "subparse",
1206     "Subtitle parsing",
1207     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)