gst/subparse/: Add support for TMPlayer-type subtitles (#362845).
[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, "successfully converted %d characters from %s to UTF-8"
357       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
358
359   return ret;
360 }
361
362 static gchar *
363 get_next_line (GstSubParse * self)
364 {
365   char *line = NULL;
366   const char *line_end;
367   int line_len;
368   gboolean have_r = FALSE;
369
370   line_end = strchr (self->textbuf->str, '\n');
371
372   if (!line_end) {
373     /* end-of-line not found; return for more data */
374     return NULL;
375   }
376
377   /* get rid of '\r' */
378   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
379     line_end--;
380     have_r = TRUE;
381   }
382
383   line_len = line_end - self->textbuf->str;
384   line = convert_encoding (self, self->textbuf->str, line_len);
385   self->textbuf = g_string_erase (self->textbuf, 0,
386       line_len + (have_r ? 2 : 1));
387   return line;
388 }
389
390 static gchar *
391 parse_mdvdsub (ParserState * state, const gchar * line)
392 {
393   const gchar *line_split;
394   gchar *line_chunk;
395   guint start_frame, end_frame;
396   gint64 clip_start = 0, clip_stop = 0;
397   gboolean in_seg = FALSE;
398
399   /* FIXME: hardcoded for now, but detecting the correct value is
400    * not going to be easy, I suspect... */
401   const double frames_per_sec = 24000 / 1001.;
402   GString *markup;
403   gchar *ret;
404
405   /* style variables */
406   gboolean italic;
407   gboolean bold;
408   guint fontsize;
409
410   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
411     g_warning ("Parse of the following line, assumed to be in microdvd .sub"
412         " format, failed:\n%s", line);
413     return NULL;
414   }
415
416   state->start_time = (start_frame - 1000) / frames_per_sec * GST_SECOND;
417   state->duration = (end_frame - start_frame) / frames_per_sec * GST_SECOND;
418
419   /* Check our segment start/stop */
420   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
421       state->start_time, state->start_time + state->duration, &clip_start,
422       &clip_stop);
423
424   /* No need to parse that text if it's out of segment */
425   if (in_seg) {
426     state->start_time = clip_start;
427     state->duration = clip_stop - clip_start;
428   } else {
429     return NULL;
430   }
431
432   /* skip the {%u}{%u} part */
433   line = strchr (line, '}') + 1;
434   line = strchr (line, '}') + 1;
435
436   markup = g_string_new (NULL);
437   while (1) {
438     italic = FALSE;
439     bold = FALSE;
440     fontsize = 0;
441     /* parse style markup */
442     if (strncmp (line, "{y:i}", 5) == 0) {
443       italic = TRUE;
444       line = strchr (line, '}') + 1;
445     }
446     if (strncmp (line, "{y:b}", 5) == 0) {
447       bold = TRUE;
448       line = strchr (line, '}') + 1;
449     }
450     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
451       line = strchr (line, '}') + 1;
452     }
453     if ((line_split = strchr (line, '|')))
454       line_chunk = g_markup_escape_text (line, line_split - line);
455     else
456       line_chunk = g_markup_escape_text (line, strlen (line));
457     markup = g_string_append (markup, "<span");
458     if (italic)
459       g_string_append (markup, " style=\"italic\"");
460     if (bold)
461       g_string_append (markup, " weight=\"bold\"");
462     if (fontsize)
463       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
464     g_string_append_printf (markup, ">%s</span>", line_chunk);
465     g_free (line_chunk);
466     if (line_split) {
467       g_string_append (markup, "\n");
468       line = line_split + 1;
469     } else {
470       break;
471     }
472   }
473   ret = markup->str;
474   g_string_free (markup, FALSE);
475   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
476       state->start_time / (double) GST_SECOND,
477       state->duration / (double) GST_SECOND, ret);
478   return ret;
479 }
480
481 static void
482 strip_trailing_newlines (gchar * txt)
483 {
484   if (txt) {
485     guint len;
486
487     len = strlen (txt);
488     while (len > 1 && txt[len - 1] == '\n') {
489       txt[len - 1] = '\0';
490       --len;
491     }
492   }
493 }
494
495 /* we want to escape text in general, but retain basic markup like
496  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
497  * just unescape a white list of allowed markups again after
498  * escaping everything (the text between these simple markers isn't
499  * necessarily escaped, so it seems best to do it like this) */
500 static void
501 subrip_unescape_formatting (gchar * txt)
502 {
503   gchar *pos;
504
505   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
506     if (g_ascii_strncasecmp (pos, "&lt;u&gt;", 9) == 0 ||
507         g_ascii_strncasecmp (pos, "&lt;i&gt;", 9) == 0 ||
508         g_ascii_strncasecmp (pos, "&lt;b&gt;", 9) == 0) {
509       pos[0] = '<';
510       pos[1] = g_ascii_tolower (pos[4]);
511       pos[2] = '>';
512       /* move NUL terminator as well */
513       g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
514       pos += 2;
515     }
516   }
517
518   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
519     if (g_ascii_strncasecmp (pos, "&lt;/u&gt;", 10) == 0 ||
520         g_ascii_strncasecmp (pos, "&lt;/i&gt;", 10) == 0 ||
521         g_ascii_strncasecmp (pos, "&lt;/b&gt;", 10) == 0) {
522       pos[0] = '<';
523       pos[1] = '/';
524       pos[2] = g_ascii_tolower (pos[5]);
525       pos[3] = '>';
526       /* move NUL terminator as well */
527       g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
528       pos += 3;
529     }
530   }
531 }
532
533 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
534  * assumes the input has been escaped and subrip_unescape_formatting() has then
535  * been run over the input! This function adds missing closing markup tags and
536  * removes broken closing tags for tags that have never been opened. */
537 static void
538 subrip_fix_up_markup (gchar ** p_txt)
539 {
540   gchar *cur, *next_tag;
541   gchar open_tags[32];
542   guint num_open_tags = 0;
543
544   g_assert (*p_txt != NULL);
545
546   cur = *p_txt;
547   while (*cur != '\0') {
548     next_tag = strchr (cur, '<');
549     if (next_tag == NULL)
550       break;
551     ++next_tag;
552     switch (*next_tag) {
553       case '/':{
554         ++next_tag;
555         if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
556           GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
557           g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
558           next_tag -= 2;
559         } else {
560           /* it's all good, closing tag which is open */
561           --num_open_tags;
562         }
563         break;
564       }
565       case 'i':
566       case 'b':
567       case 'u':
568         if (num_open_tags == G_N_ELEMENTS (open_tags))
569           return;               /* something dodgy is going on, stop parsing */
570         open_tags[num_open_tags] = *next_tag;
571         ++num_open_tags;
572         break;
573       default:
574         GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
575         g_assert_not_reached ();
576         break;
577     }
578     cur = next_tag;
579   }
580
581   if (num_open_tags > 0) {
582     GString *s;
583
584     s = g_string_new (*p_txt);
585     while (num_open_tags > 0) {
586       GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
587       g_string_append_c (s, '<');
588       g_string_append_c (s, '/');
589       g_string_append_c (s, open_tags[num_open_tags - 1]);
590       g_string_append_c (s, '>');
591       --num_open_tags;
592     }
593     g_free (*p_txt);
594     *p_txt = g_string_free (s, FALSE);
595   }
596 }
597
598 static gchar *
599 parse_subrip (ParserState * state, const gchar * line)
600 {
601   guint h1, m1, s1, ms1;
602   guint h2, m2, s2, ms2;
603   int subnum;
604   gchar *ret;
605
606   switch (state->state) {
607     case 0:
608       /* looking for a single integer */
609       if (sscanf (line, "%u", &subnum) == 1)
610         state->state = 1;
611       return NULL;
612     case 1:
613       /* looking for start_time --> end_time */
614       if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
615               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
616         state->state = 2;
617         state->start_time =
618             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
619             ms1 * GST_MSECOND;
620         state->duration =
621             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
622             ms2 * GST_MSECOND - state->start_time;
623       } else {
624         GST_DEBUG ("error parsing subrip time line");
625         state->state = 0;
626       }
627       return NULL;
628     case 2:
629     {                           /* No need to parse that text if it's out of segment */
630       gint64 clip_start = 0, clip_stop = 0;
631       gboolean in_seg = FALSE;
632
633       /* Check our segment start/stop */
634       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
635           state->start_time, state->start_time + state->duration,
636           &clip_start, &clip_stop);
637
638       if (in_seg) {
639         state->start_time = clip_start;
640         state->duration = clip_stop - clip_start;
641       } else {
642         state->state = 0;
643         return NULL;
644       }
645     }
646       /* looking for subtitle text; empty line ends this
647        * subtitle entry */
648       if (state->buf->len)
649         g_string_append_c (state->buf, '\n');
650       g_string_append (state->buf, line);
651       if (strlen (line) == 0) {
652         ret = g_markup_escape_text (state->buf->str, state->buf->len);
653         g_string_truncate (state->buf, 0);
654         state->state = 0;
655         subrip_unescape_formatting (ret);
656         strip_trailing_newlines (ret);
657         subrip_fix_up_markup (&ret);
658         return ret;
659       }
660       return NULL;
661     default:
662       g_return_val_if_reached (NULL);
663   }
664 }
665
666 static gchar *
667 parse_mpsub (ParserState * state, const gchar * line)
668 {
669   gchar *ret;
670   float t1, t2;
671
672   switch (state->state) {
673     case 0:
674       /* looking for two floats (offset, duration) */
675       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
676         state->state = 1;
677         state->start_time += state->duration + GST_SECOND * t1;
678         state->duration = GST_SECOND * t2;
679       }
680       return NULL;
681     case 1:
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_strdup (state->buf->str);
706         g_string_truncate (state->buf, 0);
707         state->state = 0;
708         return ret;
709       }
710       return NULL;
711     default:
712       g_assert_not_reached ();
713       return NULL;
714   }
715 }
716
717 static void
718 parser_state_init (ParserState * state)
719 {
720   GST_DEBUG ("initialising parser");
721
722   if (state->buf) {
723     g_string_truncate (state->buf, 0);
724   } else {
725     state->buf = g_string_new (NULL);
726   }
727
728   state->start_time = 0;
729   state->duration = 0;
730   state->state = 0;
731   state->segment = NULL;
732 }
733
734 static void
735 parser_state_dispose (ParserState * state)
736 {
737   if (state->buf) {
738     g_string_free (state->buf, TRUE);
739     state->buf = NULL;
740   }
741   if (state->user_data) {
742     sami_context_reset (state);
743   }
744 }
745
746 /*
747  * FIXME: maybe we should pass along a second argument, the preceding
748  * text buffer, because that is how this originally worked, even though
749  * I don't really see the use of that.
750  */
751
752 static GstSubParseFormat
753 gst_sub_parse_data_format_autodetect (gchar * match_str)
754 {
755   static gboolean need_init_regexps = TRUE;
756   static regex_t mdvd_rx;
757   static regex_t subrip_rx;
758   guint n1, n2, n3;
759
760   /* initialize the regexps used the first time around */
761   if (need_init_regexps) {
762     int err;
763     char errstr[128];
764
765     need_init_regexps = FALSE;
766     if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
767                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
768         (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
769                 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
770                 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
771                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
772       regerror (err, &subrip_rx, errstr, 127);
773       GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
774     }
775   }
776
777   if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
778     GST_LOG ("MicroDVD (frame based) format detected");
779     return GST_SUB_PARSE_FORMAT_MDVDSUB;
780   }
781   if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
782     GST_LOG ("SubRip (time based) format detected");
783     return GST_SUB_PARSE_FORMAT_SUBRIP;
784   }
785   if (!strncmp (match_str, "FORMAT=TIME", 11)) {
786     GST_LOG ("MPSub (time based) format detected");
787     return GST_SUB_PARSE_FORMAT_MPSUB;
788   }
789   if (strstr (match_str, "<SAMI>") != NULL ||
790       strstr (match_str, "<sami>") != NULL) {
791     GST_LOG ("SAMI (time based) format detected");
792     return GST_SUB_PARSE_FORMAT_SAMI;
793   }
794   /* we're boldly assuming the first subtitle appears within the first hour */
795   if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
796       sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
797       sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
798       sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
799       sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
800     GST_LOG ("TMPlayer (time based) format detected");
801     return GST_SUB_PARSE_FORMAT_TMPLAYER;
802   }
803
804   GST_DEBUG ("no subtitle format detected");
805   return GST_SUB_PARSE_FORMAT_UNKNOWN;
806 }
807
808 static GstCaps *
809 gst_sub_parse_format_autodetect (GstSubParse * self)
810 {
811   gchar *data;
812   GstSubParseFormat format;
813
814   if (strlen (self->textbuf->str) < 35) {
815     GST_DEBUG ("File too small to be a subtitles file");
816     return NULL;
817   }
818
819   data = g_strndup (self->textbuf->str, 35);
820   format = gst_sub_parse_data_format_autodetect (data);
821   g_free (data);
822
823   self->parser_type = format;
824   parser_state_init (&self->state);
825
826   switch (format) {
827     case GST_SUB_PARSE_FORMAT_MDVDSUB:
828       self->parse_line = parse_mdvdsub;
829       return gst_caps_new_simple ("text/x-pango-markup", NULL);
830     case GST_SUB_PARSE_FORMAT_SUBRIP:
831       self->parse_line = parse_subrip;
832       return gst_caps_new_simple ("text/x-pango-markup", NULL);
833     case GST_SUB_PARSE_FORMAT_MPSUB:
834       self->parse_line = parse_mpsub;
835       return gst_caps_new_simple ("text/plain", NULL);
836     case GST_SUB_PARSE_FORMAT_SAMI:
837       self->parse_line = parse_sami;
838       sami_context_init (&self->state);
839       return gst_caps_new_simple ("text/x-pango-markup", NULL);
840     case GST_SUB_PARSE_FORMAT_TMPLAYER:
841       self->parse_line = parse_tmplayer;
842       return gst_caps_new_simple ("text/plain", NULL);
843     case GST_SUB_PARSE_FORMAT_UNKNOWN:
844     default:
845       GST_DEBUG ("no subtitle format detected");
846       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
847           ("The input is not a valid/supported subtitle file"), (NULL));
848       return NULL;
849   }
850 }
851
852 static void
853 feed_textbuf (GstSubParse * self, GstBuffer * buf)
854 {
855   if (GST_BUFFER_OFFSET (buf) != self->offset) {
856     /* flush the parser state */
857     parser_state_init (&self->state);
858     g_string_truncate (self->textbuf, 0);
859     sami_context_reset (&self->state);
860   }
861
862   self->textbuf = g_string_append_len (self->textbuf,
863       (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
864   self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
865   self->next_offset = self->offset;
866
867   gst_buffer_unref (buf);
868 }
869
870 static GstFlowReturn
871 handle_buffer (GstSubParse * self, GstBuffer * buf)
872 {
873   GstFlowReturn ret = GST_FLOW_OK;
874   GstCaps *caps = NULL;
875   gchar *line, *subtitle;
876
877   feed_textbuf (self, buf);
878
879   /* make sure we know the format */
880   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
881     if (!(caps = gst_sub_parse_format_autodetect (self))) {
882       return GST_FLOW_UNEXPECTED;
883     }
884     if (!gst_pad_set_caps (self->srcpad, caps)) {
885       gst_caps_unref (caps);
886       return GST_FLOW_UNEXPECTED;
887     }
888     gst_caps_unref (caps);
889   }
890
891   while ((line = get_next_line (self)) && !self->flushing) {
892     /* Set segment on our parser state machine */
893     self->state.segment = self->segment;
894     /* Now parse the line, out of segment lines will just return NULL */
895     GST_LOG_OBJECT (self, "Parsing line '%s'", line);
896     subtitle = self->parse_line (&self->state, line);
897     g_free (line);
898
899     if (subtitle) {
900       guint subtitle_len = strlen (subtitle);
901
902       /* +1 for terminating NUL character */
903       ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
904           GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
905           GST_PAD_CAPS (self->srcpad), &buf);
906
907       if (ret == GST_FLOW_OK) {
908         /* copy terminating NUL character as well */
909         memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
910         GST_BUFFER_SIZE (buf) = subtitle_len;
911         GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
912         GST_BUFFER_DURATION (buf) = self->state.duration;
913
914         gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
915             self->state.start_time);
916
917         GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
918             GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
919             GST_TIME_ARGS (self->state.duration));
920
921         ret = gst_pad_push (self->srcpad, buf);
922       }
923
924       g_free (subtitle);
925       subtitle = NULL;
926
927       if (GST_FLOW_IS_FATAL (ret))
928         break;
929     }
930   }
931
932   return ret;
933 }
934
935 static GstFlowReturn
936 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
937 {
938   GstFlowReturn ret;
939   GstSubParse *self;
940
941   self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
942
943   /* Push newsegment if needed */
944   if (self->need_segment) {
945     gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
946             self->segment->rate, self->segment->format,
947             self->segment->last_stop, self->segment->stop,
948             self->segment->time));
949     self->need_segment = FALSE;
950   }
951
952   ret = handle_buffer (self, buf);
953
954   return ret;
955 }
956
957 static gboolean
958 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
959 {
960   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
961   gboolean ret = FALSE;
962
963   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
964
965   switch (GST_EVENT_TYPE (event)) {
966     case GST_EVENT_EOS:{
967       /* Make sure the last subrip chunk is pushed out even
968        * if the file does not have an empty line at the end */
969       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
970         GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
971
972         GST_DEBUG ("EOS. Pushing remaining text (if any)");
973         GST_BUFFER_DATA (buf)[0] = '\n';
974         GST_BUFFER_DATA (buf)[1] = '\0';        /* play it safe */
975         GST_BUFFER_SIZE (buf) = 1;
976         GST_BUFFER_OFFSET (buf) = self->offset;
977         gst_sub_parse_chain (pad, buf);
978       }
979       ret = gst_pad_event_default (pad, event);
980       break;
981     }
982     case GST_EVENT_NEWSEGMENT:
983     {
984       GstFormat format;
985       gdouble rate;
986       gint64 start, stop, time;
987       gboolean update;
988
989       GST_DEBUG_OBJECT (self, "received new segment");
990
991       gst_event_parse_new_segment (event, &update, &rate, &format, &start,
992           &stop, &time);
993
994       /* now copy over the values */
995       gst_segment_set_newsegment (self->segment, update, rate, format,
996           start, stop, time);
997
998       ret = TRUE;
999       gst_event_unref (event);
1000       break;
1001     }
1002     case GST_EVENT_FLUSH_START:
1003     {
1004       self->flushing = TRUE;
1005
1006       ret = gst_pad_event_default (pad, event);
1007       break;
1008     }
1009     case GST_EVENT_FLUSH_STOP:
1010     {
1011       self->flushing = FALSE;
1012
1013       ret = gst_pad_event_default (pad, event);
1014       break;
1015     }
1016     default:
1017       ret = gst_pad_event_default (pad, event);
1018       break;
1019   }
1020
1021   gst_object_unref (self);
1022
1023   return ret;
1024 }
1025
1026
1027 static GstStateChangeReturn
1028 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1029 {
1030   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1031   GstSubParse *self = GST_SUBPARSE (element);
1032
1033   switch (transition) {
1034     case GST_STATE_CHANGE_READY_TO_PAUSED:
1035       /* format detection will init the parser state */
1036       self->offset = 0;
1037       self->next_offset = 0;
1038       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1039       self->valid_utf8 = TRUE;
1040       g_string_truncate (self->textbuf, 0);
1041       break;
1042     default:
1043       break;
1044   }
1045
1046   ret = parent_class->change_state (element, transition);
1047   if (ret == GST_STATE_CHANGE_FAILURE)
1048     return ret;
1049
1050   switch (transition) {
1051     case GST_STATE_CHANGE_PAUSED_TO_READY:
1052       parser_state_dispose (&self->state);
1053       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1054       break;
1055     default:
1056       break;
1057   }
1058
1059   return ret;
1060 }
1061
1062 /*
1063  * Typefind support.
1064  */
1065
1066 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1067  * also, give different  subtitle formats really different types */
1068 static GstStaticCaps tmp_caps =
1069 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1070 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1071 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1072
1073 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1074 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1075 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1076
1077 static void
1078 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1079 {
1080   GstSubParseFormat format;
1081   const guint8 *data;
1082   GstCaps *caps;
1083   gchar *str;
1084
1085   if (!(data = gst_type_find_peek (tf, 0, 36)))
1086     return;
1087
1088   /* make sure string passed to _autodetect() is NUL-terminated */
1089   str = g_strndup ((gchar *) data, 35);
1090   format = gst_sub_parse_data_format_autodetect (str);
1091   g_free (str);
1092
1093   switch (format) {
1094     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1095       GST_DEBUG ("MicroDVD format detected");
1096       caps = SUB_CAPS;
1097       break;
1098     case GST_SUB_PARSE_FORMAT_SUBRIP:
1099       GST_DEBUG ("SubRip format detected");
1100       caps = SUB_CAPS;
1101       break;
1102     case GST_SUB_PARSE_FORMAT_MPSUB:
1103       GST_DEBUG ("MPSub format detected");
1104       caps = SUB_CAPS;
1105       break;
1106     case GST_SUB_PARSE_FORMAT_SAMI:
1107       GST_DEBUG ("SAMI (time-based) format detected");
1108       caps = SAMI_CAPS;
1109       break;
1110     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1111       GST_DEBUG ("TMPlayer (time based) format detected");
1112       caps = TMP_CAPS;
1113       break;
1114     default:
1115     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1116       GST_DEBUG ("no subtitle format detected");
1117       return;
1118   }
1119
1120   /* if we're here, it's ok */
1121   gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1122 }
1123
1124 static gboolean
1125 plugin_init (GstPlugin * plugin)
1126 {
1127   static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1128     NULL
1129   };
1130
1131   GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1132
1133   if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1134           gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1135     return FALSE;
1136
1137   if (!gst_element_register (plugin, "subparse",
1138           GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1139       !gst_element_register (plugin, "ssaparse",
1140           GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1141     return FALSE;
1142   }
1143
1144   return TRUE;
1145 }
1146
1147 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1148     GST_VERSION_MINOR,
1149     "subparse",
1150     "Subtitle parsing",
1151     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)