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,
174 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
178 gst_sub_parse_init (GstSubParse * subparse)
180 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
181 gst_pad_set_chain_function (subparse->sinkpad,
182 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
183 gst_pad_set_event_function (subparse->sinkpad,
184 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
185 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
187 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
188 gst_pad_set_event_function (subparse->srcpad,
189 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
190 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
192 subparse->textbuf = g_string_new (NULL);
193 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
194 subparse->flushing = FALSE;
195 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
196 subparse->need_segment = TRUE;
197 subparse->encoding = g_strdup (DEFAULT_ENCODING);
201 * Source pad functions.
205 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
207 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
208 gboolean ret = FALSE;
210 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
212 switch (GST_EVENT_TYPE (event)) {
216 GstSeekType start_type, stop_type;
221 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
222 &start_type, &start, &stop_type, &stop);
224 if (format != GST_FORMAT_TIME) {
225 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
226 gst_event_unref (event);
230 /* Convert that seek to a seeking in bytes at position 0,
231 FIXME: could use an index */
232 ret = gst_pad_push_event (self->sinkpad,
233 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
234 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
237 /* Apply the seek to our segment */
238 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
239 start_type, start, stop_type, stop, &update);
241 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
244 self->next_offset = 0;
246 self->need_segment = TRUE;
248 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
251 gst_event_unref (event);
255 ret = gst_pad_event_default (pad, event);
260 gst_object_unref (self);
266 gst_sub_parse_set_property (GObject * object, guint prop_id,
267 const GValue * value, GParamSpec * pspec)
269 GstSubParse *subparse = GST_SUBPARSE (object);
271 GST_OBJECT_LOCK (subparse);
274 g_free (subparse->encoding);
275 subparse->encoding = g_value_dup_string (value);
276 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
277 GST_STR_NULL (subparse->encoding));
280 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
283 GST_OBJECT_UNLOCK (subparse);
287 gst_sub_parse_get_property (GObject * object, guint prop_id,
288 GValue * value, GParamSpec * pspec)
290 GstSubParse *subparse = GST_SUBPARSE (object);
292 GST_OBJECT_LOCK (subparse);
295 g_value_set_string (value, subparse->encoding);
298 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
301 GST_OBJECT_UNLOCK (subparse);
305 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
307 const gchar *encoding;
311 if (self->valid_utf8) {
312 if (g_utf8_validate (str, len, NULL)) {
313 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
314 return g_strndup (str, len);
316 GST_INFO_OBJECT (self, "invalid UTF-8!");
317 self->valid_utf8 = FALSE;
320 encoding = self->encoding;
321 if (encoding == NULL || *encoding == '\0') {
322 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
324 if (encoding == NULL || *encoding == '\0') {
325 /* if local encoding is UTF-8 and no encoding specified
326 * via the environment variable, assume ISO-8859-15 */
327 if (g_get_charset (&encoding)) {
328 encoding = "ISO-8859-15";
332 ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
336 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
337 encoding, err->message);
340 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
341 ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
345 GST_LOG_OBJECT (self,
346 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
347 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
353 get_next_line (GstSubParse * self)
356 const char *line_end;
358 gboolean have_r = FALSE;
360 line_end = strchr (self->textbuf->str, '\n');
363 /* end-of-line not found; return for more data */
367 /* get rid of '\r' */
368 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
373 line_len = line_end - self->textbuf->str;
374 line = convert_encoding (self, self->textbuf->str, line_len);
375 self->textbuf = g_string_erase (self->textbuf, 0,
376 line_len + (have_r ? 2 : 1));
381 parse_mdvdsub (ParserState * state, const gchar * line)
383 const gchar *line_split;
385 guint start_frame, end_frame;
386 gint64 clip_start = 0, clip_stop = 0;
387 gboolean in_seg = FALSE;
391 /* style variables */
396 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
397 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
398 " format, failed:\n%s", line);
402 /* skip the {%u}{%u} part */
403 line = strchr (line, '}') + 1;
404 line = strchr (line, '}') + 1;
406 /* see if there's a first line with a framerate */
407 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
408 gchar *rest, *end = NULL;
410 rest = g_strdup (line);
411 g_strdelimit (rest, ",", '.');
412 state->fps = g_ascii_strtod (rest, &end);
415 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
420 if (state->fps == 0.0) {
421 /* FIXME: hardcoded for now, is there a better way/assumption? */
422 state->fps = 24000.0 / 1001.0;
423 GST_INFO ("no framerate specified, assuming %f", state->fps);
426 state->start_time = start_frame / state->fps * GST_SECOND;
427 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
429 /* Check our segment start/stop */
430 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
431 state->start_time, state->start_time + state->duration, &clip_start,
434 /* No need to parse that text if it's out of segment */
436 state->start_time = clip_start;
437 state->duration = clip_stop - clip_start;
442 markup = g_string_new (NULL);
447 /* parse style markup */
448 if (strncmp (line, "{y:i}", 5) == 0) {
450 line = strchr (line, '}') + 1;
452 if (strncmp (line, "{y:b}", 5) == 0) {
454 line = strchr (line, '}') + 1;
456 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
457 line = strchr (line, '}') + 1;
459 /* forward slashes at beginning/end signify italics too */
460 if (g_str_has_prefix (line, "/")) {
464 if ((line_split = strchr (line, '|')))
465 line_chunk = g_markup_escape_text (line, line_split - line);
467 line_chunk = g_markup_escape_text (line, strlen (line));
469 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
470 * always at the end of a line or can they span multiple lines?) */
471 if (g_str_has_suffix (line_chunk, "/")) {
472 line_chunk[strlen (line_chunk) - 1] = '\0';
475 markup = g_string_append (markup, "<span");
477 g_string_append (markup, " style=\"italic\"");
479 g_string_append (markup, " weight=\"bold\"");
481 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
482 g_string_append_printf (markup, ">%s</span>", line_chunk);
485 g_string_append (markup, "\n");
486 line = line_split + 1;
492 g_string_free (markup, FALSE);
493 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
494 state->start_time / (double) GST_SECOND,
495 state->duration / (double) GST_SECOND, ret);
500 strip_trailing_newlines (gchar * txt)
506 while (len > 1 && txt[len - 1] == '\n') {
513 /* we want to escape text in general, but retain basic markup like
514 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
515 * just unescape a white list of allowed markups again after
516 * escaping everything (the text between these simple markers isn't
517 * necessarily escaped, so it seems best to do it like this) */
519 subrip_unescape_formatting (gchar * txt)
523 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
524 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
525 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
526 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
528 pos[1] = g_ascii_tolower (pos[4]);
530 /* move NUL terminator as well */
531 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
536 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
537 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
538 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
539 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
542 pos[2] = g_ascii_tolower (pos[5]);
544 /* move NUL terminator as well */
545 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
553 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
557 tag = start + strlen ("<");
561 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
566 GST_LOG ("removing unhandled tag '%s'", start);
568 g_memmove (start, stop, strlen (stop) + 1);
572 /* remove tags we haven't explicitly allowed earlier on, like font tags
575 subrip_remove_unhandled_tags (gchar * txt)
579 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
580 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
581 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
587 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
588 * assumes the input has been escaped and subrip_unescape_formatting() has then
589 * been run over the input! This function adds missing closing markup tags and
590 * removes broken closing tags for tags that have never been opened. */
592 subrip_fix_up_markup (gchar ** p_txt)
594 gchar *cur, *next_tag;
596 guint num_open_tags = 0;
598 g_assert (*p_txt != NULL);
601 while (*cur != '\0') {
602 next_tag = strchr (cur, '<');
603 if (next_tag == NULL)
609 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
610 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
611 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
614 /* it's all good, closing tag which is open */
622 if (num_open_tags == G_N_ELEMENTS (open_tags))
623 return; /* something dodgy is going on, stop parsing */
624 open_tags[num_open_tags] = *next_tag;
628 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
629 g_assert_not_reached ();
635 if (num_open_tags > 0) {
638 s = g_string_new (*p_txt);
639 while (num_open_tags > 0) {
640 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
641 g_string_append_c (s, '<');
642 g_string_append_c (s, '/');
643 g_string_append_c (s, open_tags[num_open_tags - 1]);
644 g_string_append_c (s, '>');
648 *p_txt = g_string_free (s, FALSE);
653 parse_subrip (ParserState * state, const gchar * line)
655 guint h1, m1, s1, ms1;
656 guint h2, m2, s2, ms2;
660 switch (state->state) {
662 /* looking for a single integer */
663 if (sscanf (line, "%u", &subnum) == 1)
667 /* looking for start_time --> end_time */
668 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
669 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
672 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
675 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
676 ms2 * GST_MSECOND - state->start_time;
678 GST_DEBUG ("error parsing subrip time line");
684 /* No need to parse that text if it's out of segment */
685 gint64 clip_start = 0, clip_stop = 0;
686 gboolean in_seg = FALSE;
688 /* Check our segment start/stop */
689 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
690 state->start_time, state->start_time + state->duration,
691 &clip_start, &clip_stop);
694 state->start_time = clip_start;
695 state->duration = clip_stop - clip_start;
701 /* looking for subtitle text; empty line ends this subtitle entry */
703 g_string_append_c (state->buf, '\n');
704 g_string_append (state->buf, line);
705 if (strlen (line) == 0) {
706 ret = g_markup_escape_text (state->buf->str, state->buf->len);
707 g_string_truncate (state->buf, 0);
709 subrip_unescape_formatting (ret);
710 subrip_remove_unhandled_tags (ret);
711 strip_trailing_newlines (ret);
712 subrip_fix_up_markup (&ret);
717 g_return_val_if_reached (NULL);
722 subviewer_unescape_newlines (gchar * read)
726 /* Replace all occurences of '[br]' with a newline as version 2
727 * of the subviewer format uses this for newlines */
729 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
733 if (strncmp (read, "[br]", 4) == 0) {
747 parse_subviewer (ParserState * state, const gchar * line)
749 guint h1, m1, s1, ms1;
750 guint h2, m2, s2, ms2;
753 /* TODO: Maybe also parse the fields in the header, especially DELAY.
754 * For examples see the unit test or
755 * http://www.doom9.org/index.html?/sub.htm */
757 switch (state->state) {
759 /* looking for start_time,end_time */
760 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
761 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
764 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
767 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
768 ms2 * GST_MSECOND - state->start_time;
773 /* No need to parse that text if it's out of segment */
774 gint64 clip_start = 0, clip_stop = 0;
775 gboolean in_seg = FALSE;
777 /* Check our segment start/stop */
778 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
779 state->start_time, state->start_time + state->duration,
780 &clip_start, &clip_stop);
783 state->start_time = clip_start;
784 state->duration = clip_stop - clip_start;
790 /* looking for subtitle text; empty line ends this subtitle entry */
792 g_string_append_c (state->buf, '\n');
793 g_string_append (state->buf, line);
794 if (strlen (line) == 0) {
795 ret = g_strdup (state->buf->str);
796 subviewer_unescape_newlines (ret);
797 strip_trailing_newlines (ret);
798 g_string_truncate (state->buf, 0);
804 g_assert_not_reached ();
810 parse_mpsub (ParserState * state, const gchar * line)
815 switch (state->state) {
817 /* looking for two floats (offset, duration) */
818 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
820 state->start_time += state->duration + GST_SECOND * t1;
821 state->duration = GST_SECOND * t2;
825 { /* No need to parse that text if it's out of segment */
826 gint64 clip_start = 0, clip_stop = 0;
827 gboolean in_seg = FALSE;
829 /* Check our segment start/stop */
830 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
831 state->start_time, state->start_time + state->duration,
832 &clip_start, &clip_stop);
835 state->start_time = clip_start;
836 state->duration = clip_stop - clip_start;
842 /* looking for subtitle text; empty line ends this
845 g_string_append_c (state->buf, '\n');
846 g_string_append (state->buf, line);
847 if (strlen (line) == 0) {
848 ret = g_strdup (state->buf->str);
849 g_string_truncate (state->buf, 0);
855 g_assert_not_reached ();
861 parser_state_init (ParserState * state)
863 GST_DEBUG ("initialising parser");
866 g_string_truncate (state->buf, 0);
868 state->buf = g_string_new (NULL);
871 state->start_time = 0;
874 state->segment = NULL;
878 parser_state_dispose (ParserState * state)
881 g_string_free (state->buf, TRUE);
884 if (state->user_data) {
885 sami_context_reset (state);
890 * FIXME: maybe we should pass along a second argument, the preceding
891 * text buffer, because that is how this originally worked, even though
892 * I don't really see the use of that.
895 static GstSubParseFormat
896 gst_sub_parse_data_format_autodetect (gchar * match_str)
898 static gboolean need_init_regexps = TRUE;
899 static regex_t mdvd_rx;
900 static regex_t subrip_rx;
903 /* initialize the regexps used the first time around */
904 if (need_init_regexps) {
908 need_init_regexps = FALSE;
909 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
910 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
911 (err = regcomp (&subrip_rx, "^[0-9]([0-9]){0,3}(\x0d)?\x0a"
912 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
913 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
914 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
915 regerror (err, &subrip_rx, errstr, 127);
916 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
920 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
921 GST_LOG ("MicroDVD (frame based) format detected");
922 return GST_SUB_PARSE_FORMAT_MDVDSUB;
924 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
925 GST_LOG ("SubRip (time based) format detected");
926 return GST_SUB_PARSE_FORMAT_SUBRIP;
929 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
930 GST_LOG ("MPSub (time based) format detected");
931 return GST_SUB_PARSE_FORMAT_MPSUB;
933 if (strstr (match_str, "<SAMI>") != NULL ||
934 strstr (match_str, "<sami>") != NULL) {
935 GST_LOG ("SAMI (time based) format detected");
936 return GST_SUB_PARSE_FORMAT_SAMI;
938 /* we're boldly assuming the first subtitle appears within the first hour */
939 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
940 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
941 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
942 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
943 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
944 GST_LOG ("TMPlayer (time based) format detected");
945 return GST_SUB_PARSE_FORMAT_TMPLAYER;
947 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
948 GST_LOG ("MPL2 (time based) format detected");
949 return GST_SUB_PARSE_FORMAT_MPL2;
951 if (strstr (match_str, "[INFORMATION]") != NULL) {
952 GST_LOG ("SubViewer (time based) format detected");
953 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
956 GST_DEBUG ("no subtitle format detected");
957 return GST_SUB_PARSE_FORMAT_UNKNOWN;
961 gst_sub_parse_format_autodetect (GstSubParse * self)
964 GstSubParseFormat format;
966 if (strlen (self->textbuf->str) < 35) {
967 GST_DEBUG ("File too small to be a subtitles file");
971 data = g_strndup (self->textbuf->str, 35);
972 format = gst_sub_parse_data_format_autodetect (data);
975 self->parser_type = format;
976 parser_state_init (&self->state);
979 case GST_SUB_PARSE_FORMAT_MDVDSUB:
980 self->parse_line = parse_mdvdsub;
981 return gst_caps_new_simple ("text/x-pango-markup", NULL);
982 case GST_SUB_PARSE_FORMAT_SUBRIP:
983 self->parse_line = parse_subrip;
984 return gst_caps_new_simple ("text/x-pango-markup", NULL);
985 case GST_SUB_PARSE_FORMAT_MPSUB:
986 self->parse_line = parse_mpsub;
987 return gst_caps_new_simple ("text/plain", NULL);
988 case GST_SUB_PARSE_FORMAT_SAMI:
989 self->parse_line = parse_sami;
990 sami_context_init (&self->state);
991 return gst_caps_new_simple ("text/x-pango-markup", NULL);
992 case GST_SUB_PARSE_FORMAT_TMPLAYER:
993 self->parse_line = parse_tmplayer;
994 return gst_caps_new_simple ("text/plain", NULL);
995 case GST_SUB_PARSE_FORMAT_MPL2:
996 self->parse_line = parse_mpl2;
997 return gst_caps_new_simple ("text/x-pango-markup", NULL);
998 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
999 self->parse_line = parse_subviewer;
1000 return gst_caps_new_simple ("text/plain", NULL);
1001 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1003 GST_DEBUG ("no subtitle format detected");
1004 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1005 ("The input is not a valid/supported subtitle file"), (NULL));
1011 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1015 discont = GST_BUFFER_IS_DISCONT (buf);
1017 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1018 GST_BUFFER_OFFSET (buf) != self->offset) {
1019 self->offset = GST_BUFFER_OFFSET (buf);
1024 GST_INFO ("discontinuity");
1025 /* flush the parser state */
1026 parser_state_init (&self->state);
1027 g_string_truncate (self->textbuf, 0);
1028 sami_context_reset (&self->state);
1029 /* we could set a flag to make sure that the next buffer we push out also
1030 * has the DISCONT flag set, but there's no point really given that it's
1031 * subtitles which are discontinuous by nature. */
1034 self->textbuf = g_string_append_len (self->textbuf,
1035 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1036 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1037 self->next_offset = self->offset;
1039 gst_buffer_unref (buf);
1042 static GstFlowReturn
1043 handle_buffer (GstSubParse * self, GstBuffer * buf)
1045 GstFlowReturn ret = GST_FLOW_OK;
1046 GstCaps *caps = NULL;
1047 gchar *line, *subtitle;
1049 feed_textbuf (self, buf);
1051 /* make sure we know the format */
1052 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1053 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1054 return GST_FLOW_UNEXPECTED;
1056 if (!gst_pad_set_caps (self->srcpad, caps)) {
1057 gst_caps_unref (caps);
1058 return GST_FLOW_UNEXPECTED;
1060 gst_caps_unref (caps);
1063 while ((line = get_next_line (self)) && !self->flushing) {
1064 /* Set segment on our parser state machine */
1065 self->state.segment = &self->segment;
1066 /* Now parse the line, out of segment lines will just return NULL */
1067 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
1068 subtitle = self->parse_line (&self->state, line);
1072 guint subtitle_len = strlen (subtitle);
1074 /* +1 for terminating NUL character */
1075 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1076 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1077 GST_PAD_CAPS (self->srcpad), &buf);
1079 if (ret == GST_FLOW_OK) {
1080 /* copy terminating NUL character as well */
1081 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1082 GST_BUFFER_SIZE (buf) = subtitle_len;
1083 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1084 GST_BUFFER_DURATION (buf) = self->state.duration;
1086 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1087 self->state.start_time);
1089 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1090 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1091 GST_TIME_ARGS (self->state.duration));
1093 ret = gst_pad_push (self->srcpad, buf);
1096 /* move this forward (the tmplayer parser needs this) */
1097 if (self->state.duration != GST_CLOCK_TIME_NONE)
1098 self->state.start_time += self->state.duration;
1103 if (ret != GST_FLOW_OK) {
1104 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1113 static GstFlowReturn
1114 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1119 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1121 /* Push newsegment if needed */
1122 if (self->need_segment) {
1123 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1126 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1127 self->segment.rate, self->segment.format,
1128 self->segment.last_stop, self->segment.stop, self->segment.time));
1129 self->need_segment = FALSE;
1132 ret = handle_buffer (self, buf);
1138 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1140 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1141 gboolean ret = FALSE;
1143 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1145 switch (GST_EVENT_TYPE (event)) {
1146 case GST_EVENT_EOS:{
1147 /* Make sure the last subrip chunk is pushed out even
1148 * if the file does not have an empty line at the end */
1149 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1150 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1151 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1152 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1154 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1155 GST_BUFFER_DATA (buf)[0] = '\n';
1156 GST_BUFFER_DATA (buf)[1] = '\n';
1157 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1158 GST_BUFFER_SIZE (buf) = 2;
1159 GST_BUFFER_OFFSET (buf) = self->offset;
1160 gst_sub_parse_chain (pad, buf);
1162 ret = gst_pad_event_default (pad, event);
1165 case GST_EVENT_NEWSEGMENT:
1169 gint64 start, stop, time;
1172 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1175 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1177 if (format == GST_FORMAT_TIME) {
1178 gst_segment_set_newsegment (&self->segment, update, rate, format,
1181 /* if not time format, we'll either start with a 0 timestamp anyway or
1182 * it's following a seek in which case we'll have saved the requested
1183 * seek segment and don't want to overwrite it (remember that on a seek
1184 * we always just seek back to the start in BYTES format and just throw
1185 * away all text that's before the requested position; if the subtitles
1186 * come from an upstream demuxer, it won't be able to handle our BYTES
1187 * seek request and instead send us a newsegment from the seek request
1188 * it received via its video pads instead, so all is fine then too) */
1192 gst_event_unref (event);
1195 case GST_EVENT_FLUSH_START:
1197 self->flushing = TRUE;
1199 ret = gst_pad_event_default (pad, event);
1202 case GST_EVENT_FLUSH_STOP:
1204 self->flushing = FALSE;
1206 ret = gst_pad_event_default (pad, event);
1210 ret = gst_pad_event_default (pad, event);
1214 gst_object_unref (self);
1220 static GstStateChangeReturn
1221 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1223 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1224 GstSubParse *self = GST_SUBPARSE (element);
1226 switch (transition) {
1227 case GST_STATE_CHANGE_READY_TO_PAUSED:
1228 /* format detection will init the parser state */
1230 self->next_offset = 0;
1231 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1232 self->valid_utf8 = TRUE;
1233 g_string_truncate (self->textbuf, 0);
1239 ret = parent_class->change_state (element, transition);
1240 if (ret == GST_STATE_CHANGE_FAILURE)
1243 switch (transition) {
1244 case GST_STATE_CHANGE_PAUSED_TO_READY:
1245 parser_state_dispose (&self->state);
1246 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1259 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1260 * also, give different subtitle formats really different types */
1261 static GstStaticCaps mpl2_caps =
1262 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1263 static GstStaticCaps tmp_caps =
1264 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1265 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1266 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1268 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1269 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1270 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1271 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1274 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1276 GstSubParseFormat format;
1281 if (!(data = gst_type_find_peek (tf, 0, 36)))
1284 /* make sure string passed to _autodetect() is NUL-terminated */
1285 str = g_strndup ((gchar *) data, 35);
1286 format = gst_sub_parse_data_format_autodetect (str);
1290 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1291 GST_DEBUG ("MicroDVD format detected");
1294 case GST_SUB_PARSE_FORMAT_SUBRIP:
1295 GST_DEBUG ("SubRip format detected");
1298 case GST_SUB_PARSE_FORMAT_MPSUB:
1299 GST_DEBUG ("MPSub format detected");
1302 case GST_SUB_PARSE_FORMAT_SAMI:
1303 GST_DEBUG ("SAMI (time-based) format detected");
1306 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1307 GST_DEBUG ("TMPlayer (time based) format detected");
1310 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1311 * returning a high probability (however, since we registered our
1312 * typefinder here with a rank of MARGINAL we should pretty much only
1313 * be called if most other typefinders have already run */
1314 case GST_SUB_PARSE_FORMAT_MPL2:
1315 GST_DEBUG ("MPL2 (time based) format detected");
1318 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1319 GST_DEBUG ("SubViewer format detected");
1323 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1324 GST_DEBUG ("no subtitle format detected");
1328 /* if we're here, it's ok */
1329 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1333 plugin_init (GstPlugin * plugin)
1335 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1339 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1341 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1342 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1345 if (!gst_element_register (plugin, "subparse",
1346 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1347 !gst_element_register (plugin, "ssaparse",
1348 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1355 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1359 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)