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>
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.
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.
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.
28 #include <sys/types.h>
31 #include "gstsubparse.h"
32 #include "gstssaparse.h"
33 #include "samiparse.h"
34 #include "tmplayerparse.h"
35 #include "mpl2parse.h"
37 GST_DEBUG_CATEGORY (sub_parse_debug);
39 #define DEFAULT_ENCODING NULL
48 gst_sub_parse_set_property (GObject * object, guint prop_id,
49 const GValue * value, GParamSpec * pspec);
51 gst_sub_parse_get_property (GObject * object, guint prop_id,
52 GValue * value, GParamSpec * pspec);
55 static const GstElementDetails sub_parse_details =
56 GST_ELEMENT_DETAILS ("Subtitle parser",
57 "Codec/Parser/Subtitle",
58 "Parses subtitle (.sub) files into text streams",
59 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
60 "Ronald S. Bultje <rbultje@ronald.bitfreak.net>");
62 #ifndef GST_DISABLE_XML
63 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
66 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
67 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2")
70 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
73 GST_STATIC_CAPS ("application/x-subtitle")
77 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
80 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
83 static void gst_sub_parse_base_init (GstSubParseClass * klass);
84 static void gst_sub_parse_class_init (GstSubParseClass * klass);
85 static void gst_sub_parse_init (GstSubParse * subparse);
87 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
88 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
90 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
91 GstStateChange transition);
93 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
95 static GstElementClass *parent_class = NULL;
98 gst_sub_parse_get_type (void)
100 static GType sub_parse_type = 0;
102 if (!sub_parse_type) {
103 static const GTypeInfo sub_parse_info = {
104 sizeof (GstSubParseClass),
105 (GBaseInitFunc) gst_sub_parse_base_init,
107 (GClassInitFunc) gst_sub_parse_class_init,
110 sizeof (GstSubParse),
112 (GInstanceInitFunc) gst_sub_parse_init,
115 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
116 "GstSubParse", &sub_parse_info, 0);
119 return sub_parse_type;
123 gst_sub_parse_base_init (GstSubParseClass * klass)
125 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
127 gst_element_class_add_pad_template (element_class,
128 gst_static_pad_template_get (&sink_templ));
129 gst_element_class_add_pad_template (element_class,
130 gst_static_pad_template_get (&src_templ));
131 gst_element_class_set_details (element_class, &sub_parse_details);
135 gst_sub_parse_dispose (GObject * object)
137 GstSubParse *subparse = GST_SUBPARSE (object);
139 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
141 if (subparse->encoding) {
142 g_free (subparse->encoding);
143 subparse->encoding = NULL;
145 if (subparse->textbuf) {
146 g_string_free (subparse->textbuf, TRUE);
147 subparse->textbuf = NULL;
149 sami_context_deinit (&subparse->state);
151 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
155 gst_sub_parse_class_init (GstSubParseClass * klass)
157 GObjectClass *object_class = G_OBJECT_CLASS (klass);
158 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
160 parent_class = g_type_class_peek_parent (klass);
162 object_class->dispose = gst_sub_parse_dispose;
163 object_class->set_property = gst_sub_parse_set_property;
164 object_class->get_property = gst_sub_parse_get_property;
166 element_class->change_state = gst_sub_parse_change_state;
168 g_object_class_install_property (object_class, PROP_ENCODING,
169 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
170 "Encoding to assume if input subtitles are not in UTF-8 encoding. "
171 "If not set, the GST_SUBTITLE_ENCODING environment variable will "
172 "be checked for an encoding to use. If that is not set either, "
173 "ISO-8859-15 will be assumed.", DEFAULT_ENCODING, G_PARAM_READWRITE));
177 gst_sub_parse_init (GstSubParse * subparse)
179 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
180 gst_pad_set_chain_function (subparse->sinkpad,
181 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
182 gst_pad_set_event_function (subparse->sinkpad,
183 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
184 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
186 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
187 gst_pad_set_event_function (subparse->srcpad,
188 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
189 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
191 subparse->textbuf = g_string_new (NULL);
192 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
193 subparse->flushing = FALSE;
194 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
195 subparse->need_segment = TRUE;
196 subparse->encoding = g_strdup (DEFAULT_ENCODING);
200 * Source pad functions.
204 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
206 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
207 gboolean ret = FALSE;
209 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
211 switch (GST_EVENT_TYPE (event)) {
215 GstSeekType start_type, stop_type;
220 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
221 &start_type, &start, &stop_type, &stop);
223 if (format != GST_FORMAT_TIME) {
224 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
225 gst_event_unref (event);
229 /* Convert that seek to a seeking in bytes at position 0,
230 FIXME: could use an index */
231 ret = gst_pad_push_event (self->sinkpad,
232 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
233 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
236 /* Apply the seek to our segment */
237 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
238 start_type, start, stop_type, stop, &update);
240 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
243 self->next_offset = 0;
245 self->need_segment = TRUE;
247 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
250 gst_event_unref (event);
254 ret = gst_pad_event_default (pad, event);
259 gst_object_unref (self);
265 gst_sub_parse_set_property (GObject * object, guint prop_id,
266 const GValue * value, GParamSpec * pspec)
268 GstSubParse *subparse = GST_SUBPARSE (object);
270 GST_OBJECT_LOCK (subparse);
273 g_free (subparse->encoding);
274 subparse->encoding = g_value_dup_string (value);
275 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
276 GST_STR_NULL (subparse->encoding));
279 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
282 GST_OBJECT_UNLOCK (subparse);
286 gst_sub_parse_get_property (GObject * object, guint prop_id,
287 GValue * value, GParamSpec * pspec)
289 GstSubParse *subparse = GST_SUBPARSE (object);
291 GST_OBJECT_LOCK (subparse);
294 g_value_set_string (value, subparse->encoding);
297 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
300 GST_OBJECT_UNLOCK (subparse);
304 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
306 const gchar *encoding;
310 if (self->valid_utf8) {
311 if (g_utf8_validate (str, len, NULL)) {
312 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
313 return g_strndup (str, len);
315 GST_INFO_OBJECT (self, "invalid UTF-8!");
316 self->valid_utf8 = FALSE;
319 encoding = self->encoding;
320 if (encoding == NULL || *encoding == '\0') {
321 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
323 if (encoding == NULL || *encoding == '\0') {
324 /* if local encoding is UTF-8 and no encoding specified
325 * via the environment variable, assume ISO-8859-15 */
326 if (g_get_charset (&encoding)) {
327 encoding = "ISO-8859-15";
331 ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
335 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
336 encoding, err->message);
339 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
340 ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
344 GST_LOG_OBJECT (self,
345 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
346 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
352 get_next_line (GstSubParse * self)
355 const char *line_end;
357 gboolean have_r = FALSE;
359 line_end = strchr (self->textbuf->str, '\n');
362 /* end-of-line not found; return for more data */
366 /* get rid of '\r' */
367 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
372 line_len = line_end - self->textbuf->str;
373 line = convert_encoding (self, self->textbuf->str, line_len);
374 self->textbuf = g_string_erase (self->textbuf, 0,
375 line_len + (have_r ? 2 : 1));
380 parse_mdvdsub (ParserState * state, const gchar * line)
382 const gchar *line_split;
384 guint start_frame, end_frame;
385 gint64 clip_start = 0, clip_stop = 0;
386 gboolean in_seg = FALSE;
390 /* style variables */
395 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
396 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
397 " format, failed:\n%s", line);
401 /* skip the {%u}{%u} part */
402 line = strchr (line, '}') + 1;
403 line = strchr (line, '}') + 1;
405 /* see if there's a first line with a framerate */
406 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
407 gchar *rest, *end = NULL;
409 rest = g_strdup (line);
410 g_strdelimit (rest, ",", '.');
411 state->fps = g_ascii_strtod (rest, &end);
414 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
419 if (state->fps == 0.0) {
420 /* FIXME: hardcoded for now, is there a better way/assumption? */
421 state->fps = 24000.0 / 1001.0;
422 GST_INFO ("no framerate specified, assuming %f", state->fps);
425 state->start_time = start_frame / state->fps * GST_SECOND;
426 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
428 /* Check our segment start/stop */
429 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
430 state->start_time, state->start_time + state->duration, &clip_start,
433 /* No need to parse that text if it's out of segment */
435 state->start_time = clip_start;
436 state->duration = clip_stop - clip_start;
441 markup = g_string_new (NULL);
446 /* parse style markup */
447 if (strncmp (line, "{y:i}", 5) == 0) {
449 line = strchr (line, '}') + 1;
451 if (strncmp (line, "{y:b}", 5) == 0) {
453 line = strchr (line, '}') + 1;
455 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
456 line = strchr (line, '}') + 1;
458 if ((line_split = strchr (line, '|')))
459 line_chunk = g_markup_escape_text (line, line_split - line);
461 line_chunk = g_markup_escape_text (line, strlen (line));
462 markup = g_string_append (markup, "<span");
464 g_string_append (markup, " style=\"italic\"");
466 g_string_append (markup, " weight=\"bold\"");
468 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
469 g_string_append_printf (markup, ">%s</span>", line_chunk);
472 g_string_append (markup, "\n");
473 line = line_split + 1;
479 g_string_free (markup, FALSE);
480 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
481 state->start_time / (double) GST_SECOND,
482 state->duration / (double) GST_SECOND, ret);
487 strip_trailing_newlines (gchar * txt)
493 while (len > 1 && txt[len - 1] == '\n') {
500 /* we want to escape text in general, but retain basic markup like
501 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
502 * just unescape a white list of allowed markups again after
503 * escaping everything (the text between these simple markers isn't
504 * necessarily escaped, so it seems best to do it like this) */
506 subrip_unescape_formatting (gchar * txt)
510 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
511 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
512 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
513 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
515 pos[1] = g_ascii_tolower (pos[4]);
517 /* move NUL terminator as well */
518 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
523 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
524 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
525 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
526 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
529 pos[2] = g_ascii_tolower (pos[5]);
531 /* move NUL terminator as well */
532 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
540 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
544 tag = start + strlen ("<");
548 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
553 GST_LOG ("removing unhandled tag '%s'", start);
555 g_memmove (start, stop, strlen (stop) + 1);
559 /* remove tags we haven't explicitly allowed earlier on, like font tags
562 subrip_remove_unhandled_tags (gchar * txt)
566 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
567 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
568 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
574 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
575 * assumes the input has been escaped and subrip_unescape_formatting() has then
576 * been run over the input! This function adds missing closing markup tags and
577 * removes broken closing tags for tags that have never been opened. */
579 subrip_fix_up_markup (gchar ** p_txt)
581 gchar *cur, *next_tag;
583 guint num_open_tags = 0;
585 g_assert (*p_txt != NULL);
588 while (*cur != '\0') {
589 next_tag = strchr (cur, '<');
590 if (next_tag == NULL)
596 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
597 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
598 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
601 /* it's all good, closing tag which is open */
609 if (num_open_tags == G_N_ELEMENTS (open_tags))
610 return; /* something dodgy is going on, stop parsing */
611 open_tags[num_open_tags] = *next_tag;
615 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
616 g_assert_not_reached ();
622 if (num_open_tags > 0) {
625 s = g_string_new (*p_txt);
626 while (num_open_tags > 0) {
627 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
628 g_string_append_c (s, '<');
629 g_string_append_c (s, '/');
630 g_string_append_c (s, open_tags[num_open_tags - 1]);
631 g_string_append_c (s, '>');
635 *p_txt = g_string_free (s, FALSE);
640 parse_subrip (ParserState * state, const gchar * line)
642 guint h1, m1, s1, ms1;
643 guint h2, m2, s2, ms2;
647 switch (state->state) {
649 /* looking for a single integer */
650 if (sscanf (line, "%u", &subnum) == 1)
654 /* looking for start_time --> end_time */
655 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
656 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
659 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
662 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
663 ms2 * GST_MSECOND - state->start_time;
665 GST_DEBUG ("error parsing subrip time line");
671 /* No need to parse that text if it's out of segment */
672 gint64 clip_start = 0, clip_stop = 0;
673 gboolean in_seg = FALSE;
675 /* Check our segment start/stop */
676 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
677 state->start_time, state->start_time + state->duration,
678 &clip_start, &clip_stop);
681 state->start_time = clip_start;
682 state->duration = clip_stop - clip_start;
688 /* looking for subtitle text; empty line ends this subtitle entry */
690 g_string_append_c (state->buf, '\n');
691 g_string_append (state->buf, line);
692 if (strlen (line) == 0) {
693 ret = g_markup_escape_text (state->buf->str, state->buf->len);
694 g_string_truncate (state->buf, 0);
696 subrip_unescape_formatting (ret);
697 subrip_remove_unhandled_tags (ret);
698 strip_trailing_newlines (ret);
699 subrip_fix_up_markup (&ret);
704 g_return_val_if_reached (NULL);
709 subviewer_unescape_newlines (gchar * read)
713 /* Replace all occurences of '[br]' with a newline as version 2
714 * of the subviewer format uses this for newlines */
716 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
720 if (strncmp (read, "[br]", 4) == 0) {
734 parse_subviewer (ParserState * state, const gchar * line)
736 guint h1, m1, s1, ms1;
737 guint h2, m2, s2, ms2;
740 /* TODO: Maybe also parse the fields in the header, especially DELAY.
741 * For examples see the unit test or
742 * http://www.doom9.org/index.html?/sub.htm */
744 switch (state->state) {
746 /* looking for start_time,end_time */
747 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
748 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
751 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
754 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
755 ms2 * GST_MSECOND - state->start_time;
760 /* No need to parse that text if it's out of segment */
761 gint64 clip_start = 0, clip_stop = 0;
762 gboolean in_seg = FALSE;
764 /* Check our segment start/stop */
765 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
766 state->start_time, state->start_time + state->duration,
767 &clip_start, &clip_stop);
770 state->start_time = clip_start;
771 state->duration = clip_stop - clip_start;
777 /* looking for subtitle text; empty line ends this subtitle entry */
779 g_string_append_c (state->buf, '\n');
780 g_string_append (state->buf, line);
781 if (strlen (line) == 0) {
782 ret = g_strdup (state->buf->str);
783 subviewer_unescape_newlines (ret);
784 strip_trailing_newlines (ret);
785 g_string_truncate (state->buf, 0);
791 g_assert_not_reached ();
797 parse_mpsub (ParserState * state, const gchar * line)
802 switch (state->state) {
804 /* looking for two floats (offset, duration) */
805 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
807 state->start_time += state->duration + GST_SECOND * t1;
808 state->duration = GST_SECOND * t2;
812 { /* No need to parse that text if it's out of segment */
813 gint64 clip_start = 0, clip_stop = 0;
814 gboolean in_seg = FALSE;
816 /* Check our segment start/stop */
817 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
818 state->start_time, state->start_time + state->duration,
819 &clip_start, &clip_stop);
822 state->start_time = clip_start;
823 state->duration = clip_stop - clip_start;
829 /* looking for subtitle text; empty line ends this
832 g_string_append_c (state->buf, '\n');
833 g_string_append (state->buf, line);
834 if (strlen (line) == 0) {
835 ret = g_strdup (state->buf->str);
836 g_string_truncate (state->buf, 0);
842 g_assert_not_reached ();
848 parser_state_init (ParserState * state)
850 GST_DEBUG ("initialising parser");
853 g_string_truncate (state->buf, 0);
855 state->buf = g_string_new (NULL);
858 state->start_time = 0;
861 state->segment = NULL;
865 parser_state_dispose (ParserState * state)
868 g_string_free (state->buf, TRUE);
871 if (state->user_data) {
872 sami_context_reset (state);
877 * FIXME: maybe we should pass along a second argument, the preceding
878 * text buffer, because that is how this originally worked, even though
879 * I don't really see the use of that.
882 static GstSubParseFormat
883 gst_sub_parse_data_format_autodetect (gchar * match_str)
885 static gboolean need_init_regexps = TRUE;
886 static regex_t mdvd_rx;
887 static regex_t subrip_rx;
890 /* initialize the regexps used the first time around */
891 if (need_init_regexps) {
895 need_init_regexps = FALSE;
896 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
897 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
898 (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
899 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
900 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
901 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
902 regerror (err, &subrip_rx, errstr, 127);
903 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
907 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
908 GST_LOG ("MicroDVD (frame based) format detected");
909 return GST_SUB_PARSE_FORMAT_MDVDSUB;
911 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
912 GST_LOG ("SubRip (time based) format detected");
913 return GST_SUB_PARSE_FORMAT_SUBRIP;
916 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
917 GST_LOG ("MPSub (time based) format detected");
918 return GST_SUB_PARSE_FORMAT_MPSUB;
920 if (strstr (match_str, "<SAMI>") != NULL ||
921 strstr (match_str, "<sami>") != NULL) {
922 GST_LOG ("SAMI (time based) format detected");
923 return GST_SUB_PARSE_FORMAT_SAMI;
925 /* we're boldly assuming the first subtitle appears within the first hour */
926 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
927 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
928 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
929 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
930 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
931 GST_LOG ("TMPlayer (time based) format detected");
932 return GST_SUB_PARSE_FORMAT_TMPLAYER;
934 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
935 GST_LOG ("MPL2 (time based) format detected");
936 return GST_SUB_PARSE_FORMAT_MPL2;
938 if (strstr (match_str, "[INFORMATION]") != NULL) {
939 GST_LOG ("SubViewer (time based) format detected");
940 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
943 GST_DEBUG ("no subtitle format detected");
944 return GST_SUB_PARSE_FORMAT_UNKNOWN;
948 gst_sub_parse_format_autodetect (GstSubParse * self)
951 GstSubParseFormat format;
953 if (strlen (self->textbuf->str) < 35) {
954 GST_DEBUG ("File too small to be a subtitles file");
958 data = g_strndup (self->textbuf->str, 35);
959 format = gst_sub_parse_data_format_autodetect (data);
962 self->parser_type = format;
963 parser_state_init (&self->state);
966 case GST_SUB_PARSE_FORMAT_MDVDSUB:
967 self->parse_line = parse_mdvdsub;
968 return gst_caps_new_simple ("text/x-pango-markup", NULL);
969 case GST_SUB_PARSE_FORMAT_SUBRIP:
970 self->parse_line = parse_subrip;
971 return gst_caps_new_simple ("text/x-pango-markup", NULL);
972 case GST_SUB_PARSE_FORMAT_MPSUB:
973 self->parse_line = parse_mpsub;
974 return gst_caps_new_simple ("text/plain", NULL);
975 case GST_SUB_PARSE_FORMAT_SAMI:
976 self->parse_line = parse_sami;
977 sami_context_init (&self->state);
978 return gst_caps_new_simple ("text/x-pango-markup", NULL);
979 case GST_SUB_PARSE_FORMAT_TMPLAYER:
980 self->parse_line = parse_tmplayer;
981 return gst_caps_new_simple ("text/plain", NULL);
982 case GST_SUB_PARSE_FORMAT_MPL2:
983 self->parse_line = parse_mpl2;
984 return gst_caps_new_simple ("text/x-pango-markup", NULL);
985 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
986 self->parse_line = parse_subviewer;
987 return gst_caps_new_simple ("text/plain", NULL);
988 case GST_SUB_PARSE_FORMAT_UNKNOWN:
990 GST_DEBUG ("no subtitle format detected");
991 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
992 ("The input is not a valid/supported subtitle file"), (NULL));
998 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1000 if (GST_BUFFER_OFFSET (buf) != self->offset) {
1001 /* flush the parser state */
1002 parser_state_init (&self->state);
1003 g_string_truncate (self->textbuf, 0);
1004 sami_context_reset (&self->state);
1007 self->textbuf = g_string_append_len (self->textbuf,
1008 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1009 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1010 self->next_offset = self->offset;
1012 gst_buffer_unref (buf);
1015 static GstFlowReturn
1016 handle_buffer (GstSubParse * self, GstBuffer * buf)
1018 GstFlowReturn ret = GST_FLOW_OK;
1019 GstCaps *caps = NULL;
1020 gchar *line, *subtitle;
1022 feed_textbuf (self, buf);
1024 /* make sure we know the format */
1025 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1026 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1027 return GST_FLOW_UNEXPECTED;
1029 if (!gst_pad_set_caps (self->srcpad, caps)) {
1030 gst_caps_unref (caps);
1031 return GST_FLOW_UNEXPECTED;
1033 gst_caps_unref (caps);
1036 while ((line = get_next_line (self)) && !self->flushing) {
1037 /* Set segment on our parser state machine */
1038 self->state.segment = &self->segment;
1039 /* Now parse the line, out of segment lines will just return NULL */
1040 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
1041 subtitle = self->parse_line (&self->state, line);
1045 guint subtitle_len = strlen (subtitle);
1047 /* +1 for terminating NUL character */
1048 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1049 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1050 GST_PAD_CAPS (self->srcpad), &buf);
1052 if (ret == GST_FLOW_OK) {
1053 /* copy terminating NUL character as well */
1054 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1055 GST_BUFFER_SIZE (buf) = subtitle_len;
1056 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1057 GST_BUFFER_DURATION (buf) = self->state.duration;
1059 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1060 self->state.start_time);
1062 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1063 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1064 GST_TIME_ARGS (self->state.duration));
1066 ret = gst_pad_push (self->srcpad, buf);
1072 if (ret != GST_FLOW_OK) {
1073 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1082 static GstFlowReturn
1083 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1088 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1090 /* Push newsegment if needed */
1091 if (self->need_segment) {
1092 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1095 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1096 self->segment.rate, self->segment.format,
1097 self->segment.last_stop, self->segment.stop, self->segment.time));
1098 self->need_segment = FALSE;
1101 ret = handle_buffer (self, buf);
1107 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1109 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1110 gboolean ret = FALSE;
1112 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1114 switch (GST_EVENT_TYPE (event)) {
1115 case GST_EVENT_EOS:{
1116 /* Make sure the last subrip chunk is pushed out even
1117 * if the file does not have an empty line at the end */
1118 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1119 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1120 GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
1122 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1123 GST_BUFFER_DATA (buf)[0] = '\n';
1124 GST_BUFFER_DATA (buf)[1] = '\0'; /* play it safe */
1125 GST_BUFFER_SIZE (buf) = 1;
1126 GST_BUFFER_OFFSET (buf) = self->offset;
1127 gst_sub_parse_chain (pad, buf);
1129 ret = gst_pad_event_default (pad, event);
1132 case GST_EVENT_NEWSEGMENT:
1136 gint64 start, stop, time;
1139 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1142 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1144 if (format == GST_FORMAT_TIME) {
1145 gst_segment_set_newsegment (&self->segment, update, rate, format,
1148 /* if not time format, we'll either start with a 0 timestamp anyway or
1149 * it's following a seek in which case we'll have saved the requested
1150 * seek segment and don't want to overwrite it (remember that on a seek
1151 * we always just seek back to the start in BYTES format and just throw
1152 * away all text that's before the requested position; if the subtitles
1153 * come from an upstream demuxer, it won't be able to handle our BYTES
1154 * seek request and instead send us a newsegment from the seek request
1155 * it received via its video pads instead, so all is fine then too) */
1159 gst_event_unref (event);
1162 case GST_EVENT_FLUSH_START:
1164 self->flushing = TRUE;
1166 ret = gst_pad_event_default (pad, event);
1169 case GST_EVENT_FLUSH_STOP:
1171 self->flushing = FALSE;
1173 ret = gst_pad_event_default (pad, event);
1177 ret = gst_pad_event_default (pad, event);
1181 gst_object_unref (self);
1187 static GstStateChangeReturn
1188 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1190 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1191 GstSubParse *self = GST_SUBPARSE (element);
1193 switch (transition) {
1194 case GST_STATE_CHANGE_READY_TO_PAUSED:
1195 /* format detection will init the parser state */
1197 self->next_offset = 0;
1198 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1199 self->valid_utf8 = TRUE;
1200 g_string_truncate (self->textbuf, 0);
1206 ret = parent_class->change_state (element, transition);
1207 if (ret == GST_STATE_CHANGE_FAILURE)
1210 switch (transition) {
1211 case GST_STATE_CHANGE_PAUSED_TO_READY:
1212 parser_state_dispose (&self->state);
1213 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1226 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1227 * also, give different subtitle formats really different types */
1228 static GstStaticCaps mpl2_caps =
1229 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1230 static GstStaticCaps tmp_caps =
1231 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1232 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1233 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1235 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1236 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1237 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1238 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1241 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1243 GstSubParseFormat format;
1248 if (!(data = gst_type_find_peek (tf, 0, 36)))
1251 /* make sure string passed to _autodetect() is NUL-terminated */
1252 str = g_strndup ((gchar *) data, 35);
1253 format = gst_sub_parse_data_format_autodetect (str);
1257 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1258 GST_DEBUG ("MicroDVD format detected");
1261 case GST_SUB_PARSE_FORMAT_SUBRIP:
1262 GST_DEBUG ("SubRip format detected");
1265 case GST_SUB_PARSE_FORMAT_MPSUB:
1266 GST_DEBUG ("MPSub format detected");
1269 case GST_SUB_PARSE_FORMAT_SAMI:
1270 GST_DEBUG ("SAMI (time-based) format detected");
1273 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1274 GST_DEBUG ("TMPlayer (time based) format detected");
1277 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1278 * returning a high probability (however, since we registered our
1279 * typefinder here with a rank of MARGINAL we should pretty much only
1280 * be called if most other typefinders have already run */
1281 case GST_SUB_PARSE_FORMAT_MPL2:
1282 GST_DEBUG ("MPL2 (time based) format detected");
1285 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1286 GST_DEBUG ("SubViewer format detected");
1290 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1291 GST_DEBUG ("no subtitle format detected");
1295 /* if we're here, it's ok */
1296 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1300 plugin_init (GstPlugin * plugin)
1302 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1306 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1308 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1309 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1312 if (!gst_element_register (plugin, "subparse",
1313 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1314 !gst_element_register (plugin, "ssaparse",
1315 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1322 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1326 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)