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