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-9]){0,3}(\x0d)?\x0a"
917 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
918 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
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 (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
926 GST_LOG ("MicroDVD (frame based) format detected");
927 return GST_SUB_PARSE_FORMAT_MDVDSUB;
929 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
930 GST_LOG ("SubRip (time based) format detected");
931 return GST_SUB_PARSE_FORMAT_SUBRIP;
934 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
935 GST_LOG ("MPSub (time based) format detected");
936 return GST_SUB_PARSE_FORMAT_MPSUB;
938 #ifndef GST_DISABLE_XML
939 if (strstr (match_str, "<SAMI>") != NULL ||
940 strstr (match_str, "<sami>") != NULL) {
941 GST_LOG ("SAMI (time based) format detected");
942 return GST_SUB_PARSE_FORMAT_SAMI;
945 /* we're boldly assuming the first subtitle appears within the first hour */
946 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
947 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
948 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
949 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
950 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
951 GST_LOG ("TMPlayer (time based) format detected");
952 return GST_SUB_PARSE_FORMAT_TMPLAYER;
954 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
955 GST_LOG ("MPL2 (time based) format detected");
956 return GST_SUB_PARSE_FORMAT_MPL2;
958 if (strstr (match_str, "[INFORMATION]") != NULL) {
959 GST_LOG ("SubViewer (time based) format detected");
960 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
963 GST_DEBUG ("no subtitle format detected");
964 return GST_SUB_PARSE_FORMAT_UNKNOWN;
968 gst_sub_parse_format_autodetect (GstSubParse * self)
971 GstSubParseFormat format;
973 if (strlen (self->textbuf->str) < 35) {
974 GST_DEBUG ("File too small to be a subtitles file");
978 data = g_strndup (self->textbuf->str, 35);
979 format = gst_sub_parse_data_format_autodetect (data);
982 self->parser_type = format;
983 parser_state_init (&self->state);
986 case GST_SUB_PARSE_FORMAT_MDVDSUB:
987 self->parse_line = parse_mdvdsub;
988 return gst_caps_new_simple ("text/x-pango-markup", NULL);
989 case GST_SUB_PARSE_FORMAT_SUBRIP:
990 self->parse_line = parse_subrip;
991 return gst_caps_new_simple ("text/x-pango-markup", NULL);
992 case GST_SUB_PARSE_FORMAT_MPSUB:
993 self->parse_line = parse_mpsub;
994 return gst_caps_new_simple ("text/plain", NULL);
995 #ifndef GST_DISABLE_XML
996 case GST_SUB_PARSE_FORMAT_SAMI:
997 self->parse_line = parse_sami;
998 sami_context_init (&self->state);
999 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1001 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1002 self->parse_line = parse_tmplayer;
1003 self->state.max_duration = 5 * GST_SECOND;
1004 return gst_caps_new_simple ("text/plain", NULL);
1005 case GST_SUB_PARSE_FORMAT_MPL2:
1006 self->parse_line = parse_mpl2;
1007 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1008 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1009 self->parse_line = parse_subviewer;
1010 return gst_caps_new_simple ("text/plain", NULL);
1011 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1013 GST_DEBUG ("no subtitle format detected");
1014 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1015 ("The input is not a valid/supported subtitle file"), (NULL));
1021 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1025 discont = GST_BUFFER_IS_DISCONT (buf);
1027 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1028 GST_BUFFER_OFFSET (buf) != self->offset) {
1029 self->offset = GST_BUFFER_OFFSET (buf);
1034 GST_INFO ("discontinuity");
1035 /* flush the parser state */
1036 parser_state_init (&self->state);
1037 g_string_truncate (self->textbuf, 0);
1038 #ifndef GST_DISABLE_XML
1039 sami_context_reset (&self->state);
1041 /* we could set a flag to make sure that the next buffer we push out also
1042 * has the DISCONT flag set, but there's no point really given that it's
1043 * subtitles which are discontinuous by nature. */
1046 self->textbuf = g_string_append_len (self->textbuf,
1047 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1048 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1049 self->next_offset = self->offset;
1051 gst_buffer_unref (buf);
1054 static GstFlowReturn
1055 handle_buffer (GstSubParse * self, GstBuffer * buf)
1057 GstFlowReturn ret = GST_FLOW_OK;
1058 GstCaps *caps = NULL;
1059 gchar *line, *subtitle;
1061 feed_textbuf (self, buf);
1063 /* make sure we know the format */
1064 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1065 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1066 return GST_FLOW_UNEXPECTED;
1068 if (!gst_pad_set_caps (self->srcpad, caps)) {
1069 gst_caps_unref (caps);
1070 return GST_FLOW_UNEXPECTED;
1072 gst_caps_unref (caps);
1075 while ((line = get_next_line (self)) && !self->flushing) {
1076 /* Set segment on our parser state machine */
1077 self->state.segment = &self->segment;
1078 /* Now parse the line, out of segment lines will just return NULL */
1079 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
1080 subtitle = self->parse_line (&self->state, line);
1084 guint subtitle_len = strlen (subtitle);
1086 /* +1 for terminating NUL character */
1087 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1088 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1089 GST_PAD_CAPS (self->srcpad), &buf);
1091 if (ret == GST_FLOW_OK) {
1092 /* copy terminating NUL character as well */
1093 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1094 GST_BUFFER_SIZE (buf) = subtitle_len;
1095 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1096 GST_BUFFER_DURATION (buf) = self->state.duration;
1098 /* in some cases (e.g. tmplayer) we can only determine the duration
1099 * of a text chunk from the timestamp of the next text chunk; in those
1100 * cases, we probably want to limit the duration to something
1101 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1102 * just because nothing else is being said during that time */
1103 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1104 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1105 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1108 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1109 self->state.start_time);
1111 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1112 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1113 GST_TIME_ARGS (self->state.duration));
1115 ret = gst_pad_push (self->srcpad, buf);
1118 /* move this forward (the tmplayer parser needs this) */
1119 if (self->state.duration != GST_CLOCK_TIME_NONE)
1120 self->state.start_time += self->state.duration;
1125 if (ret != GST_FLOW_OK) {
1126 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1135 static GstFlowReturn
1136 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1141 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1143 /* Push newsegment if needed */
1144 if (self->need_segment) {
1145 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1148 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1149 self->segment.rate, self->segment.format,
1150 self->segment.last_stop, self->segment.stop, self->segment.time));
1151 self->need_segment = FALSE;
1154 ret = handle_buffer (self, buf);
1160 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1162 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1163 gboolean ret = FALSE;
1165 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1167 switch (GST_EVENT_TYPE (event)) {
1168 case GST_EVENT_EOS:{
1169 /* Make sure the last subrip chunk is pushed out even
1170 * if the file does not have an empty line at the end */
1171 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1172 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1173 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1174 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1176 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1177 GST_BUFFER_DATA (buf)[0] = '\n';
1178 GST_BUFFER_DATA (buf)[1] = '\n';
1179 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1180 GST_BUFFER_SIZE (buf) = 2;
1181 GST_BUFFER_OFFSET (buf) = self->offset;
1182 gst_sub_parse_chain (pad, buf);
1184 ret = gst_pad_event_default (pad, event);
1187 case GST_EVENT_NEWSEGMENT:
1191 gint64 start, stop, time;
1194 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1197 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1199 if (format == GST_FORMAT_TIME) {
1200 gst_segment_set_newsegment (&self->segment, update, rate, format,
1203 /* if not time format, we'll either start with a 0 timestamp anyway or
1204 * it's following a seek in which case we'll have saved the requested
1205 * seek segment and don't want to overwrite it (remember that on a seek
1206 * we always just seek back to the start in BYTES format and just throw
1207 * away all text that's before the requested position; if the subtitles
1208 * come from an upstream demuxer, it won't be able to handle our BYTES
1209 * seek request and instead send us a newsegment from the seek request
1210 * it received via its video pads instead, so all is fine then too) */
1214 gst_event_unref (event);
1217 case GST_EVENT_FLUSH_START:
1219 self->flushing = TRUE;
1221 ret = gst_pad_event_default (pad, event);
1224 case GST_EVENT_FLUSH_STOP:
1226 self->flushing = FALSE;
1228 ret = gst_pad_event_default (pad, event);
1232 ret = gst_pad_event_default (pad, event);
1236 gst_object_unref (self);
1242 static GstStateChangeReturn
1243 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1245 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1246 GstSubParse *self = GST_SUBPARSE (element);
1248 switch (transition) {
1249 case GST_STATE_CHANGE_READY_TO_PAUSED:
1250 /* format detection will init the parser state */
1252 self->next_offset = 0;
1253 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1254 self->valid_utf8 = TRUE;
1255 g_string_truncate (self->textbuf, 0);
1261 ret = parent_class->change_state (element, transition);
1262 if (ret == GST_STATE_CHANGE_FAILURE)
1265 switch (transition) {
1266 case GST_STATE_CHANGE_PAUSED_TO_READY:
1267 parser_state_dispose (&self->state);
1268 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1281 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1282 * also, give different subtitle formats really different types */
1283 static GstStaticCaps mpl2_caps =
1284 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1285 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1287 static GstStaticCaps tmp_caps =
1288 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1289 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1291 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1292 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1294 #ifndef GST_DISABLE_XML
1295 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1296 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1300 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1302 GstSubParseFormat format;
1307 if (!(data = gst_type_find_peek (tf, 0, 36)))
1310 /* make sure string passed to _autodetect() is NUL-terminated */
1311 str = g_strndup ((gchar *) data, 35);
1312 format = gst_sub_parse_data_format_autodetect (str);
1316 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1317 GST_DEBUG ("MicroDVD format detected");
1320 case GST_SUB_PARSE_FORMAT_SUBRIP:
1321 GST_DEBUG ("SubRip format detected");
1324 case GST_SUB_PARSE_FORMAT_MPSUB:
1325 GST_DEBUG ("MPSub format detected");
1328 #ifndef GST_DISABLE_XML
1329 case GST_SUB_PARSE_FORMAT_SAMI:
1330 GST_DEBUG ("SAMI (time-based) format detected");
1334 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1335 GST_DEBUG ("TMPlayer (time based) format detected");
1338 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1339 * returning a high probability (however, since we registered our
1340 * typefinder here with a rank of MARGINAL we should pretty much only
1341 * be called if most other typefinders have already run */
1342 case GST_SUB_PARSE_FORMAT_MPL2:
1343 GST_DEBUG ("MPL2 (time based) format detected");
1346 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1347 GST_DEBUG ("SubViewer format detected");
1351 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1352 GST_DEBUG ("no subtitle format detected");
1356 /* if we're here, it's ok */
1357 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1361 plugin_init (GstPlugin * plugin)
1363 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1367 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1369 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1370 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1373 if (!gst_element_register (plugin, "subparse",
1374 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1375 !gst_element_register (plugin, "ssaparse",
1376 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1383 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1387 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)