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;
873 state->max_duration = 0; /* no limit */
875 state->segment = NULL;
879 parser_state_dispose (ParserState * state)
882 g_string_free (state->buf, TRUE);
885 if (state->user_data) {
886 sami_context_reset (state);
891 * FIXME: maybe we should pass along a second argument, the preceding
892 * text buffer, because that is how this originally worked, even though
893 * I don't really see the use of that.
896 static GstSubParseFormat
897 gst_sub_parse_data_format_autodetect (gchar * match_str)
899 static gboolean need_init_regexps = TRUE;
900 static regex_t mdvd_rx;
901 static regex_t subrip_rx;
904 /* initialize the regexps used the first time around */
905 if (need_init_regexps) {
909 need_init_regexps = FALSE;
910 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
911 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
912 (err = regcomp (&subrip_rx, "^[0-9]([0-9]){0,3}(\x0d)?\x0a"
913 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
914 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
915 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
916 regerror (err, &subrip_rx, errstr, 127);
917 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
921 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
922 GST_LOG ("MicroDVD (frame based) format detected");
923 return GST_SUB_PARSE_FORMAT_MDVDSUB;
925 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
926 GST_LOG ("SubRip (time based) format detected");
927 return GST_SUB_PARSE_FORMAT_SUBRIP;
930 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
931 GST_LOG ("MPSub (time based) format detected");
932 return GST_SUB_PARSE_FORMAT_MPSUB;
934 if (strstr (match_str, "<SAMI>") != NULL ||
935 strstr (match_str, "<sami>") != NULL) {
936 GST_LOG ("SAMI (time based) format detected");
937 return GST_SUB_PARSE_FORMAT_SAMI;
939 /* we're boldly assuming the first subtitle appears within the first hour */
940 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
941 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
942 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
943 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
944 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
945 GST_LOG ("TMPlayer (time based) format detected");
946 return GST_SUB_PARSE_FORMAT_TMPLAYER;
948 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
949 GST_LOG ("MPL2 (time based) format detected");
950 return GST_SUB_PARSE_FORMAT_MPL2;
952 if (strstr (match_str, "[INFORMATION]") != NULL) {
953 GST_LOG ("SubViewer (time based) format detected");
954 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
957 GST_DEBUG ("no subtitle format detected");
958 return GST_SUB_PARSE_FORMAT_UNKNOWN;
962 gst_sub_parse_format_autodetect (GstSubParse * self)
965 GstSubParseFormat format;
967 if (strlen (self->textbuf->str) < 35) {
968 GST_DEBUG ("File too small to be a subtitles file");
972 data = g_strndup (self->textbuf->str, 35);
973 format = gst_sub_parse_data_format_autodetect (data);
976 self->parser_type = format;
977 parser_state_init (&self->state);
980 case GST_SUB_PARSE_FORMAT_MDVDSUB:
981 self->parse_line = parse_mdvdsub;
982 return gst_caps_new_simple ("text/x-pango-markup", NULL);
983 case GST_SUB_PARSE_FORMAT_SUBRIP:
984 self->parse_line = parse_subrip;
985 return gst_caps_new_simple ("text/x-pango-markup", NULL);
986 case GST_SUB_PARSE_FORMAT_MPSUB:
987 self->parse_line = parse_mpsub;
988 return gst_caps_new_simple ("text/plain", NULL);
989 case GST_SUB_PARSE_FORMAT_SAMI:
990 self->parse_line = parse_sami;
991 sami_context_init (&self->state);
992 return gst_caps_new_simple ("text/x-pango-markup", NULL);
993 case GST_SUB_PARSE_FORMAT_TMPLAYER:
994 self->parse_line = parse_tmplayer;
995 self->state.max_duration = 5 * GST_SECOND;
996 return gst_caps_new_simple ("text/plain", NULL);
997 case GST_SUB_PARSE_FORMAT_MPL2:
998 self->parse_line = parse_mpl2;
999 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1000 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1001 self->parse_line = parse_subviewer;
1002 return gst_caps_new_simple ("text/plain", NULL);
1003 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1005 GST_DEBUG ("no subtitle format detected");
1006 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1007 ("The input is not a valid/supported subtitle file"), (NULL));
1013 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1017 discont = GST_BUFFER_IS_DISCONT (buf);
1019 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1020 GST_BUFFER_OFFSET (buf) != self->offset) {
1021 self->offset = GST_BUFFER_OFFSET (buf);
1026 GST_INFO ("discontinuity");
1027 /* flush the parser state */
1028 parser_state_init (&self->state);
1029 g_string_truncate (self->textbuf, 0);
1030 sami_context_reset (&self->state);
1031 /* we could set a flag to make sure that the next buffer we push out also
1032 * has the DISCONT flag set, but there's no point really given that it's
1033 * subtitles which are discontinuous by nature. */
1036 self->textbuf = g_string_append_len (self->textbuf,
1037 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1038 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1039 self->next_offset = self->offset;
1041 gst_buffer_unref (buf);
1044 static GstFlowReturn
1045 handle_buffer (GstSubParse * self, GstBuffer * buf)
1047 GstFlowReturn ret = GST_FLOW_OK;
1048 GstCaps *caps = NULL;
1049 gchar *line, *subtitle;
1051 feed_textbuf (self, buf);
1053 /* make sure we know the format */
1054 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1055 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1056 return GST_FLOW_UNEXPECTED;
1058 if (!gst_pad_set_caps (self->srcpad, caps)) {
1059 gst_caps_unref (caps);
1060 return GST_FLOW_UNEXPECTED;
1062 gst_caps_unref (caps);
1065 while ((line = get_next_line (self)) && !self->flushing) {
1066 /* Set segment on our parser state machine */
1067 self->state.segment = &self->segment;
1068 /* Now parse the line, out of segment lines will just return NULL */
1069 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
1070 subtitle = self->parse_line (&self->state, line);
1074 guint subtitle_len = strlen (subtitle);
1076 /* +1 for terminating NUL character */
1077 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1078 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1079 GST_PAD_CAPS (self->srcpad), &buf);
1081 if (ret == GST_FLOW_OK) {
1082 /* copy terminating NUL character as well */
1083 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1084 GST_BUFFER_SIZE (buf) = subtitle_len;
1085 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1086 GST_BUFFER_DURATION (buf) = self->state.duration;
1088 /* in some cases (e.g. tmplayer) we can only determine the duration
1089 * of a text chunk from the timestamp of the next text chunk; in those
1090 * cases, we probably want to limit the duration to something
1091 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1092 * just because nothing else is being said during that time */
1093 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1094 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1095 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1098 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1099 self->state.start_time);
1101 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1102 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1103 GST_TIME_ARGS (self->state.duration));
1105 ret = gst_pad_push (self->srcpad, buf);
1108 /* move this forward (the tmplayer parser needs this) */
1109 if (self->state.duration != GST_CLOCK_TIME_NONE)
1110 self->state.start_time += self->state.duration;
1115 if (ret != GST_FLOW_OK) {
1116 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1125 static GstFlowReturn
1126 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1131 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1133 /* Push newsegment if needed */
1134 if (self->need_segment) {
1135 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1138 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1139 self->segment.rate, self->segment.format,
1140 self->segment.last_stop, self->segment.stop, self->segment.time));
1141 self->need_segment = FALSE;
1144 ret = handle_buffer (self, buf);
1150 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1152 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1153 gboolean ret = FALSE;
1155 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1157 switch (GST_EVENT_TYPE (event)) {
1158 case GST_EVENT_EOS:{
1159 /* Make sure the last subrip chunk is pushed out even
1160 * if the file does not have an empty line at the end */
1161 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1162 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1163 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1164 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1166 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1167 GST_BUFFER_DATA (buf)[0] = '\n';
1168 GST_BUFFER_DATA (buf)[1] = '\n';
1169 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1170 GST_BUFFER_SIZE (buf) = 2;
1171 GST_BUFFER_OFFSET (buf) = self->offset;
1172 gst_sub_parse_chain (pad, buf);
1174 ret = gst_pad_event_default (pad, event);
1177 case GST_EVENT_NEWSEGMENT:
1181 gint64 start, stop, time;
1184 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1187 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1189 if (format == GST_FORMAT_TIME) {
1190 gst_segment_set_newsegment (&self->segment, update, rate, format,
1193 /* if not time format, we'll either start with a 0 timestamp anyway or
1194 * it's following a seek in which case we'll have saved the requested
1195 * seek segment and don't want to overwrite it (remember that on a seek
1196 * we always just seek back to the start in BYTES format and just throw
1197 * away all text that's before the requested position; if the subtitles
1198 * come from an upstream demuxer, it won't be able to handle our BYTES
1199 * seek request and instead send us a newsegment from the seek request
1200 * it received via its video pads instead, so all is fine then too) */
1204 gst_event_unref (event);
1207 case GST_EVENT_FLUSH_START:
1209 self->flushing = TRUE;
1211 ret = gst_pad_event_default (pad, event);
1214 case GST_EVENT_FLUSH_STOP:
1216 self->flushing = FALSE;
1218 ret = gst_pad_event_default (pad, event);
1222 ret = gst_pad_event_default (pad, event);
1226 gst_object_unref (self);
1232 static GstStateChangeReturn
1233 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1235 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1236 GstSubParse *self = GST_SUBPARSE (element);
1238 switch (transition) {
1239 case GST_STATE_CHANGE_READY_TO_PAUSED:
1240 /* format detection will init the parser state */
1242 self->next_offset = 0;
1243 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1244 self->valid_utf8 = TRUE;
1245 g_string_truncate (self->textbuf, 0);
1251 ret = parent_class->change_state (element, transition);
1252 if (ret == GST_STATE_CHANGE_FAILURE)
1255 switch (transition) {
1256 case GST_STATE_CHANGE_PAUSED_TO_READY:
1257 parser_state_dispose (&self->state);
1258 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1271 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1272 * also, give different subtitle formats really different types */
1273 static GstStaticCaps mpl2_caps =
1274 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1275 static GstStaticCaps tmp_caps =
1276 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1277 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1278 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1280 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1281 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1282 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1283 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1286 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1288 GstSubParseFormat format;
1293 if (!(data = gst_type_find_peek (tf, 0, 36)))
1296 /* make sure string passed to _autodetect() is NUL-terminated */
1297 str = g_strndup ((gchar *) data, 35);
1298 format = gst_sub_parse_data_format_autodetect (str);
1302 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1303 GST_DEBUG ("MicroDVD format detected");
1306 case GST_SUB_PARSE_FORMAT_SUBRIP:
1307 GST_DEBUG ("SubRip format detected");
1310 case GST_SUB_PARSE_FORMAT_MPSUB:
1311 GST_DEBUG ("MPSub format detected");
1314 case GST_SUB_PARSE_FORMAT_SAMI:
1315 GST_DEBUG ("SAMI (time-based) format detected");
1318 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1319 GST_DEBUG ("TMPlayer (time based) format detected");
1322 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1323 * returning a high probability (however, since we registered our
1324 * typefinder here with a rank of MARGINAL we should pretty much only
1325 * be called if most other typefinders have already run */
1326 case GST_SUB_PARSE_FORMAT_MPL2:
1327 GST_DEBUG ("MPL2 (time based) format detected");
1330 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1331 GST_DEBUG ("SubViewer format detected");
1335 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1336 GST_DEBUG ("no subtitle format detected");
1340 /* if we're here, it's ok */
1341 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1345 plugin_init (GstPlugin * plugin)
1347 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1351 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1353 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1354 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1357 if (!gst_element_register (plugin, "subparse",
1358 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1359 !gst_element_register (plugin, "ssaparse",
1360 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1367 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1371 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)