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 #ifndef GST_DISABLE_XML
150 sami_context_deinit (&subparse->state);
153 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
157 gst_sub_parse_class_init (GstSubParseClass * klass)
159 GObjectClass *object_class = G_OBJECT_CLASS (klass);
160 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
162 parent_class = g_type_class_peek_parent (klass);
164 object_class->dispose = gst_sub_parse_dispose;
165 object_class->set_property = gst_sub_parse_set_property;
166 object_class->get_property = gst_sub_parse_get_property;
168 element_class->change_state = gst_sub_parse_change_state;
170 g_object_class_install_property (object_class, PROP_ENCODING,
171 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
172 "Encoding to assume if input subtitles are not in UTF-8 encoding. "
173 "If not set, the GST_SUBTITLE_ENCODING environment variable will "
174 "be checked for an encoding to use. If that is not set either, "
175 "ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
176 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
180 gst_sub_parse_init (GstSubParse * subparse)
182 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
183 gst_pad_set_chain_function (subparse->sinkpad,
184 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
185 gst_pad_set_event_function (subparse->sinkpad,
186 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
187 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
189 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
190 gst_pad_set_event_function (subparse->srcpad,
191 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
192 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
194 subparse->textbuf = g_string_new (NULL);
195 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
196 subparse->flushing = FALSE;
197 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
198 subparse->need_segment = TRUE;
199 subparse->encoding = g_strdup (DEFAULT_ENCODING);
203 * Source pad functions.
207 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
209 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
210 gboolean ret = FALSE;
212 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
214 switch (GST_EVENT_TYPE (event)) {
218 GstSeekType start_type, stop_type;
223 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
224 &start_type, &start, &stop_type, &stop);
226 if (format != GST_FORMAT_TIME) {
227 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
228 gst_event_unref (event);
232 /* Convert that seek to a seeking in bytes at position 0,
233 FIXME: could use an index */
234 ret = gst_pad_push_event (self->sinkpad,
235 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
236 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
239 /* Apply the seek to our segment */
240 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
241 start_type, start, stop_type, stop, &update);
243 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
246 self->next_offset = 0;
248 self->need_segment = TRUE;
250 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
253 gst_event_unref (event);
257 ret = gst_pad_event_default (pad, event);
262 gst_object_unref (self);
268 gst_sub_parse_set_property (GObject * object, guint prop_id,
269 const GValue * value, GParamSpec * pspec)
271 GstSubParse *subparse = GST_SUBPARSE (object);
273 GST_OBJECT_LOCK (subparse);
276 g_free (subparse->encoding);
277 subparse->encoding = g_value_dup_string (value);
278 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
279 GST_STR_NULL (subparse->encoding));
282 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
285 GST_OBJECT_UNLOCK (subparse);
289 gst_sub_parse_get_property (GObject * object, guint prop_id,
290 GValue * value, GParamSpec * pspec)
292 GstSubParse *subparse = GST_SUBPARSE (object);
294 GST_OBJECT_LOCK (subparse);
297 g_value_set_string (value, subparse->encoding);
300 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
303 GST_OBJECT_UNLOCK (subparse);
307 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
309 const gchar *encoding;
313 if (self->valid_utf8) {
314 if (g_utf8_validate (str, len, NULL)) {
315 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
316 return g_strndup (str, len);
318 GST_INFO_OBJECT (self, "invalid UTF-8!");
319 self->valid_utf8 = FALSE;
322 encoding = self->encoding;
323 if (encoding == NULL || *encoding == '\0') {
324 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
326 if (encoding == NULL || *encoding == '\0') {
327 /* if local encoding is UTF-8 and no encoding specified
328 * via the environment variable, assume ISO-8859-15 */
329 if (g_get_charset (&encoding)) {
330 encoding = "ISO-8859-15";
334 ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
338 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
339 encoding, err->message);
342 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
343 ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
347 GST_LOG_OBJECT (self,
348 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
349 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
355 get_next_line (GstSubParse * self)
358 const char *line_end;
360 gboolean have_r = FALSE;
362 line_end = strchr (self->textbuf->str, '\n');
365 /* end-of-line not found; return for more data */
369 /* get rid of '\r' */
370 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
375 line_len = line_end - self->textbuf->str;
376 line = convert_encoding (self, self->textbuf->str, line_len);
377 self->textbuf = g_string_erase (self->textbuf, 0,
378 line_len + (have_r ? 2 : 1));
383 parse_mdvdsub (ParserState * state, const gchar * line)
385 const gchar *line_split;
387 guint start_frame, end_frame;
388 gint64 clip_start = 0, clip_stop = 0;
389 gboolean in_seg = FALSE;
393 /* style variables */
398 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
399 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
400 " format, failed:\n%s", line);
404 /* skip the {%u}{%u} part */
405 line = strchr (line, '}') + 1;
406 line = strchr (line, '}') + 1;
408 /* see if there's a first line with a framerate */
409 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
410 gchar *rest, *end = NULL;
412 rest = g_strdup (line);
413 g_strdelimit (rest, ",", '.');
414 state->fps = g_ascii_strtod (rest, &end);
417 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
422 if (state->fps == 0.0) {
423 /* FIXME: hardcoded for now, is there a better way/assumption? */
424 state->fps = 24000.0 / 1001.0;
425 GST_INFO ("no framerate specified, assuming %f", state->fps);
428 state->start_time = start_frame / state->fps * GST_SECOND;
429 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
431 /* Check our segment start/stop */
432 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
433 state->start_time, state->start_time + state->duration, &clip_start,
436 /* No need to parse that text if it's out of segment */
438 state->start_time = clip_start;
439 state->duration = clip_stop - clip_start;
444 markup = g_string_new (NULL);
449 /* parse style markup */
450 if (strncmp (line, "{y:i}", 5) == 0) {
452 line = strchr (line, '}') + 1;
454 if (strncmp (line, "{y:b}", 5) == 0) {
456 line = strchr (line, '}') + 1;
458 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
459 line = strchr (line, '}') + 1;
461 /* forward slashes at beginning/end signify italics too */
462 if (g_str_has_prefix (line, "/")) {
466 if ((line_split = strchr (line, '|')))
467 line_chunk = g_markup_escape_text (line, line_split - line);
469 line_chunk = g_markup_escape_text (line, strlen (line));
471 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
472 * always at the end of a line or can they span multiple lines?) */
473 if (g_str_has_suffix (line_chunk, "/")) {
474 line_chunk[strlen (line_chunk) - 1] = '\0';
477 markup = g_string_append (markup, "<span");
479 g_string_append (markup, " style=\"italic\"");
481 g_string_append (markup, " weight=\"bold\"");
483 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
484 g_string_append_printf (markup, ">%s</span>", line_chunk);
487 g_string_append (markup, "\n");
488 line = line_split + 1;
494 g_string_free (markup, FALSE);
495 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
496 state->start_time / (double) GST_SECOND,
497 state->duration / (double) GST_SECOND, ret);
502 strip_trailing_newlines (gchar * txt)
508 while (len > 1 && txt[len - 1] == '\n') {
515 /* we want to escape text in general, but retain basic markup like
516 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
517 * just unescape a white list of allowed markups again after
518 * escaping everything (the text between these simple markers isn't
519 * necessarily escaped, so it seems best to do it like this) */
521 subrip_unescape_formatting (gchar * txt)
525 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
526 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
527 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
528 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
530 pos[1] = g_ascii_tolower (pos[4]);
532 /* move NUL terminator as well */
533 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
538 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
539 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
540 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
541 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
544 pos[2] = g_ascii_tolower (pos[5]);
546 /* move NUL terminator as well */
547 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
555 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
559 tag = start + strlen ("<");
563 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
568 GST_LOG ("removing unhandled tag '%s'", start);
570 g_memmove (start, stop, strlen (stop) + 1);
574 /* remove tags we haven't explicitly allowed earlier on, like font tags
577 subrip_remove_unhandled_tags (gchar * txt)
581 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
582 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
583 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
589 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
590 * assumes the input has been escaped and subrip_unescape_formatting() has then
591 * been run over the input! This function adds missing closing markup tags and
592 * removes broken closing tags for tags that have never been opened. */
594 subrip_fix_up_markup (gchar ** p_txt)
596 gchar *cur, *next_tag;
598 guint num_open_tags = 0;
600 g_assert (*p_txt != NULL);
603 while (*cur != '\0') {
604 next_tag = strchr (cur, '<');
605 if (next_tag == NULL)
611 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
612 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
613 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
616 /* it's all good, closing tag which is open */
624 if (num_open_tags == G_N_ELEMENTS (open_tags))
625 return; /* something dodgy is going on, stop parsing */
626 open_tags[num_open_tags] = *next_tag;
630 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
631 g_assert_not_reached ();
637 if (num_open_tags > 0) {
640 s = g_string_new (*p_txt);
641 while (num_open_tags > 0) {
642 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
643 g_string_append_c (s, '<');
644 g_string_append_c (s, '/');
645 g_string_append_c (s, open_tags[num_open_tags - 1]);
646 g_string_append_c (s, '>');
650 *p_txt = g_string_free (s, FALSE);
655 parse_subrip (ParserState * state, const gchar * line)
657 guint h1, m1, s1, ms1;
658 guint h2, m2, s2, ms2;
662 switch (state->state) {
664 /* looking for a single integer */
665 if (sscanf (line, "%u", &subnum) == 1)
669 /* looking for start_time --> end_time */
670 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
671 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
674 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
677 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
678 ms2 * GST_MSECOND - state->start_time;
680 GST_DEBUG ("error parsing subrip time line");
686 /* No need to parse that text if it's out of segment */
687 gint64 clip_start = 0, clip_stop = 0;
688 gboolean in_seg = FALSE;
690 /* Check our segment start/stop */
691 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
692 state->start_time, state->start_time + state->duration,
693 &clip_start, &clip_stop);
696 state->start_time = clip_start;
697 state->duration = clip_stop - clip_start;
703 /* looking for subtitle text; empty line ends this subtitle entry */
705 g_string_append_c (state->buf, '\n');
706 g_string_append (state->buf, line);
707 if (strlen (line) == 0) {
708 ret = g_markup_escape_text (state->buf->str, state->buf->len);
709 g_string_truncate (state->buf, 0);
711 subrip_unescape_formatting (ret);
712 subrip_remove_unhandled_tags (ret);
713 strip_trailing_newlines (ret);
714 subrip_fix_up_markup (&ret);
719 g_return_val_if_reached (NULL);
724 subviewer_unescape_newlines (gchar * read)
728 /* Replace all occurences of '[br]' with a newline as version 2
729 * of the subviewer format uses this for newlines */
731 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
735 if (strncmp (read, "[br]", 4) == 0) {
749 parse_subviewer (ParserState * state, const gchar * line)
751 guint h1, m1, s1, ms1;
752 guint h2, m2, s2, ms2;
755 /* TODO: Maybe also parse the fields in the header, especially DELAY.
756 * For examples see the unit test or
757 * http://www.doom9.org/index.html?/sub.htm */
759 switch (state->state) {
761 /* looking for start_time,end_time */
762 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
763 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
766 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
769 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
770 ms2 * GST_MSECOND - state->start_time;
775 /* No need to parse that text if it's out of segment */
776 gint64 clip_start = 0, clip_stop = 0;
777 gboolean in_seg = FALSE;
779 /* Check our segment start/stop */
780 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
781 state->start_time, state->start_time + state->duration,
782 &clip_start, &clip_stop);
785 state->start_time = clip_start;
786 state->duration = clip_stop - clip_start;
792 /* looking for subtitle text; empty line ends this subtitle entry */
794 g_string_append_c (state->buf, '\n');
795 g_string_append (state->buf, line);
796 if (strlen (line) == 0) {
797 ret = g_strdup (state->buf->str);
798 subviewer_unescape_newlines (ret);
799 strip_trailing_newlines (ret);
800 g_string_truncate (state->buf, 0);
806 g_assert_not_reached ();
812 parse_mpsub (ParserState * state, const gchar * line)
817 switch (state->state) {
819 /* looking for two floats (offset, duration) */
820 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
822 state->start_time += state->duration + GST_SECOND * t1;
823 state->duration = GST_SECOND * t2;
827 { /* No need to parse that text if it's out of segment */
828 gint64 clip_start = 0, clip_stop = 0;
829 gboolean in_seg = FALSE;
831 /* Check our segment start/stop */
832 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
833 state->start_time, state->start_time + state->duration,
834 &clip_start, &clip_stop);
837 state->start_time = clip_start;
838 state->duration = clip_stop - clip_start;
844 /* looking for subtitle text; empty line ends this
847 g_string_append_c (state->buf, '\n');
848 g_string_append (state->buf, line);
849 if (strlen (line) == 0) {
850 ret = g_strdup (state->buf->str);
851 g_string_truncate (state->buf, 0);
857 g_assert_not_reached ();
863 parser_state_init (ParserState * state)
865 GST_DEBUG ("initialising parser");
868 g_string_truncate (state->buf, 0);
870 state->buf = g_string_new (NULL);
873 state->start_time = 0;
875 state->max_duration = 0; /* no limit */
877 state->segment = NULL;
881 parser_state_dispose (ParserState * state)
884 g_string_free (state->buf, TRUE);
887 #ifndef GST_DISABLE_XML
888 if (state->user_data) {
889 sami_context_reset (state);
895 * FIXME: maybe we should pass along a second argument, the preceding
896 * text buffer, because that is how this originally worked, even though
897 * I don't really see the use of that.
900 static GstSubParseFormat
901 gst_sub_parse_data_format_autodetect (gchar * match_str)
903 static gboolean need_init_regexps = TRUE;
904 static regex_t mdvd_rx;
905 static regex_t subrip_rx;
908 /* initialize the regexps used the first time around */
909 if (need_init_regexps) {
913 need_init_regexps = FALSE;
914 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
915 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
916 (err = regcomp (&subrip_rx, "^([ 0-9]){0,3}[0-9](\x0d)?\x0a"
917 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]"
918 " --> ([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]",
919 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
920 regerror (err, &subrip_rx, errstr, 127);
921 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
925 /* If the string contains a UTF-8 BOM drop it */
926 if ((guint8) match_str[0] == 0xEF && (guint8) match_str[1] == 0xBB
927 && (guint8) match_str[2] == 0xBF)
930 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
931 GST_LOG ("MicroDVD (frame based) format detected");
932 return GST_SUB_PARSE_FORMAT_MDVDSUB;
934 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
935 GST_LOG ("SubRip (time based) format detected");
936 return GST_SUB_PARSE_FORMAT_SUBRIP;
939 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
940 GST_LOG ("MPSub (time based) format detected");
941 return GST_SUB_PARSE_FORMAT_MPSUB;
943 #ifndef GST_DISABLE_XML
944 if (strstr (match_str, "<SAMI>") != NULL ||
945 strstr (match_str, "<sami>") != NULL) {
946 GST_LOG ("SAMI (time based) format detected");
947 return GST_SUB_PARSE_FORMAT_SAMI;
950 /* we're boldly assuming the first subtitle appears within the first hour */
951 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
952 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
953 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
954 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
955 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
956 GST_LOG ("TMPlayer (time based) format detected");
957 return GST_SUB_PARSE_FORMAT_TMPLAYER;
959 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
960 GST_LOG ("MPL2 (time based) format detected");
961 return GST_SUB_PARSE_FORMAT_MPL2;
963 if (strstr (match_str, "[INFORMATION]") != NULL) {
964 GST_LOG ("SubViewer (time based) format detected");
965 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
968 GST_DEBUG ("no subtitle format detected");
969 return GST_SUB_PARSE_FORMAT_UNKNOWN;
973 gst_sub_parse_format_autodetect (GstSubParse * self)
976 GstSubParseFormat format;
978 if (strlen (self->textbuf->str) < 35) {
979 GST_DEBUG ("File too small to be a subtitles file");
983 data = g_strndup (self->textbuf->str, 35);
984 format = gst_sub_parse_data_format_autodetect (data);
987 self->parser_type = format;
988 parser_state_init (&self->state);
991 case GST_SUB_PARSE_FORMAT_MDVDSUB:
992 self->parse_line = parse_mdvdsub;
993 return gst_caps_new_simple ("text/x-pango-markup", NULL);
994 case GST_SUB_PARSE_FORMAT_SUBRIP:
995 self->parse_line = parse_subrip;
996 return gst_caps_new_simple ("text/x-pango-markup", NULL);
997 case GST_SUB_PARSE_FORMAT_MPSUB:
998 self->parse_line = parse_mpsub;
999 return gst_caps_new_simple ("text/plain", NULL);
1000 #ifndef GST_DISABLE_XML
1001 case GST_SUB_PARSE_FORMAT_SAMI:
1002 self->parse_line = parse_sami;
1003 sami_context_init (&self->state);
1004 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1006 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1007 self->parse_line = parse_tmplayer;
1008 self->state.max_duration = 5 * GST_SECOND;
1009 return gst_caps_new_simple ("text/plain", NULL);
1010 case GST_SUB_PARSE_FORMAT_MPL2:
1011 self->parse_line = parse_mpl2;
1012 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1013 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1014 self->parse_line = parse_subviewer;
1015 return gst_caps_new_simple ("text/plain", NULL);
1016 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1018 GST_DEBUG ("no subtitle format detected");
1019 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1020 ("The input is not a valid/supported subtitle file"), (NULL));
1026 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1030 discont = GST_BUFFER_IS_DISCONT (buf);
1032 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1033 GST_BUFFER_OFFSET (buf) != self->offset) {
1034 self->offset = GST_BUFFER_OFFSET (buf);
1039 GST_INFO ("discontinuity");
1040 /* flush the parser state */
1041 parser_state_init (&self->state);
1042 g_string_truncate (self->textbuf, 0);
1043 #ifndef GST_DISABLE_XML
1044 sami_context_reset (&self->state);
1046 /* we could set a flag to make sure that the next buffer we push out also
1047 * has the DISCONT flag set, but there's no point really given that it's
1048 * subtitles which are discontinuous by nature. */
1051 self->textbuf = g_string_append_len (self->textbuf,
1052 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1053 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1054 self->next_offset = self->offset;
1056 gst_buffer_unref (buf);
1059 static GstFlowReturn
1060 handle_buffer (GstSubParse * self, GstBuffer * buf)
1062 GstFlowReturn ret = GST_FLOW_OK;
1063 GstCaps *caps = NULL;
1064 gchar *line, *subtitle;
1066 feed_textbuf (self, buf);
1068 /* make sure we know the format */
1069 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1070 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1071 return GST_FLOW_UNEXPECTED;
1073 if (!gst_pad_set_caps (self->srcpad, caps)) {
1074 gst_caps_unref (caps);
1075 return GST_FLOW_UNEXPECTED;
1077 gst_caps_unref (caps);
1080 while ((line = get_next_line (self)) && !self->flushing) {
1083 /* If this is the first line and it contains a UTF-8 BOM drop it */
1084 if (self->first_line && strlen (line) >= 3 &&
1085 (guint8) line[0] == 0xEF && (guint8) line[1] == 0xBB
1086 && (guint8) line[2] == 0xBF) {
1090 self->first_line = FALSE;
1092 /* Set segment on our parser state machine */
1093 self->state.segment = &self->segment;
1094 /* Now parse the line, out of segment lines will just return NULL */
1095 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1096 subtitle = self->parse_line (&self->state, line + offset);
1100 guint subtitle_len = strlen (subtitle);
1102 /* +1 for terminating NUL character */
1103 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1104 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1105 GST_PAD_CAPS (self->srcpad), &buf);
1107 if (ret == GST_FLOW_OK) {
1108 /* copy terminating NUL character as well */
1109 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1110 GST_BUFFER_SIZE (buf) = subtitle_len;
1111 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1112 GST_BUFFER_DURATION (buf) = self->state.duration;
1114 /* in some cases (e.g. tmplayer) we can only determine the duration
1115 * of a text chunk from the timestamp of the next text chunk; in those
1116 * cases, we probably want to limit the duration to something
1117 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1118 * just because nothing else is being said during that time */
1119 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1120 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1121 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1124 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1125 self->state.start_time);
1127 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1128 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1129 GST_TIME_ARGS (self->state.duration));
1131 ret = gst_pad_push (self->srcpad, buf);
1134 /* move this forward (the tmplayer parser needs this) */
1135 if (self->state.duration != GST_CLOCK_TIME_NONE)
1136 self->state.start_time += self->state.duration;
1141 if (ret != GST_FLOW_OK) {
1142 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1151 static GstFlowReturn
1152 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1157 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1159 /* Push newsegment if needed */
1160 if (self->need_segment) {
1161 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1164 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1165 self->segment.rate, self->segment.format,
1166 self->segment.last_stop, self->segment.stop, self->segment.time));
1167 self->need_segment = FALSE;
1170 ret = handle_buffer (self, buf);
1176 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1178 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1179 gboolean ret = FALSE;
1181 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1183 switch (GST_EVENT_TYPE (event)) {
1184 case GST_EVENT_EOS:{
1185 /* Make sure the last subrip chunk is pushed out even
1186 * if the file does not have an empty line at the end */
1187 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1188 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1189 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1190 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1192 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1193 GST_BUFFER_DATA (buf)[0] = '\n';
1194 GST_BUFFER_DATA (buf)[1] = '\n';
1195 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1196 GST_BUFFER_SIZE (buf) = 2;
1197 GST_BUFFER_OFFSET (buf) = self->offset;
1198 gst_sub_parse_chain (pad, buf);
1200 ret = gst_pad_event_default (pad, event);
1203 case GST_EVENT_NEWSEGMENT:
1207 gint64 start, stop, time;
1210 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1213 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1215 if (format == GST_FORMAT_TIME) {
1216 gst_segment_set_newsegment (&self->segment, update, rate, format,
1219 /* if not time format, we'll either start with a 0 timestamp anyway or
1220 * it's following a seek in which case we'll have saved the requested
1221 * seek segment and don't want to overwrite it (remember that on a seek
1222 * we always just seek back to the start in BYTES format and just throw
1223 * away all text that's before the requested position; if the subtitles
1224 * come from an upstream demuxer, it won't be able to handle our BYTES
1225 * seek request and instead send us a newsegment from the seek request
1226 * it received via its video pads instead, so all is fine then too) */
1230 gst_event_unref (event);
1233 case GST_EVENT_FLUSH_START:
1235 self->flushing = TRUE;
1237 ret = gst_pad_event_default (pad, event);
1240 case GST_EVENT_FLUSH_STOP:
1242 self->flushing = FALSE;
1244 ret = gst_pad_event_default (pad, event);
1248 ret = gst_pad_event_default (pad, event);
1252 gst_object_unref (self);
1258 static GstStateChangeReturn
1259 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1261 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1262 GstSubParse *self = GST_SUBPARSE (element);
1264 switch (transition) {
1265 case GST_STATE_CHANGE_READY_TO_PAUSED:
1266 /* format detection will init the parser state */
1268 self->next_offset = 0;
1269 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1270 self->valid_utf8 = TRUE;
1271 self->first_line = TRUE;
1272 g_string_truncate (self->textbuf, 0);
1278 ret = parent_class->change_state (element, transition);
1279 if (ret == GST_STATE_CHANGE_FAILURE)
1282 switch (transition) {
1283 case GST_STATE_CHANGE_PAUSED_TO_READY:
1284 parser_state_dispose (&self->state);
1285 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1298 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1299 * also, give different subtitle formats really different types */
1300 static GstStaticCaps mpl2_caps =
1301 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1302 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1304 static GstStaticCaps tmp_caps =
1305 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1306 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1308 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1309 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1311 #ifndef GST_DISABLE_XML
1312 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1313 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1317 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1319 GstSubParseFormat format;
1324 if (!(data = gst_type_find_peek (tf, 0, 36)))
1327 /* make sure string passed to _autodetect() is NUL-terminated */
1328 str = g_strndup ((gchar *) data, 35);
1329 format = gst_sub_parse_data_format_autodetect (str);
1333 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1334 GST_DEBUG ("MicroDVD format detected");
1337 case GST_SUB_PARSE_FORMAT_SUBRIP:
1338 GST_DEBUG ("SubRip format detected");
1341 case GST_SUB_PARSE_FORMAT_MPSUB:
1342 GST_DEBUG ("MPSub format detected");
1345 #ifndef GST_DISABLE_XML
1346 case GST_SUB_PARSE_FORMAT_SAMI:
1347 GST_DEBUG ("SAMI (time-based) format detected");
1351 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1352 GST_DEBUG ("TMPlayer (time based) format detected");
1355 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1356 * returning a high probability (however, since we registered our
1357 * typefinder here with a rank of MARGINAL we should pretty much only
1358 * be called if most other typefinders have already run */
1359 case GST_SUB_PARSE_FORMAT_MPL2:
1360 GST_DEBUG ("MPL2 (time based) format detected");
1363 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1364 GST_DEBUG ("SubViewer format detected");
1368 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1369 GST_DEBUG ("no subtitle format detected");
1373 /* if we're here, it's ok */
1374 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1378 plugin_init (GstPlugin * plugin)
1380 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1384 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1386 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1387 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1390 if (!gst_element_register (plugin, "subparse",
1391 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1392 !gst_element_register (plugin, "ssaparse",
1393 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1400 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1404 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)