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>
32 #include "gstsubparse.h"
33 #include "gstssaparse.h"
34 #include "samiparse.h"
35 #include "tmplayerparse.h"
36 #include "mpl2parse.h"
38 GST_DEBUG_CATEGORY (sub_parse_debug);
40 #define DEFAULT_ENCODING NULL
49 gst_sub_parse_set_property (GObject * object, guint prop_id,
50 const GValue * value, GParamSpec * pspec);
52 gst_sub_parse_get_property (GObject * object, guint prop_id,
53 GValue * value, GParamSpec * pspec);
56 static const GstElementDetails sub_parse_details =
57 GST_ELEMENT_DETAILS ("Subtitle parser",
58 "Codec/Parser/Subtitle",
59 "Parses subtitle (.sub) files into text streams",
60 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
61 "Ronald S. Bultje <rbultje@ronald.bitfreak.net>");
63 #ifndef GST_DISABLE_XML
64 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
67 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
68 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2")
71 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
74 GST_STATIC_CAPS ("application/x-subtitle")
78 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
81 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
84 static void gst_sub_parse_base_init (GstSubParseClass * klass);
85 static void gst_sub_parse_class_init (GstSubParseClass * klass);
86 static void gst_sub_parse_init (GstSubParse * subparse);
88 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
89 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
91 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
92 GstStateChange transition);
94 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
96 static GstElementClass *parent_class = NULL;
99 gst_sub_parse_get_type (void)
101 static GType sub_parse_type = 0;
103 if (!sub_parse_type) {
104 static const GTypeInfo sub_parse_info = {
105 sizeof (GstSubParseClass),
106 (GBaseInitFunc) gst_sub_parse_base_init,
108 (GClassInitFunc) gst_sub_parse_class_init,
111 sizeof (GstSubParse),
113 (GInstanceInitFunc) gst_sub_parse_init,
116 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
117 "GstSubParse", &sub_parse_info, 0);
120 return sub_parse_type;
124 gst_sub_parse_base_init (GstSubParseClass * klass)
126 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
128 gst_element_class_add_pad_template (element_class,
129 gst_static_pad_template_get (&sink_templ));
130 gst_element_class_add_pad_template (element_class,
131 gst_static_pad_template_get (&src_templ));
132 gst_element_class_set_details (element_class, &sub_parse_details);
136 gst_sub_parse_dispose (GObject * object)
138 GstSubParse *subparse = GST_SUBPARSE (object);
140 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
142 if (subparse->encoding) {
143 g_free (subparse->encoding);
144 subparse->encoding = NULL;
147 if (subparse->detected_encoding) {
148 g_free (subparse->detected_encoding);
149 subparse->detected_encoding = NULL;
152 if (subparse->adapter) {
153 gst_object_unref (subparse->adapter);
154 subparse->adapter = NULL;
157 if (subparse->textbuf) {
158 g_string_free (subparse->textbuf, TRUE);
159 subparse->textbuf = NULL;
161 #ifndef GST_DISABLE_XML
162 sami_context_deinit (&subparse->state);
165 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
169 gst_sub_parse_class_init (GstSubParseClass * klass)
171 GObjectClass *object_class = G_OBJECT_CLASS (klass);
172 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
174 parent_class = g_type_class_peek_parent (klass);
176 object_class->dispose = gst_sub_parse_dispose;
177 object_class->set_property = gst_sub_parse_set_property;
178 object_class->get_property = gst_sub_parse_get_property;
180 element_class->change_state = gst_sub_parse_change_state;
182 g_object_class_install_property (object_class, PROP_ENCODING,
183 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
184 "Encoding to assume if input subtitles are not in UTF-8 or any other "
185 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
186 "variable will be checked for an encoding to use. If that is not set "
187 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
188 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192 gst_sub_parse_init (GstSubParse * subparse)
194 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
195 gst_pad_set_chain_function (subparse->sinkpad,
196 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
197 gst_pad_set_event_function (subparse->sinkpad,
198 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
199 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
201 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
202 gst_pad_set_event_function (subparse->srcpad,
203 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
204 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
206 subparse->textbuf = g_string_new (NULL);
207 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
208 subparse->flushing = FALSE;
209 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
210 subparse->need_segment = TRUE;
211 subparse->encoding = g_strdup (DEFAULT_ENCODING);
212 subparse->detected_encoding = NULL;
213 subparse->adapter = gst_adapter_new ();
217 * Source pad functions.
221 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
223 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
224 gboolean ret = FALSE;
226 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
228 switch (GST_EVENT_TYPE (event)) {
232 GstSeekType start_type, stop_type;
237 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
238 &start_type, &start, &stop_type, &stop);
240 if (format != GST_FORMAT_TIME) {
241 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
242 gst_event_unref (event);
246 /* Convert that seek to a seeking in bytes at position 0,
247 FIXME: could use an index */
248 ret = gst_pad_push_event (self->sinkpad,
249 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
250 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
253 /* Apply the seek to our segment */
254 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
255 start_type, start, stop_type, stop, &update);
257 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
260 self->next_offset = 0;
262 self->need_segment = TRUE;
264 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
267 gst_event_unref (event);
271 ret = gst_pad_event_default (pad, event);
276 gst_object_unref (self);
282 gst_sub_parse_set_property (GObject * object, guint prop_id,
283 const GValue * value, GParamSpec * pspec)
285 GstSubParse *subparse = GST_SUBPARSE (object);
287 GST_OBJECT_LOCK (subparse);
290 g_free (subparse->encoding);
291 subparse->encoding = g_value_dup_string (value);
292 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
293 GST_STR_NULL (subparse->encoding));
296 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
299 GST_OBJECT_UNLOCK (subparse);
303 gst_sub_parse_get_property (GObject * object, guint prop_id,
304 GValue * value, GParamSpec * pspec)
306 GstSubParse *subparse = GST_SUBPARSE (object);
308 GST_OBJECT_LOCK (subparse);
311 g_value_set_string (value, subparse->encoding);
314 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
317 GST_OBJECT_UNLOCK (subparse);
321 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
322 gsize * consumed, GError ** err)
328 g_convert_with_fallback (str, len, "UTF-8", encoding, "*", consumed, NULL,
333 /* + 3 to skip UTF-8 BOM if it was added */
335 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
336 && (guint8) ret[2] == 0xBF)
337 g_memmove (ret, ret + 3, len + 1 - 3);
343 detect_encoding (const gchar * str, gsize len)
345 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
346 && (guint8) str[2] == 0xBF)
347 return g_strdup ("UTF-8");
349 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
350 return g_strdup ("UTF-16BE");
352 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
353 return g_strdup ("UTF-16LE");
355 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
356 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
357 return g_strdup ("UTF-32BE");
359 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
360 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
361 return g_strdup ("UTF-32LE");
367 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
370 const gchar *encoding;
376 /* First try any detected encoding */
377 if (self->detected_encoding) {
379 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
384 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
385 encoding, err->message);
386 g_free (self->detected_encoding);
387 self->detected_encoding = NULL;
391 /* Otherwise check if it's UTF8 */
392 if (self->valid_utf8) {
393 if (g_utf8_validate (str, len, NULL)) {
394 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
396 return g_strndup (str, len);
398 GST_INFO_OBJECT (self, "invalid UTF-8!");
399 self->valid_utf8 = FALSE;
402 /* Else try fallback */
403 encoding = self->encoding;
404 if (encoding == NULL || *encoding == '\0') {
405 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
407 if (encoding == NULL || *encoding == '\0') {
408 /* if local encoding is UTF-8 and no encoding specified
409 * via the environment variable, assume ISO-8859-15 */
410 if (g_get_charset (&encoding)) {
411 encoding = "ISO-8859-15";
415 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
418 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
419 encoding, err->message);
422 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
423 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
426 GST_LOG_OBJECT (self,
427 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
428 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
434 get_next_line (GstSubParse * self)
437 const char *line_end;
439 gboolean have_r = FALSE;
441 line_end = strchr (self->textbuf->str, '\n');
444 /* end-of-line not found; return for more data */
448 /* get rid of '\r' */
449 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
454 line_len = line_end - self->textbuf->str;
455 line = g_strndup (self->textbuf->str, line_len);
456 self->textbuf = g_string_erase (self->textbuf, 0,
457 line_len + (have_r ? 2 : 1));
462 parse_mdvdsub (ParserState * state, const gchar * line)
464 const gchar *line_split;
466 guint start_frame, end_frame;
467 gint64 clip_start = 0, clip_stop = 0;
468 gboolean in_seg = FALSE;
472 /* style variables */
477 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
478 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
479 " format, failed:\n%s", line);
483 /* skip the {%u}{%u} part */
484 line = strchr (line, '}') + 1;
485 line = strchr (line, '}') + 1;
487 /* see if there's a first line with a framerate */
488 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
489 gchar *rest, *end = NULL;
491 rest = g_strdup (line);
492 g_strdelimit (rest, ",", '.');
493 state->fps = g_ascii_strtod (rest, &end);
496 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
501 if (state->fps == 0.0) {
502 /* FIXME: hardcoded for now, is there a better way/assumption? */
503 state->fps = 24000.0 / 1001.0;
504 GST_INFO ("no framerate specified, assuming %f", state->fps);
507 state->start_time = start_frame / state->fps * GST_SECOND;
508 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
510 /* Check our segment start/stop */
511 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
512 state->start_time, state->start_time + state->duration, &clip_start,
515 /* No need to parse that text if it's out of segment */
517 state->start_time = clip_start;
518 state->duration = clip_stop - clip_start;
523 markup = g_string_new (NULL);
528 /* parse style markup */
529 if (strncmp (line, "{y:i}", 5) == 0) {
531 line = strchr (line, '}') + 1;
533 if (strncmp (line, "{y:b}", 5) == 0) {
535 line = strchr (line, '}') + 1;
537 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
538 line = strchr (line, '}') + 1;
540 /* forward slashes at beginning/end signify italics too */
541 if (g_str_has_prefix (line, "/")) {
545 if ((line_split = strchr (line, '|')))
546 line_chunk = g_markup_escape_text (line, line_split - line);
548 line_chunk = g_markup_escape_text (line, strlen (line));
550 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
551 * always at the end of a line or can they span multiple lines?) */
552 if (g_str_has_suffix (line_chunk, "/")) {
553 line_chunk[strlen (line_chunk) - 1] = '\0';
556 markup = g_string_append (markup, "<span");
558 g_string_append (markup, " style=\"italic\"");
560 g_string_append (markup, " weight=\"bold\"");
562 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
563 g_string_append_printf (markup, ">%s</span>", line_chunk);
566 g_string_append (markup, "\n");
567 line = line_split + 1;
573 g_string_free (markup, FALSE);
574 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
575 state->start_time / (double) GST_SECOND,
576 state->duration / (double) GST_SECOND, ret);
581 strip_trailing_newlines (gchar * txt)
587 while (len > 1 && txt[len - 1] == '\n') {
594 /* we want to escape text in general, but retain basic markup like
595 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
596 * just unescape a white list of allowed markups again after
597 * escaping everything (the text between these simple markers isn't
598 * necessarily escaped, so it seems best to do it like this) */
600 subrip_unescape_formatting (gchar * txt)
604 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
605 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
606 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
607 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
609 pos[1] = g_ascii_tolower (pos[4]);
611 /* move NUL terminator as well */
612 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
617 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
618 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
619 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
620 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
623 pos[2] = g_ascii_tolower (pos[5]);
625 /* move NUL terminator as well */
626 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
634 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
638 tag = start + strlen ("<");
642 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
647 GST_LOG ("removing unhandled tag '%s'", start);
649 g_memmove (start, stop, strlen (stop) + 1);
653 /* remove tags we haven't explicitly allowed earlier on, like font tags
656 subrip_remove_unhandled_tags (gchar * txt)
660 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
661 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
662 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
668 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
669 * assumes the input has been escaped and subrip_unescape_formatting() has then
670 * been run over the input! This function adds missing closing markup tags and
671 * removes broken closing tags for tags that have never been opened. */
673 subrip_fix_up_markup (gchar ** p_txt)
675 gchar *cur, *next_tag;
677 guint num_open_tags = 0;
679 g_assert (*p_txt != NULL);
682 while (*cur != '\0') {
683 next_tag = strchr (cur, '<');
684 if (next_tag == NULL)
690 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
691 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
692 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
695 /* it's all good, closing tag which is open */
703 if (num_open_tags == G_N_ELEMENTS (open_tags))
704 return; /* something dodgy is going on, stop parsing */
705 open_tags[num_open_tags] = *next_tag;
709 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
710 g_assert_not_reached ();
716 if (num_open_tags > 0) {
719 s = g_string_new (*p_txt);
720 while (num_open_tags > 0) {
721 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
722 g_string_append_c (s, '<');
723 g_string_append_c (s, '/');
724 g_string_append_c (s, open_tags[num_open_tags - 1]);
725 g_string_append_c (s, '>');
729 *p_txt = g_string_free (s, FALSE);
734 parse_subrip (ParserState * state, const gchar * line)
736 guint h1, m1, s1, ms1;
737 guint h2, m2, s2, ms2;
741 switch (state->state) {
743 /* looking for a single integer */
744 if (sscanf (line, "%u", &subnum) == 1)
748 /* looking for start_time --> end_time */
749 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
750 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
753 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
756 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
757 ms2 * GST_MSECOND - state->start_time;
759 GST_DEBUG ("error parsing subrip time line");
765 /* No need to parse that text if it's out of segment */
766 gint64 clip_start = 0, clip_stop = 0;
767 gboolean in_seg = FALSE;
769 /* Check our segment start/stop */
770 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
771 state->start_time, state->start_time + state->duration,
772 &clip_start, &clip_stop);
775 state->start_time = clip_start;
776 state->duration = clip_stop - clip_start;
782 /* looking for subtitle text; empty line ends this subtitle entry */
784 g_string_append_c (state->buf, '\n');
785 g_string_append (state->buf, line);
786 if (strlen (line) == 0) {
787 ret = g_markup_escape_text (state->buf->str, state->buf->len);
788 g_string_truncate (state->buf, 0);
790 subrip_unescape_formatting (ret);
791 subrip_remove_unhandled_tags (ret);
792 strip_trailing_newlines (ret);
793 subrip_fix_up_markup (&ret);
798 g_return_val_if_reached (NULL);
803 subviewer_unescape_newlines (gchar * read)
807 /* Replace all occurences of '[br]' with a newline as version 2
808 * of the subviewer format uses this for newlines */
810 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
814 if (strncmp (read, "[br]", 4) == 0) {
828 parse_subviewer (ParserState * state, const gchar * line)
830 guint h1, m1, s1, ms1;
831 guint h2, m2, s2, ms2;
834 /* TODO: Maybe also parse the fields in the header, especially DELAY.
835 * For examples see the unit test or
836 * http://www.doom9.org/index.html?/sub.htm */
838 switch (state->state) {
840 /* looking for start_time,end_time */
841 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
842 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
845 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
848 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
849 ms2 * GST_MSECOND - state->start_time;
854 /* No need to parse that text if it's out of segment */
855 gint64 clip_start = 0, clip_stop = 0;
856 gboolean in_seg = FALSE;
858 /* Check our segment start/stop */
859 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
860 state->start_time, state->start_time + state->duration,
861 &clip_start, &clip_stop);
864 state->start_time = clip_start;
865 state->duration = clip_stop - clip_start;
871 /* looking for subtitle text; empty line ends this subtitle entry */
873 g_string_append_c (state->buf, '\n');
874 g_string_append (state->buf, line);
875 if (strlen (line) == 0) {
876 ret = g_strdup (state->buf->str);
877 subviewer_unescape_newlines (ret);
878 strip_trailing_newlines (ret);
879 g_string_truncate (state->buf, 0);
885 g_assert_not_reached ();
891 parse_mpsub (ParserState * state, const gchar * line)
896 switch (state->state) {
898 /* looking for two floats (offset, duration) */
899 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
901 state->start_time += state->duration + GST_SECOND * t1;
902 state->duration = GST_SECOND * t2;
906 { /* No need to parse that text if it's out of segment */
907 gint64 clip_start = 0, clip_stop = 0;
908 gboolean in_seg = FALSE;
910 /* Check our segment start/stop */
911 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
912 state->start_time, state->start_time + state->duration,
913 &clip_start, &clip_stop);
916 state->start_time = clip_start;
917 state->duration = clip_stop - clip_start;
923 /* looking for subtitle text; empty line ends this
926 g_string_append_c (state->buf, '\n');
927 g_string_append (state->buf, line);
928 if (strlen (line) == 0) {
929 ret = g_strdup (state->buf->str);
930 g_string_truncate (state->buf, 0);
936 g_assert_not_reached ();
942 parser_state_init (ParserState * state)
944 GST_DEBUG ("initialising parser");
947 g_string_truncate (state->buf, 0);
949 state->buf = g_string_new (NULL);
952 state->start_time = 0;
954 state->max_duration = 0; /* no limit */
956 state->segment = NULL;
960 parser_state_dispose (ParserState * state)
963 g_string_free (state->buf, TRUE);
966 #ifndef GST_DISABLE_XML
967 if (state->user_data) {
968 sami_context_reset (state);
973 /* regex type enum */
976 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
977 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
978 GST_SUB_PARSE_REGEX_SUBRIP = 2,
982 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
984 gpointer result = NULL;
987 case GST_SUB_PARSE_REGEX_MDVDSUB:
989 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}", 0, 0, &gerr);
990 if (result == NULL) {
991 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
995 case GST_SUB_PARSE_REGEX_SUBRIP:
996 result = (gpointer) g_regex_new ("^([ 0-9]){0,3}[0-9](\x0d)?\x0a"
997 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]"
998 " --> ([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9],[ 0-9]{2}[0-9]",
1000 if (result == NULL) {
1001 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1002 g_error_free (gerr);
1006 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1012 * FIXME: maybe we should pass along a second argument, the preceding
1013 * text buffer, because that is how this originally worked, even though
1014 * I don't really see the use of that.
1017 static GstSubParseFormat
1018 gst_sub_parse_data_format_autodetect (gchar * match_str)
1022 static GOnce mdvd_rx_once = G_ONCE_INIT;
1023 static GOnce subrip_rx_once = G_ONCE_INIT;
1028 g_once (&mdvd_rx_once,
1029 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1030 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1031 g_once (&subrip_rx_once,
1032 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1033 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1035 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1036 subrip_grx = (GRegex *) subrip_rx_once.retval;
1038 if (g_regex_match (mdvd_grx, match_str, 0, NULL) == TRUE) {
1039 GST_LOG ("MicroDVD (frame based) format detected");
1040 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1042 if (g_regex_match (subrip_grx, match_str, 0, NULL) == TRUE) {
1043 GST_LOG ("SubRip (time based) format detected");
1044 return GST_SUB_PARSE_FORMAT_SUBRIP;
1047 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1048 GST_LOG ("MPSub (time based) format detected");
1049 return GST_SUB_PARSE_FORMAT_MPSUB;
1051 #ifndef GST_DISABLE_XML
1052 if (strstr (match_str, "<SAMI>") != NULL ||
1053 strstr (match_str, "<sami>") != NULL) {
1054 GST_LOG ("SAMI (time based) format detected");
1055 return GST_SUB_PARSE_FORMAT_SAMI;
1058 /* we're boldly assuming the first subtitle appears within the first hour */
1059 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1060 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1061 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1062 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1063 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1064 GST_LOG ("TMPlayer (time based) format detected");
1065 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1067 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1068 GST_LOG ("MPL2 (time based) format detected");
1069 return GST_SUB_PARSE_FORMAT_MPL2;
1071 if (strstr (match_str, "[INFORMATION]") != NULL) {
1072 GST_LOG ("SubViewer (time based) format detected");
1073 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1076 GST_DEBUG ("no subtitle format detected");
1077 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1081 gst_sub_parse_format_autodetect (GstSubParse * self)
1084 GstSubParseFormat format;
1086 if (strlen (self->textbuf->str) < 35) {
1087 GST_DEBUG ("File too small to be a subtitles file");
1091 data = g_strndup (self->textbuf->str, 35);
1092 format = gst_sub_parse_data_format_autodetect (data);
1095 self->parser_type = format;
1096 parser_state_init (&self->state);
1099 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1100 self->parse_line = parse_mdvdsub;
1101 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1102 case GST_SUB_PARSE_FORMAT_SUBRIP:
1103 self->parse_line = parse_subrip;
1104 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1105 case GST_SUB_PARSE_FORMAT_MPSUB:
1106 self->parse_line = parse_mpsub;
1107 return gst_caps_new_simple ("text/plain", NULL);
1108 #ifndef GST_DISABLE_XML
1109 case GST_SUB_PARSE_FORMAT_SAMI:
1110 self->parse_line = parse_sami;
1111 sami_context_init (&self->state);
1112 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1114 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1115 self->parse_line = parse_tmplayer;
1116 self->state.max_duration = 5 * GST_SECOND;
1117 return gst_caps_new_simple ("text/plain", NULL);
1118 case GST_SUB_PARSE_FORMAT_MPL2:
1119 self->parse_line = parse_mpl2;
1120 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1121 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1122 self->parse_line = parse_subviewer;
1123 return gst_caps_new_simple ("text/plain", NULL);
1124 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1126 GST_DEBUG ("no subtitle format detected");
1127 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1128 ("The input is not a valid/supported subtitle file"), (NULL));
1134 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1138 gchar *input = NULL;
1140 discont = GST_BUFFER_IS_DISCONT (buf);
1142 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1143 GST_BUFFER_OFFSET (buf) != self->offset) {
1144 self->offset = GST_BUFFER_OFFSET (buf);
1149 GST_INFO ("discontinuity");
1150 /* flush the parser state */
1151 parser_state_init (&self->state);
1152 g_string_truncate (self->textbuf, 0);
1153 gst_adapter_clear (self->adapter);
1154 #ifndef GST_DISABLE_XML
1155 sami_context_reset (&self->state);
1157 /* we could set a flag to make sure that the next buffer we push out also
1158 * has the DISCONT flag set, but there's no point really given that it's
1159 * subtitles which are discontinuous by nature. */
1162 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1163 self->next_offset = self->offset;
1165 gst_adapter_push (self->adapter, buf);
1168 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1169 gst_adapter_available (self->adapter)),
1170 (gsize) gst_adapter_available (self->adapter), &consumed);
1172 if (input && consumed > 0) {
1173 self->textbuf = g_string_append (self->textbuf, input);
1174 gst_adapter_flush (self->adapter, consumed);
1180 static GstFlowReturn
1181 handle_buffer (GstSubParse * self, GstBuffer * buf)
1183 GstFlowReturn ret = GST_FLOW_OK;
1184 GstCaps *caps = NULL;
1185 gchar *line, *subtitle;
1187 if (self->first_buffer) {
1188 self->detected_encoding =
1189 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1190 GST_BUFFER_SIZE (buf));
1191 self->first_buffer = FALSE;
1194 feed_textbuf (self, buf);
1196 /* make sure we know the format */
1197 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1198 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1199 return GST_FLOW_UNEXPECTED;
1201 if (!gst_pad_set_caps (self->srcpad, caps)) {
1202 gst_caps_unref (caps);
1203 return GST_FLOW_UNEXPECTED;
1205 gst_caps_unref (caps);
1208 while (!self->flushing && (line = get_next_line (self))) {
1211 /* Set segment on our parser state machine */
1212 self->state.segment = &self->segment;
1213 /* Now parse the line, out of segment lines will just return NULL */
1214 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1215 subtitle = self->parse_line (&self->state, line + offset);
1219 guint subtitle_len = strlen (subtitle);
1221 /* +1 for terminating NUL character */
1222 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1223 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1224 GST_PAD_CAPS (self->srcpad), &buf);
1226 if (ret == GST_FLOW_OK) {
1227 /* copy terminating NUL character as well */
1228 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1229 GST_BUFFER_SIZE (buf) = subtitle_len;
1230 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1231 GST_BUFFER_DURATION (buf) = self->state.duration;
1233 /* in some cases (e.g. tmplayer) we can only determine the duration
1234 * of a text chunk from the timestamp of the next text chunk; in those
1235 * cases, we probably want to limit the duration to something
1236 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1237 * just because nothing else is being said during that time */
1238 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1239 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1240 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1243 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1244 self->state.start_time);
1246 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1247 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1248 GST_TIME_ARGS (self->state.duration));
1250 ret = gst_pad_push (self->srcpad, buf);
1253 /* move this forward (the tmplayer parser needs this) */
1254 if (self->state.duration != GST_CLOCK_TIME_NONE)
1255 self->state.start_time += self->state.duration;
1260 if (ret != GST_FLOW_OK) {
1261 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1270 static GstFlowReturn
1271 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1276 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1278 /* Push newsegment if needed */
1279 if (self->need_segment) {
1280 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1283 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1284 self->segment.rate, self->segment.format,
1285 self->segment.last_stop, self->segment.stop, self->segment.time));
1286 self->need_segment = FALSE;
1289 ret = handle_buffer (self, buf);
1295 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1297 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1298 gboolean ret = FALSE;
1300 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1302 switch (GST_EVENT_TYPE (event)) {
1303 case GST_EVENT_EOS:{
1304 /* Make sure the last subrip chunk is pushed out even
1305 * if the file does not have an empty line at the end */
1306 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1307 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1308 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1309 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1311 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1312 GST_BUFFER_DATA (buf)[0] = '\n';
1313 GST_BUFFER_DATA (buf)[1] = '\n';
1314 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1315 GST_BUFFER_SIZE (buf) = 2;
1316 GST_BUFFER_OFFSET (buf) = self->offset;
1317 gst_sub_parse_chain (pad, buf);
1319 ret = gst_pad_event_default (pad, event);
1322 case GST_EVENT_NEWSEGMENT:
1326 gint64 start, stop, time;
1329 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1332 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1334 if (format == GST_FORMAT_TIME) {
1335 gst_segment_set_newsegment (&self->segment, update, rate, format,
1338 /* if not time format, we'll either start with a 0 timestamp anyway or
1339 * it's following a seek in which case we'll have saved the requested
1340 * seek segment and don't want to overwrite it (remember that on a seek
1341 * we always just seek back to the start in BYTES format and just throw
1342 * away all text that's before the requested position; if the subtitles
1343 * come from an upstream demuxer, it won't be able to handle our BYTES
1344 * seek request and instead send us a newsegment from the seek request
1345 * it received via its video pads instead, so all is fine then too) */
1349 gst_event_unref (event);
1352 case GST_EVENT_FLUSH_START:
1354 self->flushing = TRUE;
1356 ret = gst_pad_event_default (pad, event);
1359 case GST_EVENT_FLUSH_STOP:
1361 self->flushing = FALSE;
1363 ret = gst_pad_event_default (pad, event);
1367 ret = gst_pad_event_default (pad, event);
1371 gst_object_unref (self);
1377 static GstStateChangeReturn
1378 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1380 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1381 GstSubParse *self = GST_SUBPARSE (element);
1383 switch (transition) {
1384 case GST_STATE_CHANGE_READY_TO_PAUSED:
1385 /* format detection will init the parser state */
1387 self->next_offset = 0;
1388 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1389 self->valid_utf8 = TRUE;
1390 self->first_buffer = TRUE;
1391 g_free (self->detected_encoding);
1392 self->detected_encoding = NULL;
1393 g_string_truncate (self->textbuf, 0);
1394 gst_adapter_clear (self->adapter);
1400 ret = parent_class->change_state (element, transition);
1401 if (ret == GST_STATE_CHANGE_FAILURE)
1404 switch (transition) {
1405 case GST_STATE_CHANGE_PAUSED_TO_READY:
1406 parser_state_dispose (&self->state);
1407 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1420 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1421 * also, give different subtitle formats really different types */
1422 static GstStaticCaps mpl2_caps =
1423 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1424 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1426 static GstStaticCaps tmp_caps =
1427 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1428 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1430 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1431 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1433 #ifndef GST_DISABLE_XML
1434 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1435 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1439 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1441 GstSubParseFormat format;
1445 gchar *encoding = NULL;
1448 if (!(data = gst_type_find_peek (tf, 0, 129)))
1451 /* make sure string passed to _autodetect() is NUL-terminated */
1452 str = g_malloc0 (129);
1453 memcpy (str, data, 128);
1455 if ((encoding = detect_encoding (str, 128)) != NULL) {
1456 gchar *converted_str;
1460 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
1461 if (converted_str == NULL) {
1462 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
1468 str = converted_str;
1473 /* Check if at least the first 120 chars are valid UTF8,
1474 * otherwise convert as always */
1475 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
1476 gchar *converted_str;
1481 enc = g_getenv ("GST_SUBTITLE_ENCODING");
1482 if (enc == NULL || *enc == '\0') {
1483 /* if local encoding is UTF-8 and no encoding specified
1484 * via the environment variable, assume ISO-8859-15 */
1485 if (g_get_charset (&enc)) {
1486 enc = "ISO-8859-15";
1489 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, &err);
1490 if (converted_str == NULL) {
1491 GST_DEBUG ("Charset conversion failed: %s", err->message);
1497 str = converted_str;
1501 format = gst_sub_parse_data_format_autodetect (str);
1505 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1506 GST_DEBUG ("MicroDVD format detected");
1509 case GST_SUB_PARSE_FORMAT_SUBRIP:
1510 GST_DEBUG ("SubRip format detected");
1513 case GST_SUB_PARSE_FORMAT_MPSUB:
1514 GST_DEBUG ("MPSub format detected");
1517 #ifndef GST_DISABLE_XML
1518 case GST_SUB_PARSE_FORMAT_SAMI:
1519 GST_DEBUG ("SAMI (time-based) format detected");
1523 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1524 GST_DEBUG ("TMPlayer (time based) format detected");
1527 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1528 * returning a high probability (however, since we registered our
1529 * typefinder here with a rank of MARGINAL we should pretty much only
1530 * be called if most other typefinders have already run */
1531 case GST_SUB_PARSE_FORMAT_MPL2:
1532 GST_DEBUG ("MPL2 (time based) format detected");
1535 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1536 GST_DEBUG ("SubViewer format detected");
1540 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1541 GST_DEBUG ("no subtitle format detected");
1545 /* if we're here, it's ok */
1546 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1550 plugin_init (GstPlugin * plugin)
1552 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1556 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1558 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1559 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1562 if (!gst_element_register (plugin, "subparse",
1563 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1564 !gst_element_register (plugin, "ssaparse",
1565 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1572 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1576 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)