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;
146 if (subparse->detected_encoding) {
147 g_free (subparse->detected_encoding);
148 subparse->detected_encoding = NULL;
151 if (subparse->adapter) {
152 gst_object_unref (subparse->adapter);
153 subparse->adapter = NULL;
156 if (subparse->textbuf) {
157 g_string_free (subparse->textbuf, TRUE);
158 subparse->textbuf = NULL;
160 #ifndef GST_DISABLE_XML
161 sami_context_deinit (&subparse->state);
164 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
168 gst_sub_parse_class_init (GstSubParseClass * klass)
170 GObjectClass *object_class = G_OBJECT_CLASS (klass);
171 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
173 parent_class = g_type_class_peek_parent (klass);
175 object_class->dispose = gst_sub_parse_dispose;
176 object_class->set_property = gst_sub_parse_set_property;
177 object_class->get_property = gst_sub_parse_get_property;
179 element_class->change_state = gst_sub_parse_change_state;
181 g_object_class_install_property (object_class, PROP_ENCODING,
182 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
183 "Encoding to assume if input subtitles are not in UTF-8 or any other "
184 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
185 "variable will be checked for an encoding to use. If that is not set "
186 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
187 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
191 gst_sub_parse_init (GstSubParse * subparse)
193 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
194 gst_pad_set_chain_function (subparse->sinkpad,
195 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
196 gst_pad_set_event_function (subparse->sinkpad,
197 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
198 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
200 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
201 gst_pad_set_event_function (subparse->srcpad,
202 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
203 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
205 subparse->textbuf = g_string_new (NULL);
206 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
207 subparse->flushing = FALSE;
208 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
209 subparse->need_segment = TRUE;
210 subparse->encoding = g_strdup (DEFAULT_ENCODING);
211 subparse->detected_encoding = NULL;
212 subparse->adapter = gst_adapter_new ();
216 * Source pad functions.
220 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
222 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
223 gboolean ret = FALSE;
225 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
227 switch (GST_EVENT_TYPE (event)) {
231 GstSeekType start_type, stop_type;
236 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
237 &start_type, &start, &stop_type, &stop);
239 if (format != GST_FORMAT_TIME) {
240 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
241 gst_event_unref (event);
245 /* Convert that seek to a seeking in bytes at position 0,
246 FIXME: could use an index */
247 ret = gst_pad_push_event (self->sinkpad,
248 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
249 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
252 /* Apply the seek to our segment */
253 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
254 start_type, start, stop_type, stop, &update);
256 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
259 self->next_offset = 0;
261 self->need_segment = TRUE;
263 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
266 gst_event_unref (event);
270 ret = gst_pad_event_default (pad, event);
275 gst_object_unref (self);
281 gst_sub_parse_set_property (GObject * object, guint prop_id,
282 const GValue * value, GParamSpec * pspec)
284 GstSubParse *subparse = GST_SUBPARSE (object);
286 GST_OBJECT_LOCK (subparse);
289 g_free (subparse->encoding);
290 subparse->encoding = g_value_dup_string (value);
291 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
292 GST_STR_NULL (subparse->encoding));
295 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
298 GST_OBJECT_UNLOCK (subparse);
302 gst_sub_parse_get_property (GObject * object, guint prop_id,
303 GValue * value, GParamSpec * pspec)
305 GstSubParse *subparse = GST_SUBPARSE (object);
307 GST_OBJECT_LOCK (subparse);
310 g_value_set_string (value, subparse->encoding);
313 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
316 GST_OBJECT_UNLOCK (subparse);
320 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
321 gsize * consumed, GError ** err)
327 g_convert_with_fallback (str, len, "UTF-8", encoding, "*", consumed, NULL,
332 /* + 3 to skip UTF-8 BOM if it was added */
334 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
335 && (guint8) ret[2] == 0xBF)
336 g_memmove (ret, ret + 3, len + 1 - 3);
342 detect_encoding (const gchar * str, gsize len)
344 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
345 && (guint8) str[2] == 0xBF)
346 return g_strdup ("UTF-8");
348 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
349 return g_strdup ("UTF-16BE");
351 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
352 return g_strdup ("UTF-16LE");
354 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
355 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
356 return g_strdup ("UTF-32BE");
358 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
359 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
360 return g_strdup ("UTF-32LE");
366 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
369 const gchar *encoding;
375 /* First try any detected encoding */
376 if (self->detected_encoding) {
378 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
383 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
384 encoding, err->message);
385 g_free (self->detected_encoding);
386 self->detected_encoding = NULL;
390 /* Otherwise check if it's UTF8 */
391 if (self->valid_utf8) {
392 if (g_utf8_validate (str, len, NULL)) {
393 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
395 return g_strndup (str, len);
397 GST_INFO_OBJECT (self, "invalid UTF-8!");
398 self->valid_utf8 = FALSE;
401 /* Else try fallback */
402 encoding = self->encoding;
403 if (encoding == NULL || *encoding == '\0') {
404 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
406 if (encoding == NULL || *encoding == '\0') {
407 /* if local encoding is UTF-8 and no encoding specified
408 * via the environment variable, assume ISO-8859-15 */
409 if (g_get_charset (&encoding)) {
410 encoding = "ISO-8859-15";
414 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
417 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
418 encoding, err->message);
421 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
422 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
425 GST_LOG_OBJECT (self,
426 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
427 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
433 get_next_line (GstSubParse * self)
436 const char *line_end;
438 gboolean have_r = FALSE;
440 line_end = strchr (self->textbuf->str, '\n');
443 /* end-of-line not found; return for more data */
447 /* get rid of '\r' */
448 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
453 line_len = line_end - self->textbuf->str;
454 line = g_strndup (self->textbuf->str, line_len);
455 self->textbuf = g_string_erase (self->textbuf, 0,
456 line_len + (have_r ? 2 : 1));
461 parse_mdvdsub (ParserState * state, const gchar * line)
463 const gchar *line_split;
465 guint start_frame, end_frame;
466 gint64 clip_start = 0, clip_stop = 0;
467 gboolean in_seg = FALSE;
471 /* style variables */
476 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
477 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
478 " format, failed:\n%s", line);
482 /* skip the {%u}{%u} part */
483 line = strchr (line, '}') + 1;
484 line = strchr (line, '}') + 1;
486 /* see if there's a first line with a framerate */
487 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
488 gchar *rest, *end = NULL;
490 rest = g_strdup (line);
491 g_strdelimit (rest, ",", '.');
492 state->fps = g_ascii_strtod (rest, &end);
495 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
500 if (state->fps == 0.0) {
501 /* FIXME: hardcoded for now, is there a better way/assumption? */
502 state->fps = 24000.0 / 1001.0;
503 GST_INFO ("no framerate specified, assuming %f", state->fps);
506 state->start_time = start_frame / state->fps * GST_SECOND;
507 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
509 /* Check our segment start/stop */
510 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
511 state->start_time, state->start_time + state->duration, &clip_start,
514 /* No need to parse that text if it's out of segment */
516 state->start_time = clip_start;
517 state->duration = clip_stop - clip_start;
522 markup = g_string_new (NULL);
527 /* parse style markup */
528 if (strncmp (line, "{y:i}", 5) == 0) {
530 line = strchr (line, '}') + 1;
532 if (strncmp (line, "{y:b}", 5) == 0) {
534 line = strchr (line, '}') + 1;
536 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
537 line = strchr (line, '}') + 1;
539 /* forward slashes at beginning/end signify italics too */
540 if (g_str_has_prefix (line, "/")) {
544 if ((line_split = strchr (line, '|')))
545 line_chunk = g_markup_escape_text (line, line_split - line);
547 line_chunk = g_markup_escape_text (line, strlen (line));
549 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
550 * always at the end of a line or can they span multiple lines?) */
551 if (g_str_has_suffix (line_chunk, "/")) {
552 line_chunk[strlen (line_chunk) - 1] = '\0';
555 markup = g_string_append (markup, "<span");
557 g_string_append (markup, " style=\"italic\"");
559 g_string_append (markup, " weight=\"bold\"");
561 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
562 g_string_append_printf (markup, ">%s</span>", line_chunk);
565 g_string_append (markup, "\n");
566 line = line_split + 1;
572 g_string_free (markup, FALSE);
573 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
574 state->start_time / (double) GST_SECOND,
575 state->duration / (double) GST_SECOND, ret);
580 strip_trailing_newlines (gchar * txt)
586 while (len > 1 && txt[len - 1] == '\n') {
593 /* we want to escape text in general, but retain basic markup like
594 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
595 * just unescape a white list of allowed markups again after
596 * escaping everything (the text between these simple markers isn't
597 * necessarily escaped, so it seems best to do it like this) */
599 subrip_unescape_formatting (gchar * txt)
603 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
604 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
605 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
606 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
608 pos[1] = g_ascii_tolower (pos[4]);
610 /* move NUL terminator as well */
611 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
616 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
617 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
618 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
619 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
622 pos[2] = g_ascii_tolower (pos[5]);
624 /* move NUL terminator as well */
625 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
633 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
637 tag = start + strlen ("<");
641 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
646 GST_LOG ("removing unhandled tag '%s'", start);
648 g_memmove (start, stop, strlen (stop) + 1);
652 /* remove tags we haven't explicitly allowed earlier on, like font tags
655 subrip_remove_unhandled_tags (gchar * txt)
659 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
660 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
661 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
667 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
668 * assumes the input has been escaped and subrip_unescape_formatting() has then
669 * been run over the input! This function adds missing closing markup tags and
670 * removes broken closing tags for tags that have never been opened. */
672 subrip_fix_up_markup (gchar ** p_txt)
674 gchar *cur, *next_tag;
676 guint num_open_tags = 0;
678 g_assert (*p_txt != NULL);
681 while (*cur != '\0') {
682 next_tag = strchr (cur, '<');
683 if (next_tag == NULL)
689 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
690 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
691 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
694 /* it's all good, closing tag which is open */
702 if (num_open_tags == G_N_ELEMENTS (open_tags))
703 return; /* something dodgy is going on, stop parsing */
704 open_tags[num_open_tags] = *next_tag;
708 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
709 g_assert_not_reached ();
715 if (num_open_tags > 0) {
718 s = g_string_new (*p_txt);
719 while (num_open_tags > 0) {
720 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
721 g_string_append_c (s, '<');
722 g_string_append_c (s, '/');
723 g_string_append_c (s, open_tags[num_open_tags - 1]);
724 g_string_append_c (s, '>');
728 *p_txt = g_string_free (s, FALSE);
733 parse_subrip (ParserState * state, const gchar * line)
735 guint h1, m1, s1, ms1;
736 guint h2, m2, s2, ms2;
740 switch (state->state) {
742 /* looking for a single integer */
743 if (sscanf (line, "%u", &subnum) == 1)
747 /* looking for start_time --> end_time */
748 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
749 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
752 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
755 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
756 ms2 * GST_MSECOND - state->start_time;
758 GST_DEBUG ("error parsing subrip time line");
764 /* No need to parse that text if it's out of segment */
765 gint64 clip_start = 0, clip_stop = 0;
766 gboolean in_seg = FALSE;
768 /* Check our segment start/stop */
769 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
770 state->start_time, state->start_time + state->duration,
771 &clip_start, &clip_stop);
774 state->start_time = clip_start;
775 state->duration = clip_stop - clip_start;
781 /* looking for subtitle text; empty line ends this subtitle entry */
783 g_string_append_c (state->buf, '\n');
784 g_string_append (state->buf, line);
785 if (strlen (line) == 0) {
786 ret = g_markup_escape_text (state->buf->str, state->buf->len);
787 g_string_truncate (state->buf, 0);
789 subrip_unescape_formatting (ret);
790 subrip_remove_unhandled_tags (ret);
791 strip_trailing_newlines (ret);
792 subrip_fix_up_markup (&ret);
797 g_return_val_if_reached (NULL);
802 subviewer_unescape_newlines (gchar * read)
806 /* Replace all occurences of '[br]' with a newline as version 2
807 * of the subviewer format uses this for newlines */
809 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
813 if (strncmp (read, "[br]", 4) == 0) {
827 parse_subviewer (ParserState * state, const gchar * line)
829 guint h1, m1, s1, ms1;
830 guint h2, m2, s2, ms2;
833 /* TODO: Maybe also parse the fields in the header, especially DELAY.
834 * For examples see the unit test or
835 * http://www.doom9.org/index.html?/sub.htm */
837 switch (state->state) {
839 /* looking for start_time,end_time */
840 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
841 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
844 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
847 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
848 ms2 * GST_MSECOND - state->start_time;
853 /* No need to parse that text if it's out of segment */
854 gint64 clip_start = 0, clip_stop = 0;
855 gboolean in_seg = FALSE;
857 /* Check our segment start/stop */
858 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
859 state->start_time, state->start_time + state->duration,
860 &clip_start, &clip_stop);
863 state->start_time = clip_start;
864 state->duration = clip_stop - clip_start;
870 /* looking for subtitle text; empty line ends this subtitle entry */
872 g_string_append_c (state->buf, '\n');
873 g_string_append (state->buf, line);
874 if (strlen (line) == 0) {
875 ret = g_strdup (state->buf->str);
876 subviewer_unescape_newlines (ret);
877 strip_trailing_newlines (ret);
878 g_string_truncate (state->buf, 0);
884 g_assert_not_reached ();
890 parse_mpsub (ParserState * state, const gchar * line)
895 switch (state->state) {
897 /* looking for two floats (offset, duration) */
898 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
900 state->start_time += state->duration + GST_SECOND * t1;
901 state->duration = GST_SECOND * t2;
905 { /* No need to parse that text if it's out of segment */
906 gint64 clip_start = 0, clip_stop = 0;
907 gboolean in_seg = FALSE;
909 /* Check our segment start/stop */
910 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
911 state->start_time, state->start_time + state->duration,
912 &clip_start, &clip_stop);
915 state->start_time = clip_start;
916 state->duration = clip_stop - clip_start;
922 /* looking for subtitle text; empty line ends this
925 g_string_append_c (state->buf, '\n');
926 g_string_append (state->buf, line);
927 if (strlen (line) == 0) {
928 ret = g_strdup (state->buf->str);
929 g_string_truncate (state->buf, 0);
935 g_assert_not_reached ();
941 parser_state_init (ParserState * state)
943 GST_DEBUG ("initialising parser");
946 g_string_truncate (state->buf, 0);
948 state->buf = g_string_new (NULL);
951 state->start_time = 0;
953 state->max_duration = 0; /* no limit */
955 state->segment = NULL;
959 parser_state_dispose (ParserState * state)
962 g_string_free (state->buf, TRUE);
965 #ifndef GST_DISABLE_XML
966 if (state->user_data) {
967 sami_context_reset (state);
973 * FIXME: maybe we should pass along a second argument, the preceding
974 * text buffer, because that is how this originally worked, even though
975 * I don't really see the use of that.
978 static GstSubParseFormat
979 gst_sub_parse_data_format_autodetect (gchar * match_str)
981 static gboolean need_init_regexps = TRUE;
982 static regex_t mdvd_rx;
983 static regex_t subrip_rx;
986 /* initialize the regexps used the first time around */
987 if (need_init_regexps) {
991 need_init_regexps = FALSE;
992 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
993 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
994 (err = regcomp (&subrip_rx, "^([ 0-9]){0,3}[0-9](\x0d)?\x0a"
995 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]"
996 " --> ([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]",
997 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
998 regerror (err, &subrip_rx, errstr, 127);
999 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
1003 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
1004 GST_LOG ("MicroDVD (frame based) format detected");
1005 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1007 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
1008 GST_LOG ("SubRip (time based) format detected");
1009 return GST_SUB_PARSE_FORMAT_SUBRIP;
1012 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1013 GST_LOG ("MPSub (time based) format detected");
1014 return GST_SUB_PARSE_FORMAT_MPSUB;
1016 #ifndef GST_DISABLE_XML
1017 if (strstr (match_str, "<SAMI>") != NULL ||
1018 strstr (match_str, "<sami>") != NULL) {
1019 GST_LOG ("SAMI (time based) format detected");
1020 return GST_SUB_PARSE_FORMAT_SAMI;
1023 /* we're boldly assuming the first subtitle appears within the first hour */
1024 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1025 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1026 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1027 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1028 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1029 GST_LOG ("TMPlayer (time based) format detected");
1030 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1032 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1033 GST_LOG ("MPL2 (time based) format detected");
1034 return GST_SUB_PARSE_FORMAT_MPL2;
1036 if (strstr (match_str, "[INFORMATION]") != NULL) {
1037 GST_LOG ("SubViewer (time based) format detected");
1038 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1041 GST_DEBUG ("no subtitle format detected");
1042 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1046 gst_sub_parse_format_autodetect (GstSubParse * self)
1049 GstSubParseFormat format;
1051 if (strlen (self->textbuf->str) < 35) {
1052 GST_DEBUG ("File too small to be a subtitles file");
1056 data = g_strndup (self->textbuf->str, 35);
1057 format = gst_sub_parse_data_format_autodetect (data);
1060 self->parser_type = format;
1061 parser_state_init (&self->state);
1064 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1065 self->parse_line = parse_mdvdsub;
1066 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1067 case GST_SUB_PARSE_FORMAT_SUBRIP:
1068 self->parse_line = parse_subrip;
1069 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1070 case GST_SUB_PARSE_FORMAT_MPSUB:
1071 self->parse_line = parse_mpsub;
1072 return gst_caps_new_simple ("text/plain", NULL);
1073 #ifndef GST_DISABLE_XML
1074 case GST_SUB_PARSE_FORMAT_SAMI:
1075 self->parse_line = parse_sami;
1076 sami_context_init (&self->state);
1077 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1079 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1080 self->parse_line = parse_tmplayer;
1081 self->state.max_duration = 5 * GST_SECOND;
1082 return gst_caps_new_simple ("text/plain", NULL);
1083 case GST_SUB_PARSE_FORMAT_MPL2:
1084 self->parse_line = parse_mpl2;
1085 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1086 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1087 self->parse_line = parse_subviewer;
1088 return gst_caps_new_simple ("text/plain", NULL);
1089 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1091 GST_DEBUG ("no subtitle format detected");
1092 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1093 ("The input is not a valid/supported subtitle file"), (NULL));
1099 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1103 gchar *input = NULL;
1105 discont = GST_BUFFER_IS_DISCONT (buf);
1107 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1108 GST_BUFFER_OFFSET (buf) != self->offset) {
1109 self->offset = GST_BUFFER_OFFSET (buf);
1114 GST_INFO ("discontinuity");
1115 /* flush the parser state */
1116 parser_state_init (&self->state);
1117 g_string_truncate (self->textbuf, 0);
1118 gst_adapter_clear (self->adapter);
1119 #ifndef GST_DISABLE_XML
1120 sami_context_reset (&self->state);
1122 /* we could set a flag to make sure that the next buffer we push out also
1123 * has the DISCONT flag set, but there's no point really given that it's
1124 * subtitles which are discontinuous by nature. */
1127 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1128 self->next_offset = self->offset;
1130 gst_adapter_push (self->adapter, buf);
1133 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1134 gst_adapter_available (self->adapter)),
1135 (gsize) gst_adapter_available (self->adapter), &consumed);
1137 if (input && consumed > 0) {
1138 self->textbuf = g_string_append (self->textbuf, input);
1139 gst_adapter_flush (self->adapter, consumed);
1145 static GstFlowReturn
1146 handle_buffer (GstSubParse * self, GstBuffer * buf)
1148 GstFlowReturn ret = GST_FLOW_OK;
1149 GstCaps *caps = NULL;
1150 gchar *line, *subtitle;
1152 if (self->first_buffer) {
1153 self->detected_encoding =
1154 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1155 GST_BUFFER_SIZE (buf));
1156 self->first_buffer = FALSE;
1159 feed_textbuf (self, buf);
1161 /* make sure we know the format */
1162 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1163 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1164 return GST_FLOW_UNEXPECTED;
1166 if (!gst_pad_set_caps (self->srcpad, caps)) {
1167 gst_caps_unref (caps);
1168 return GST_FLOW_UNEXPECTED;
1170 gst_caps_unref (caps);
1173 while ((line = get_next_line (self)) && !self->flushing) {
1176 /* Set segment on our parser state machine */
1177 self->state.segment = &self->segment;
1178 /* Now parse the line, out of segment lines will just return NULL */
1179 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1180 subtitle = self->parse_line (&self->state, line + offset);
1184 guint subtitle_len = strlen (subtitle);
1186 /* +1 for terminating NUL character */
1187 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1188 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1189 GST_PAD_CAPS (self->srcpad), &buf);
1191 if (ret == GST_FLOW_OK) {
1192 /* copy terminating NUL character as well */
1193 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1194 GST_BUFFER_SIZE (buf) = subtitle_len;
1195 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1196 GST_BUFFER_DURATION (buf) = self->state.duration;
1198 /* in some cases (e.g. tmplayer) we can only determine the duration
1199 * of a text chunk from the timestamp of the next text chunk; in those
1200 * cases, we probably want to limit the duration to something
1201 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1202 * just because nothing else is being said during that time */
1203 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1204 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1205 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1208 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1209 self->state.start_time);
1211 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1212 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1213 GST_TIME_ARGS (self->state.duration));
1215 ret = gst_pad_push (self->srcpad, buf);
1218 /* move this forward (the tmplayer parser needs this) */
1219 if (self->state.duration != GST_CLOCK_TIME_NONE)
1220 self->state.start_time += self->state.duration;
1225 if (ret != GST_FLOW_OK) {
1226 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1235 static GstFlowReturn
1236 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1241 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1243 /* Push newsegment if needed */
1244 if (self->need_segment) {
1245 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1248 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1249 self->segment.rate, self->segment.format,
1250 self->segment.last_stop, self->segment.stop, self->segment.time));
1251 self->need_segment = FALSE;
1254 ret = handle_buffer (self, buf);
1260 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1262 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1263 gboolean ret = FALSE;
1265 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1267 switch (GST_EVENT_TYPE (event)) {
1268 case GST_EVENT_EOS:{
1269 /* Make sure the last subrip chunk is pushed out even
1270 * if the file does not have an empty line at the end */
1271 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1272 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1273 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1274 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1276 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1277 GST_BUFFER_DATA (buf)[0] = '\n';
1278 GST_BUFFER_DATA (buf)[1] = '\n';
1279 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1280 GST_BUFFER_SIZE (buf) = 2;
1281 GST_BUFFER_OFFSET (buf) = self->offset;
1282 gst_sub_parse_chain (pad, buf);
1284 ret = gst_pad_event_default (pad, event);
1287 case GST_EVENT_NEWSEGMENT:
1291 gint64 start, stop, time;
1294 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1297 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1299 if (format == GST_FORMAT_TIME) {
1300 gst_segment_set_newsegment (&self->segment, update, rate, format,
1303 /* if not time format, we'll either start with a 0 timestamp anyway or
1304 * it's following a seek in which case we'll have saved the requested
1305 * seek segment and don't want to overwrite it (remember that on a seek
1306 * we always just seek back to the start in BYTES format and just throw
1307 * away all text that's before the requested position; if the subtitles
1308 * come from an upstream demuxer, it won't be able to handle our BYTES
1309 * seek request and instead send us a newsegment from the seek request
1310 * it received via its video pads instead, so all is fine then too) */
1314 gst_event_unref (event);
1317 case GST_EVENT_FLUSH_START:
1319 self->flushing = TRUE;
1321 ret = gst_pad_event_default (pad, event);
1324 case GST_EVENT_FLUSH_STOP:
1326 self->flushing = FALSE;
1328 ret = gst_pad_event_default (pad, event);
1332 ret = gst_pad_event_default (pad, event);
1336 gst_object_unref (self);
1342 static GstStateChangeReturn
1343 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1345 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1346 GstSubParse *self = GST_SUBPARSE (element);
1348 switch (transition) {
1349 case GST_STATE_CHANGE_READY_TO_PAUSED:
1350 /* format detection will init the parser state */
1352 self->next_offset = 0;
1353 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1354 self->valid_utf8 = TRUE;
1355 self->first_buffer = TRUE;
1356 g_free (self->detected_encoding);
1357 self->detected_encoding = NULL;
1358 g_string_truncate (self->textbuf, 0);
1359 gst_adapter_clear (self->adapter);
1365 ret = parent_class->change_state (element, transition);
1366 if (ret == GST_STATE_CHANGE_FAILURE)
1369 switch (transition) {
1370 case GST_STATE_CHANGE_PAUSED_TO_READY:
1371 parser_state_dispose (&self->state);
1372 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1385 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1386 * also, give different subtitle formats really different types */
1387 static GstStaticCaps mpl2_caps =
1388 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1389 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1391 static GstStaticCaps tmp_caps =
1392 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1393 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1395 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1396 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1398 #ifndef GST_DISABLE_XML
1399 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1400 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1404 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1406 GstSubParseFormat format;
1410 gchar *encoding = NULL;
1412 if (!(data = gst_type_find_peek (tf, 0, 129)))
1415 /* make sure string passed to _autodetect() is NUL-terminated */
1416 str = g_malloc0 (129);
1417 memcpy (str, data, 128);
1419 if ((encoding = detect_encoding (str, 128)) != NULL) {
1420 gchar *converted_str;
1424 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
1425 if (converted_str == NULL) {
1426 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
1435 str = converted_str;
1438 format = gst_sub_parse_data_format_autodetect (str);
1442 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1443 GST_DEBUG ("MicroDVD format detected");
1446 case GST_SUB_PARSE_FORMAT_SUBRIP:
1447 GST_DEBUG ("SubRip format detected");
1450 case GST_SUB_PARSE_FORMAT_MPSUB:
1451 GST_DEBUG ("MPSub format detected");
1454 #ifndef GST_DISABLE_XML
1455 case GST_SUB_PARSE_FORMAT_SAMI:
1456 GST_DEBUG ("SAMI (time-based) format detected");
1460 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1461 GST_DEBUG ("TMPlayer (time based) format detected");
1464 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1465 * returning a high probability (however, since we registered our
1466 * typefinder here with a rank of MARGINAL we should pretty much only
1467 * be called if most other typefinders have already run */
1468 case GST_SUB_PARSE_FORMAT_MPL2:
1469 GST_DEBUG ("MPL2 (time based) format detected");
1472 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1473 GST_DEBUG ("SubViewer format detected");
1477 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1478 GST_DEBUG ("no subtitle format detected");
1482 /* if we're here, it's ok */
1483 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1487 plugin_init (GstPlugin * plugin)
1489 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1493 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1495 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1496 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1499 if (!gst_element_register (plugin, "subparse",
1500 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1501 !gst_element_register (plugin, "ssaparse",
1502 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1509 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1513 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)