gst/subparse/gstsubparse.*: Add 'encoding' property (#341681).
[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 (G_OBJECT_CLASS (klass), PROP_ENCODING,
166       g_param_spec_string ("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       break;
282     default:
283       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
284       break;
285   }
286   GST_OBJECT_UNLOCK (subparse);
287 }
288
289 static void
290 gst_sub_parse_get_property (GObject * object, guint prop_id,
291     GValue * value, GParamSpec * pspec)
292 {
293   GstSubParse *subparse = GST_SUBPARSE (object);
294
295   GST_OBJECT_LOCK (subparse);
296   switch (prop_id) {
297     case PROP_ENCODING:
298       g_value_set_string (value, subparse->encoding);
299       break;
300     default:
301       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
302       break;
303   }
304   GST_OBJECT_UNLOCK (subparse);
305 }
306
307 static gchar *
308 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
309 {
310   const gchar *encoding;
311   GError *err = NULL;
312   gchar *ret;
313
314   if (self->valid_utf8) {
315     if (g_utf8_validate (str, len, NULL)) {
316       GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
317       return g_strndup (str, len);
318     }
319     GST_INFO_OBJECT (self, "invalid UTF-8!");
320     self->valid_utf8 = FALSE;
321   }
322
323   encoding = self->encoding;
324   if (encoding == NULL || *encoding == '\0') {
325     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
326   }
327   if (encoding == NULL || *encoding == '\0') {
328     /* if local encoding is UTF-8 and no encoding specified
329      * via the environment variable, assume ISO-8859-15 */
330     if (g_get_charset (&encoding)) {
331       encoding = "ISO-8859-15";
332     }
333   }
334
335   ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
336       NULL, &err);
337
338   if (err) {
339     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
340         encoding, err->message);
341     g_error_free (err);
342
343     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
344     ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
345         NULL, NULL, NULL);
346   }
347
348   GST_LOG_OBJECT (self, "successfully converted %d characters from %s to UTF-8"
349       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
350
351   return ret;
352 }
353
354 static gchar *
355 get_next_line (GstSubParse * self)
356 {
357   char *line = NULL;
358   const char *line_end;
359   int line_len;
360   gboolean have_r = FALSE;
361
362   line_end = strchr (self->textbuf->str, '\n');
363
364   if (!line_end) {
365     /* end-of-line not found; return for more data */
366     return NULL;
367   }
368
369   /* get rid of '\r' */
370   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
371     line_end--;
372     have_r = TRUE;
373   }
374
375   line_len = line_end - self->textbuf->str;
376   line = convert_encoding (self, self->textbuf->str, line_len);
377   self->textbuf = g_string_erase (self->textbuf, 0,
378       line_len + (have_r ? 2 : 1));
379   return line;
380 }
381
382 static gchar *
383 parse_mdvdsub (ParserState * state, const gchar * line)
384 {
385   const gchar *line_split;
386   gchar *line_chunk;
387   guint start_frame, end_frame;
388   gint64 clip_start = 0, clip_stop = 0;
389   gboolean in_seg = FALSE;
390
391   /* FIXME: hardcoded for now, but detecting the correct value is
392    * not going to be easy, I suspect... */
393   const double frames_per_sec = 24000 / 1001.;
394   GString *markup;
395   gchar *ret;
396
397   /* style variables */
398   gboolean italic;
399   gboolean bold;
400   guint fontsize;
401
402   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
403     g_warning ("Parse of the following line, assumed to be in microdvd .sub"
404         " format, failed:\n%s", line);
405     return NULL;
406   }
407
408   state->start_time = (start_frame - 1000) / frames_per_sec * GST_SECOND;
409   state->duration = (end_frame - start_frame) / frames_per_sec * GST_SECOND;
410
411   /* Check our segment start/stop */
412   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
413       state->start_time, state->start_time + state->duration, &clip_start,
414       &clip_stop);
415
416   /* No need to parse that text if it's out of segment */
417   if (in_seg) {
418     state->start_time = clip_start;
419     state->duration = clip_stop - clip_start;
420   } else {
421     return NULL;
422   }
423
424   /* skip the {%u}{%u} part */
425   line = strchr (line, '}') + 1;
426   line = strchr (line, '}') + 1;
427
428   markup = g_string_new (NULL);
429   while (1) {
430     italic = FALSE;
431     bold = FALSE;
432     fontsize = 0;
433     /* parse style markup */
434     if (strncmp (line, "{y:i}", 5) == 0) {
435       italic = TRUE;
436       line = strchr (line, '}') + 1;
437     }
438     if (strncmp (line, "{y:b}", 5) == 0) {
439       bold = TRUE;
440       line = strchr (line, '}') + 1;
441     }
442     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
443       line = strchr (line, '}') + 1;
444     }
445     if ((line_split = strchr (line, '|')))
446       line_chunk = g_markup_escape_text (line, line_split - line);
447     else
448       line_chunk = g_markup_escape_text (line, strlen (line));
449     markup = g_string_append (markup, "<span");
450     if (italic)
451       g_string_append (markup, " style=\"italic\"");
452     if (bold)
453       g_string_append (markup, " weight=\"bold\"");
454     if (fontsize)
455       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
456     g_string_append_printf (markup, ">%s</span>", line_chunk);
457     g_free (line_chunk);
458     if (line_split) {
459       g_string_append (markup, "\n");
460       line = line_split + 1;
461     } else {
462       break;
463     }
464   }
465   ret = markup->str;
466   g_string_free (markup, FALSE);
467   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
468       state->start_time / (double) GST_SECOND,
469       state->duration / (double) GST_SECOND, ret);
470   return ret;
471 }
472
473 /* we want to escape text in general, but retain basic markup like
474  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
475  * just unescape a white list of allowed markups again after
476  * escaping everything (the text between these simple markers isn't
477  * necessarily escaped, so it seems best to do it like this) */
478 static void
479 subrip_unescape_formatting (gchar * txt)
480 {
481   gchar *pos;
482
483   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
484     if (g_ascii_strncasecmp (pos, "&lt;u&gt;", 9) == 0 ||
485         g_ascii_strncasecmp (pos, "&lt;i&gt;", 9) == 0 ||
486         g_ascii_strncasecmp (pos, "&lt;b&gt;", 9) == 0) {
487       pos[0] = '<';
488       pos[1] = g_ascii_tolower (pos[4]);
489       pos[2] = '>';
490       /* move NUL terminator as well */
491       g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
492       pos += 2;
493     }
494   }
495
496   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
497     if (g_ascii_strncasecmp (pos, "&lt;/u&gt;", 10) == 0 ||
498         g_ascii_strncasecmp (pos, "&lt;/i&gt;", 10) == 0 ||
499         g_ascii_strncasecmp (pos, "&lt;/b&gt;", 10) == 0) {
500       pos[0] = '<';
501       pos[1] = '/';
502       pos[2] = g_ascii_tolower (pos[5]);
503       pos[3] = '>';
504       /* move NUL terminator as well */
505       g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
506       pos += 3;
507     }
508   }
509 }
510
511 static gchar *
512 parse_subrip (ParserState * state, const gchar * line)
513 {
514   guint h1, m1, s1, ms1;
515   guint h2, m2, s2, ms2;
516   int subnum;
517   gchar *ret;
518
519   switch (state->state) {
520     case 0:
521       /* looking for a single integer */
522       if (sscanf (line, "%u", &subnum) == 1)
523         state->state = 1;
524       return NULL;
525     case 1:
526       /* looking for start_time --> end_time */
527       if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
528               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
529         state->state = 2;
530         state->start_time =
531             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
532             ms1 * GST_MSECOND;
533         state->duration =
534             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
535             ms2 * GST_MSECOND - state->start_time;
536       } else {
537         GST_DEBUG ("error parsing subrip time line");
538         state->state = 0;
539       }
540       return NULL;
541     case 2:
542     {                           /* No need to parse that text if it's out of segment */
543       gint64 clip_start = 0, clip_stop = 0;
544       gboolean in_seg = FALSE;
545
546       /* Check our segment start/stop */
547       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
548           state->start_time, state->start_time + state->duration,
549           &clip_start, &clip_stop);
550
551       if (in_seg) {
552         state->start_time = clip_start;
553         state->duration = clip_stop - clip_start;
554       } else {
555         state->state = 0;
556         return NULL;
557       }
558     }
559       /* looking for subtitle text; empty line ends this
560        * subtitle entry */
561       if (state->buf->len)
562         g_string_append_c (state->buf, '\n');
563       g_string_append (state->buf, line);
564       if (strlen (line) == 0) {
565         ret = g_markup_escape_text (state->buf->str, state->buf->len);
566         g_string_truncate (state->buf, 0);
567         state->state = 0;
568         subrip_unescape_formatting (ret);
569         return ret;
570       }
571       return NULL;
572     default:
573       g_return_val_if_reached (NULL);
574   }
575 }
576
577 static gchar *
578 parse_mpsub (ParserState * state, const gchar * line)
579 {
580   gchar *ret;
581   float t1, t2;
582
583   switch (state->state) {
584     case 0:
585       /* looking for two floats (offset, duration) */
586       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
587         state->state = 1;
588         state->start_time += state->duration + GST_SECOND * t1;
589         state->duration = GST_SECOND * t2;
590       }
591       return NULL;
592     case 1:
593     {                           /* No need to parse that text if it's out of segment */
594       gint64 clip_start = 0, clip_stop = 0;
595       gboolean in_seg = FALSE;
596
597       /* Check our segment start/stop */
598       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
599           state->start_time, state->start_time + state->duration,
600           &clip_start, &clip_stop);
601
602       if (in_seg) {
603         state->start_time = clip_start;
604         state->duration = clip_stop - clip_start;
605       } else {
606         state->state = 0;
607         return NULL;
608       }
609     }
610       /* looking for subtitle text; empty line ends this
611        * subtitle entry */
612       if (state->buf->len)
613         g_string_append_c (state->buf, '\n');
614       g_string_append (state->buf, line);
615       if (strlen (line) == 0) {
616         ret = g_strdup (state->buf->str);
617         g_string_truncate (state->buf, 0);
618         state->state = 0;
619         return ret;
620       }
621       return NULL;
622     default:
623       g_assert_not_reached ();
624       return NULL;
625   }
626 }
627
628 static void
629 parser_state_init (ParserState * state)
630 {
631   GST_DEBUG ("initialising parser");
632
633   if (state->buf) {
634     g_string_truncate (state->buf, 0);
635   } else {
636     state->buf = g_string_new (NULL);
637   }
638
639   state->start_time = 0;
640   state->duration = 0;
641   state->state = 0;
642   state->segment = NULL;
643 }
644
645 static void
646 parser_state_dispose (ParserState * state)
647 {
648   if (state->buf) {
649     g_string_free (state->buf, TRUE);
650     state->buf = NULL;
651   }
652   if (state->user_data) {
653     sami_context_reset (state);
654   }
655 }
656
657 /*
658  * FIXME: maybe we should pass along a second argument, the preceding
659  * text buffer, because that is how this originally worked, even though
660  * I don't really see the use of that.
661  */
662
663 static GstSubParseFormat
664 gst_sub_parse_data_format_autodetect (gchar * match_str)
665 {
666   static gboolean need_init_regexps = TRUE;
667   static regex_t mdvd_rx;
668   static regex_t subrip_rx;
669
670   /* initialize the regexps used the first time around */
671   if (need_init_regexps) {
672     int err;
673     char errstr[128];
674
675     need_init_regexps = FALSE;
676     if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
677                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
678         (err = regcomp (&subrip_rx, "^1(\x0d)?\x0a"
679                 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
680                 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
681                 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
682       regerror (err, &subrip_rx, errstr, 127);
683       GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
684     }
685   }
686
687   if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
688     GST_LOG ("MicroDVD (frame based) format detected");
689     return GST_SUB_PARSE_FORMAT_MDVDSUB;
690   }
691   if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
692     GST_LOG ("SubRip (time based) format detected");
693     return GST_SUB_PARSE_FORMAT_SUBRIP;
694   }
695   if (!strncmp (match_str, "FORMAT=TIME", 11)) {
696     GST_LOG ("MPSub (time based) format detected");
697     return GST_SUB_PARSE_FORMAT_MPSUB;
698   }
699   if (strstr (match_str, "<SAMI>") != NULL ||
700       strstr (match_str, "<sami>") != NULL) {
701     GST_LOG ("SAMI (time based) format detected");
702     return GST_SUB_PARSE_FORMAT_SAMI;
703   }
704
705   GST_DEBUG ("no subtitle format detected");
706   return GST_SUB_PARSE_FORMAT_UNKNOWN;
707 }
708
709 static GstCaps *
710 gst_sub_parse_format_autodetect (GstSubParse * self)
711 {
712   gchar *data;
713   GstSubParseFormat format;
714
715   if (strlen (self->textbuf->str) < 35) {
716     GST_DEBUG ("File too small to be a subtitles file");
717     return NULL;
718   }
719
720   data = g_strndup (self->textbuf->str, 35);
721   format = gst_sub_parse_data_format_autodetect (data);
722   g_free (data);
723
724   self->parser_type = format;
725   parser_state_init (&self->state);
726
727   switch (format) {
728     case GST_SUB_PARSE_FORMAT_MDVDSUB:
729       self->parse_line = parse_mdvdsub;
730       return gst_caps_new_simple ("text/x-pango-markup", NULL);
731     case GST_SUB_PARSE_FORMAT_SUBRIP:
732       self->parse_line = parse_subrip;
733       return gst_caps_new_simple ("text/x-pango-markup", NULL);
734     case GST_SUB_PARSE_FORMAT_MPSUB:
735       self->parse_line = parse_mpsub;
736       return gst_caps_new_simple ("text/plain", NULL);
737     case GST_SUB_PARSE_FORMAT_SAMI:
738       self->parse_line = parse_sami;
739       sami_context_init (&self->state);
740       return gst_caps_new_simple ("text/x-pango-markup", NULL);
741     case GST_SUB_PARSE_FORMAT_UNKNOWN:
742     default:
743       GST_DEBUG ("no subtitle format detected");
744       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
745           ("The input is not a valid/supported subtitle file"), (NULL));
746       return NULL;
747   }
748 }
749
750 static void
751 feed_textbuf (GstSubParse * self, GstBuffer * buf)
752 {
753   if (GST_BUFFER_OFFSET (buf) != self->offset) {
754     /* flush the parser state */
755     parser_state_init (&self->state);
756     g_string_truncate (self->textbuf, 0);
757     sami_context_reset (&self->state);
758   }
759
760   self->textbuf = g_string_append_len (self->textbuf,
761       (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
762   self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
763   self->next_offset = self->offset;
764
765   gst_buffer_unref (buf);
766 }
767
768 static GstFlowReturn
769 handle_buffer (GstSubParse * self, GstBuffer * buf)
770 {
771   GstFlowReturn ret = GST_FLOW_OK;
772   GstCaps *caps = NULL;
773   gchar *line, *subtitle;
774
775   feed_textbuf (self, buf);
776
777   /* make sure we know the format */
778   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
779     if (!(caps = gst_sub_parse_format_autodetect (self))) {
780       return GST_FLOW_UNEXPECTED;
781     }
782     if (!gst_pad_set_caps (self->srcpad, caps)) {
783       gst_caps_unref (caps);
784       return GST_FLOW_UNEXPECTED;
785     }
786     gst_caps_unref (caps);
787   }
788
789   while ((line = get_next_line (self)) && !self->flushing) {
790     /* Set segment on our parser state machine */
791     self->state.segment = self->segment;
792     /* Now parse the line, out of segment lines will just return NULL */
793     GST_DEBUG ("Parsing line '%s'", line);
794     subtitle = self->parse_line (&self->state, line);
795     g_free (line);
796
797     if (subtitle) {
798       guint subtitle_len = strlen (subtitle);
799
800       ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
801           GST_BUFFER_OFFSET_NONE, subtitle_len,
802           GST_PAD_CAPS (self->srcpad), &buf);
803
804       if (ret == GST_FLOW_OK) {
805         memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len);
806         GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
807         GST_BUFFER_DURATION (buf) = self->state.duration;
808
809         gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
810             self->state.start_time);
811
812         GST_DEBUG ("Sending text '%s', %" GST_TIME_FORMAT " + %"
813             GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
814             GST_TIME_ARGS (self->state.duration));
815
816         ret = gst_pad_push (self->srcpad, buf);
817       }
818
819       g_free (subtitle);
820       subtitle = NULL;
821
822       if (GST_FLOW_IS_FATAL (ret))
823         break;
824     }
825   }
826
827   return ret;
828 }
829
830 static GstFlowReturn
831 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
832 {
833   GstFlowReturn ret;
834   GstSubParse *self;
835
836   GST_DEBUG ("gst_sub_parse_chain");
837   self = GST_SUBPARSE (gst_pad_get_parent (sinkpad));
838
839   /* Push newsegment if needed */
840   if (self->need_segment) {
841     gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
842             self->segment->rate, self->segment->format,
843             self->segment->last_stop, self->segment->stop,
844             self->segment->time));
845     self->need_segment = FALSE;
846   }
847
848   ret = handle_buffer (self, buf);
849
850   gst_object_unref (self);
851
852   return ret;
853 }
854
855 static gboolean
856 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
857 {
858   GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
859   gboolean ret = FALSE;
860
861   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
862
863   switch (GST_EVENT_TYPE (event)) {
864     case GST_EVENT_EOS:{
865       /* Make sure the last subrip chunk is pushed out even
866        * if the file does not have an empty line at the end */
867       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
868         GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
869
870         GST_DEBUG ("EOS. Pushing remaining text (if any)");
871         GST_BUFFER_DATA (buf)[0] = '\n';
872         GST_BUFFER_DATA (buf)[1] = '\0';        /* play it safe */
873         GST_BUFFER_SIZE (buf) = 1;
874         GST_BUFFER_OFFSET (buf) = self->offset;
875         gst_sub_parse_chain (pad, buf);
876       }
877       ret = gst_pad_event_default (pad, event);
878       break;
879     }
880     case GST_EVENT_NEWSEGMENT:
881     {
882       GstFormat format;
883       gdouble rate;
884       gint64 start, stop, time;
885       gboolean update;
886
887       GST_DEBUG_OBJECT (self, "received new segment");
888
889       gst_event_parse_new_segment (event, &update, &rate, &format, &start,
890           &stop, &time);
891
892       /* now copy over the values */
893       gst_segment_set_newsegment (self->segment, update, rate, format,
894           start, stop, time);
895
896       ret = TRUE;
897       gst_event_unref (event);
898       break;
899     }
900     case GST_EVENT_FLUSH_START:
901     {
902       self->flushing = TRUE;
903
904       ret = gst_pad_event_default (pad, event);
905       break;
906     }
907     case GST_EVENT_FLUSH_STOP:
908     {
909       self->flushing = FALSE;
910
911       ret = gst_pad_event_default (pad, event);
912       break;
913     }
914     default:
915       ret = gst_pad_event_default (pad, event);
916       break;
917   }
918
919   gst_object_unref (self);
920
921   return ret;
922 }
923
924
925 static GstStateChangeReturn
926 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
927 {
928   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
929   GstSubParse *self = GST_SUBPARSE (element);
930
931   switch (transition) {
932     case GST_STATE_CHANGE_READY_TO_PAUSED:
933       /* format detection will init the parser state */
934       self->offset = self->next_offset = 0;
935       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
936       self->valid_utf8 = TRUE;
937       break;
938     default:
939       break;
940   }
941
942   ret = parent_class->change_state (element, transition);
943   if (ret == GST_STATE_CHANGE_FAILURE)
944     return ret;
945
946   switch (transition) {
947     case GST_STATE_CHANGE_PAUSED_TO_READY:
948       parser_state_dispose (&self->state);
949       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
950       break;
951     default:
952       break;
953   }
954
955   return ret;
956 }
957
958 /*
959  * Typefind support.
960  */
961
962 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
963 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
964
965 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
966 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
967
968 static void
969 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
970 {
971   GstSubParseFormat format;
972   const guint8 *data;
973   GstCaps *caps;
974   gchar *str;
975
976   if (!(data = gst_type_find_peek (tf, 0, 36)))
977     return;
978
979   /* make sure string passed to _autodetect() is NUL-terminated */
980   str = g_strndup ((gchar *) data, 35);
981   format = gst_sub_parse_data_format_autodetect (str);
982   g_free (str);
983
984   switch (format) {
985     case GST_SUB_PARSE_FORMAT_MDVDSUB:
986       GST_DEBUG ("MicroDVD format detected");
987       caps = SUB_CAPS;
988       break;
989     case GST_SUB_PARSE_FORMAT_SUBRIP:
990       GST_DEBUG ("SubRip format detected");
991       caps = SUB_CAPS;
992       break;
993     case GST_SUB_PARSE_FORMAT_MPSUB:
994       GST_DEBUG ("MPSub format detected");
995       caps = SUB_CAPS;
996       break;
997     case GST_SUB_PARSE_FORMAT_SAMI:
998       GST_DEBUG ("SAMI (time-based) format detected");
999       caps = SAMI_CAPS;
1000       break;
1001     default:
1002     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1003       GST_DEBUG ("no subtitle format detected");
1004       return;
1005   }
1006
1007   /* if we're here, it's ok */
1008   gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1009 }
1010
1011 static gboolean
1012 plugin_init (GstPlugin * plugin)
1013 {
1014   static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", NULL };
1015
1016   GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1017
1018   if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1019           gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1020     return FALSE;
1021
1022   if (!gst_element_register (plugin, "subparse",
1023           GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1024       !gst_element_register (plugin, "ssaparse",
1025           GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1026     return FALSE;
1027   }
1028
1029   return TRUE;
1030 }
1031
1032 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1033     GST_VERSION_MINOR,
1034     "subparse",
1035     "Subtitle parsing",
1036     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)