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.
29 #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 "GStreamer maintainers <gstreamer-devel@lists.sourceforge.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; "
69 "application/x-subtitle-dks")
72 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
75 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-dks")
79 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
82 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
85 static void gst_sub_parse_base_init (GstSubParseClass * klass);
86 static void gst_sub_parse_class_init (GstSubParseClass * klass);
87 static void gst_sub_parse_init (GstSubParse * subparse);
89 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
90 static gboolean gst_sub_parse_src_query (GstPad * pad, GstQuery * query);
91 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
93 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
94 GstStateChange transition);
96 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
98 static GstElementClass *parent_class = NULL;
101 gst_sub_parse_get_type (void)
103 static GType sub_parse_type = 0;
105 if (!sub_parse_type) {
106 static const GTypeInfo sub_parse_info = {
107 sizeof (GstSubParseClass),
108 (GBaseInitFunc) gst_sub_parse_base_init,
110 (GClassInitFunc) gst_sub_parse_class_init,
113 sizeof (GstSubParse),
115 (GInstanceInitFunc) gst_sub_parse_init,
118 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
119 "GstSubParse", &sub_parse_info, 0);
122 return sub_parse_type;
126 gst_sub_parse_base_init (GstSubParseClass * klass)
128 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
130 gst_element_class_add_pad_template (element_class,
131 gst_static_pad_template_get (&sink_templ));
132 gst_element_class_add_pad_template (element_class,
133 gst_static_pad_template_get (&src_templ));
134 gst_element_class_set_details (element_class, &sub_parse_details);
138 gst_sub_parse_dispose (GObject * object)
140 GstSubParse *subparse = GST_SUBPARSE (object);
142 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
144 if (subparse->encoding) {
145 g_free (subparse->encoding);
146 subparse->encoding = NULL;
149 if (subparse->detected_encoding) {
150 g_free (subparse->detected_encoding);
151 subparse->detected_encoding = NULL;
154 if (subparse->adapter) {
155 g_object_unref (subparse->adapter);
156 subparse->adapter = NULL;
159 if (subparse->textbuf) {
160 g_string_free (subparse->textbuf, TRUE);
161 subparse->textbuf = NULL;
163 #ifndef GST_DISABLE_XML
164 sami_context_deinit (&subparse->state);
167 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
171 gst_sub_parse_class_init (GstSubParseClass * klass)
173 GObjectClass *object_class = G_OBJECT_CLASS (klass);
174 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
176 parent_class = g_type_class_peek_parent (klass);
178 object_class->dispose = gst_sub_parse_dispose;
179 object_class->set_property = gst_sub_parse_set_property;
180 object_class->get_property = gst_sub_parse_get_property;
182 element_class->change_state = gst_sub_parse_change_state;
184 g_object_class_install_property (object_class, PROP_ENCODING,
185 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
186 "Encoding to assume if input subtitles are not in UTF-8 or any other "
187 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
188 "variable will be checked for an encoding to use. If that is not set "
189 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
190 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
194 gst_sub_parse_init (GstSubParse * subparse)
196 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
197 gst_pad_set_chain_function (subparse->sinkpad,
198 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
199 gst_pad_set_event_function (subparse->sinkpad,
200 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
201 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
203 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
204 gst_pad_set_event_function (subparse->srcpad,
205 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
206 gst_pad_set_query_function (subparse->srcpad,
207 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
208 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
210 subparse->textbuf = g_string_new (NULL);
211 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
212 subparse->flushing = FALSE;
213 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
214 subparse->need_segment = TRUE;
215 subparse->encoding = g_strdup (DEFAULT_ENCODING);
216 subparse->detected_encoding = NULL;
217 subparse->adapter = gst_adapter_new ();
221 * Source pad functions.
225 gst_sub_parse_src_query (GstPad * pad, GstQuery * query)
227 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
228 gboolean ret = FALSE;
230 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
232 switch (GST_QUERY_TYPE (query)) {
233 case GST_QUERY_POSITION:{
236 gst_query_parse_position (query, &fmt, NULL);
237 if (fmt != GST_FORMAT_TIME) {
238 ret = gst_pad_peer_query (self->sinkpad, query);
241 gst_query_set_position (query, GST_FORMAT_TIME,
242 self->segment.last_stop);
245 case GST_QUERY_SEEKING:
248 gboolean seekable = FALSE;
252 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
253 if (fmt == GST_FORMAT_TIME) {
254 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
256 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
258 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
259 gst_query_unref (peerquery);
262 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
267 ret = gst_pad_peer_query (self->sinkpad, query);
271 gst_object_unref (self);
277 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
279 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
280 gboolean ret = FALSE;
282 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
284 switch (GST_EVENT_TYPE (event)) {
288 GstSeekType start_type, stop_type;
293 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
294 &start_type, &start, &stop_type, &stop);
296 if (format != GST_FORMAT_TIME) {
297 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
298 gst_event_unref (event);
302 /* Convert that seek to a seeking in bytes at position 0,
303 FIXME: could use an index */
304 ret = gst_pad_push_event (self->sinkpad,
305 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
306 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
309 /* Apply the seek to our segment */
310 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
311 start_type, start, stop_type, stop, &update);
313 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
316 self->next_offset = 0;
318 self->need_segment = TRUE;
320 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
323 gst_event_unref (event);
327 ret = gst_pad_event_default (pad, event);
332 gst_object_unref (self);
338 gst_sub_parse_set_property (GObject * object, guint prop_id,
339 const GValue * value, GParamSpec * pspec)
341 GstSubParse *subparse = GST_SUBPARSE (object);
343 GST_OBJECT_LOCK (subparse);
346 g_free (subparse->encoding);
347 subparse->encoding = g_value_dup_string (value);
348 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
349 GST_STR_NULL (subparse->encoding));
352 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
355 GST_OBJECT_UNLOCK (subparse);
359 gst_sub_parse_get_property (GObject * object, guint prop_id,
360 GValue * value, GParamSpec * pspec)
362 GstSubParse *subparse = GST_SUBPARSE (object);
364 GST_OBJECT_LOCK (subparse);
367 g_value_set_string (value, subparse->encoding);
370 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
373 GST_OBJECT_UNLOCK (subparse);
377 gst_sub_parse_get_format_description (GstSubParseFormat format)
380 case GST_SUB_PARSE_FORMAT_MDVDSUB:
382 case GST_SUB_PARSE_FORMAT_SUBRIP:
384 case GST_SUB_PARSE_FORMAT_MPSUB:
386 case GST_SUB_PARSE_FORMAT_SAMI:
388 case GST_SUB_PARSE_FORMAT_TMPLAYER:
390 case GST_SUB_PARSE_FORMAT_MPL2:
392 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
394 case GST_SUB_PARSE_FORMAT_DKS:
397 case GST_SUB_PARSE_FORMAT_UNKNOWN:
404 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
405 gsize * consumed, GError ** err)
411 g_convert_with_fallback (str, len, "UTF-8", encoding, "*", consumed, NULL,
416 /* + 3 to skip UTF-8 BOM if it was added */
418 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
419 && (guint8) ret[2] == 0xBF)
420 g_memmove (ret, ret + 3, len + 1 - 3);
426 detect_encoding (const gchar * str, gsize len)
428 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
429 && (guint8) str[2] == 0xBF)
430 return g_strdup ("UTF-8");
432 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
433 return g_strdup ("UTF-16BE");
435 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
436 return g_strdup ("UTF-16LE");
438 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
439 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
440 return g_strdup ("UTF-32BE");
442 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
443 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
444 return g_strdup ("UTF-32LE");
450 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
453 const gchar *encoding;
459 /* First try any detected encoding */
460 if (self->detected_encoding) {
462 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
467 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
468 self->detected_encoding, err->message);
469 g_free (self->detected_encoding);
470 self->detected_encoding = NULL;
474 /* Otherwise check if it's UTF8 */
475 if (self->valid_utf8) {
476 if (g_utf8_validate (str, len, NULL)) {
477 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
479 return g_strndup (str, len);
481 GST_INFO_OBJECT (self, "invalid UTF-8!");
482 self->valid_utf8 = FALSE;
485 /* Else try fallback */
486 encoding = self->encoding;
487 if (encoding == NULL || *encoding == '\0') {
488 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
490 if (encoding == NULL || *encoding == '\0') {
491 /* if local encoding is UTF-8 and no encoding specified
492 * via the environment variable, assume ISO-8859-15 */
493 if (g_get_charset (&encoding)) {
494 encoding = "ISO-8859-15";
498 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
501 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
502 encoding, err->message);
505 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
506 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
509 GST_LOG_OBJECT (self,
510 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
511 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
517 get_next_line (GstSubParse * self)
520 const char *line_end;
522 gboolean have_r = FALSE;
524 line_end = strchr (self->textbuf->str, '\n');
527 /* end-of-line not found; return for more data */
531 /* get rid of '\r' */
532 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
537 line_len = line_end - self->textbuf->str;
538 line = g_strndup (self->textbuf->str, line_len);
539 self->textbuf = g_string_erase (self->textbuf, 0,
540 line_len + (have_r ? 2 : 1));
545 parse_mdvdsub (ParserState * state, const gchar * line)
547 const gchar *line_split;
549 guint start_frame, end_frame;
550 gint64 clip_start = 0, clip_stop = 0;
551 gboolean in_seg = FALSE;
555 /* style variables */
560 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
561 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
562 " format, failed:\n%s", line);
566 /* skip the {%u}{%u} part */
567 line = strchr (line, '}') + 1;
568 line = strchr (line, '}') + 1;
570 /* see if there's a first line with a framerate */
571 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
572 gchar *rest, *end = NULL;
574 rest = g_strdup (line);
575 g_strdelimit (rest, ",", '.');
576 state->fps = g_ascii_strtod (rest, &end);
579 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
584 if (state->fps == 0.0) {
585 /* FIXME: hardcoded for now, is there a better way/assumption? */
586 state->fps = 24000.0 / 1001.0;
587 GST_INFO ("no framerate specified, assuming %f", state->fps);
590 state->start_time = start_frame / state->fps * GST_SECOND;
591 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
593 /* Check our segment start/stop */
594 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
595 state->start_time, state->start_time + state->duration, &clip_start,
598 /* No need to parse that text if it's out of segment */
600 state->start_time = clip_start;
601 state->duration = clip_stop - clip_start;
606 markup = g_string_new (NULL);
611 /* parse style markup */
612 if (strncmp (line, "{y:i}", 5) == 0) {
614 line = strchr (line, '}') + 1;
616 if (strncmp (line, "{y:b}", 5) == 0) {
618 line = strchr (line, '}') + 1;
620 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
621 line = strchr (line, '}') + 1;
623 /* forward slashes at beginning/end signify italics too */
624 if (g_str_has_prefix (line, "/")) {
628 if ((line_split = strchr (line, '|')))
629 line_chunk = g_markup_escape_text (line, line_split - line);
631 line_chunk = g_markup_escape_text (line, strlen (line));
633 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
634 * always at the end of a line or can they span multiple lines?) */
635 if (g_str_has_suffix (line_chunk, "/")) {
636 line_chunk[strlen (line_chunk) - 1] = '\0';
639 markup = g_string_append (markup, "<span");
641 g_string_append (markup, " style=\"italic\"");
643 g_string_append (markup, " weight=\"bold\"");
645 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
646 g_string_append_printf (markup, ">%s</span>", line_chunk);
649 g_string_append (markup, "\n");
650 line = line_split + 1;
656 g_string_free (markup, FALSE);
657 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
658 state->start_time / (double) GST_SECOND,
659 state->duration / (double) GST_SECOND, ret);
664 strip_trailing_newlines (gchar * txt)
670 while (len > 1 && txt[len - 1] == '\n') {
677 /* we want to escape text in general, but retain basic markup like
678 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
679 * just unescape a white list of allowed markups again after
680 * escaping everything (the text between these simple markers isn't
681 * necessarily escaped, so it seems best to do it like this) */
683 subrip_unescape_formatting (gchar * txt)
687 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
688 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
689 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
690 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
692 pos[1] = g_ascii_tolower (pos[4]);
694 /* move NUL terminator as well */
695 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
700 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
701 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
702 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
703 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
706 pos[2] = g_ascii_tolower (pos[5]);
708 /* move NUL terminator as well */
709 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
717 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
721 tag = start + strlen ("<");
725 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
730 GST_LOG ("removing unhandled tag '%s'", start);
732 g_memmove (start, stop, strlen (stop) + 1);
736 /* remove tags we haven't explicitly allowed earlier on, like font tags
739 subrip_remove_unhandled_tags (gchar * txt)
743 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
744 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
745 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
751 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
752 * assumes the input has been escaped and subrip_unescape_formatting() has then
753 * been run over the input! This function adds missing closing markup tags and
754 * removes broken closing tags for tags that have never been opened. */
756 subrip_fix_up_markup (gchar ** p_txt)
758 gchar *cur, *next_tag;
760 guint num_open_tags = 0;
762 g_assert (*p_txt != NULL);
765 while (*cur != '\0') {
766 next_tag = strchr (cur, '<');
767 if (next_tag == NULL)
773 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
774 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
775 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
778 /* it's all good, closing tag which is open */
786 if (num_open_tags == G_N_ELEMENTS (open_tags))
787 return; /* something dodgy is going on, stop parsing */
788 open_tags[num_open_tags] = *next_tag;
792 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
793 g_assert_not_reached ();
799 if (num_open_tags > 0) {
802 s = g_string_new (*p_txt);
803 while (num_open_tags > 0) {
804 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
805 g_string_append_c (s, '<');
806 g_string_append_c (s, '/');
807 g_string_append_c (s, open_tags[num_open_tags - 1]);
808 g_string_append_c (s, '>');
812 *p_txt = g_string_free (s, FALSE);
817 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
819 gchar s[128] = { '\0', };
821 guint hour, min, sec, msec, len;
823 while (*ts_string == ' ')
826 g_strlcpy (s, ts_string, sizeof (s));
827 if ((end = strstr (s, "-->")))
831 /* ms may be in these formats:
832 * hh:mm:ss,500 = 500ms
835 * hh:mm:ss, 50 = 50ms
837 * and the same with . instead of ,.
838 * sscanf() doesn't differentiate between ' 5' and '5' so munge
839 * the white spaces within the timestamp to '0' (I'm sure there's a
840 * way to make sscanf() do this for us, but how?)
842 g_strdelimit (s, " ", '0');
843 g_strdelimit (s, ".", ',');
845 /* make sure we have exactly three digits after he comma */
847 g_assert (p != NULL);
854 g_strlcat (&p[len], "0", 2);
858 GST_LOG ("parsing timestamp '%s'", s);
859 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
860 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
864 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
869 parse_subrip (ParserState * state, const gchar * line)
874 switch (state->state) {
876 /* looking for a single integer */
877 if (sscanf (line, "%u", &subnum) == 1)
882 GstClockTime ts_start, ts_end;
885 /* looking for start_time --> end_time */
886 if ((end_time = strstr (line, " --> ")) &&
887 parse_subrip_time (line, &ts_start) &&
888 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
889 state->start_time <= ts_end) {
891 state->start_time = ts_start;
892 state->duration = ts_end - ts_start;
894 GST_DEBUG ("error parsing subrip time line '%s'", line);
901 /* No need to parse that text if it's out of segment */
902 gint64 clip_start = 0, clip_stop = 0;
903 gboolean in_seg = FALSE;
905 /* Check our segment start/stop */
906 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
907 state->start_time, state->start_time + state->duration,
908 &clip_start, &clip_stop);
911 state->start_time = clip_start;
912 state->duration = clip_stop - clip_start;
918 /* looking for subtitle text; empty line ends this subtitle entry */
920 g_string_append_c (state->buf, '\n');
921 g_string_append (state->buf, line);
922 if (strlen (line) == 0) {
923 ret = g_markup_escape_text (state->buf->str, state->buf->len);
924 g_string_truncate (state->buf, 0);
926 subrip_unescape_formatting (ret);
927 subrip_remove_unhandled_tags (ret);
928 strip_trailing_newlines (ret);
929 subrip_fix_up_markup (&ret);
934 g_return_val_if_reached (NULL);
939 unescape_newlines_br (gchar * read)
943 /* Replace all occurences of '[br]' with a newline as version 2
944 * of the subviewer format uses this for newlines */
946 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
950 if (strncmp (read, "[br]", 4) == 0) {
964 parse_subviewer (ParserState * state, const gchar * line)
966 guint h1, m1, s1, ms1;
967 guint h2, m2, s2, ms2;
970 /* TODO: Maybe also parse the fields in the header, especially DELAY.
971 * For examples see the unit test or
972 * http://www.doom9.org/index.html?/sub.htm */
974 switch (state->state) {
976 /* looking for start_time,end_time */
977 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
978 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
981 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
984 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
985 ms2 * GST_MSECOND - state->start_time;
990 /* No need to parse that text if it's out of segment */
991 gint64 clip_start = 0, clip_stop = 0;
992 gboolean in_seg = FALSE;
994 /* Check our segment start/stop */
995 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
996 state->start_time, state->start_time + state->duration,
997 &clip_start, &clip_stop);
1000 state->start_time = clip_start;
1001 state->duration = clip_stop - clip_start;
1007 /* looking for subtitle text; empty line ends this subtitle entry */
1008 if (state->buf->len)
1009 g_string_append_c (state->buf, '\n');
1010 g_string_append (state->buf, line);
1011 if (strlen (line) == 0) {
1012 ret = g_strdup (state->buf->str);
1013 unescape_newlines_br (ret);
1014 strip_trailing_newlines (ret);
1015 g_string_truncate (state->buf, 0);
1021 g_assert_not_reached ();
1027 parse_mpsub (ParserState * state, const gchar * line)
1032 switch (state->state) {
1034 /* looking for two floats (offset, duration) */
1035 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1037 state->start_time += state->duration + GST_SECOND * t1;
1038 state->duration = GST_SECOND * t2;
1042 { /* No need to parse that text if it's out of segment */
1043 gint64 clip_start = 0, clip_stop = 0;
1044 gboolean in_seg = FALSE;
1046 /* Check our segment start/stop */
1047 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1048 state->start_time, state->start_time + state->duration,
1049 &clip_start, &clip_stop);
1052 state->start_time = clip_start;
1053 state->duration = clip_stop - clip_start;
1059 /* looking for subtitle text; empty line ends this
1061 if (state->buf->len)
1062 g_string_append_c (state->buf, '\n');
1063 g_string_append (state->buf, line);
1064 if (strlen (line) == 0) {
1065 ret = g_strdup (state->buf->str);
1066 g_string_truncate (state->buf, 0);
1072 g_assert_not_reached ();
1077 static const gchar *
1078 dks_skip_timestamp (const gchar * line)
1080 while (*line && *line != ']')
1088 parse_dks (ParserState * state, const gchar * line)
1092 switch (state->state) {
1094 /* Looking for the start time and text */
1095 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1097 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1098 text = dks_skip_timestamp (line);
1101 g_string_append (state->buf, text);
1107 gint64 clip_start = 0, clip_stop = 0;
1111 /* Looking for the end time */
1112 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1114 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1117 GST_WARNING ("Failed to parse subtitle end time");
1121 /* Check if this subtitle is out of the current segment */
1122 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1123 state->start_time, state->start_time + state->duration,
1124 &clip_start, &clip_stop);
1130 state->start_time = clip_start;
1131 state->duration = clip_stop - clip_start;
1133 ret = g_strdup (state->buf->str);
1134 g_string_truncate (state->buf, 0);
1135 unescape_newlines_br (ret);
1139 g_assert_not_reached ();
1145 parser_state_init (ParserState * state)
1147 GST_DEBUG ("initialising parser");
1150 g_string_truncate (state->buf, 0);
1152 state->buf = g_string_new (NULL);
1155 state->start_time = 0;
1156 state->duration = 0;
1157 state->max_duration = 0; /* no limit */
1159 state->segment = NULL;
1163 parser_state_dispose (ParserState * state)
1166 g_string_free (state->buf, TRUE);
1169 #ifndef GST_DISABLE_XML
1170 if (state->user_data) {
1171 sami_context_reset (state);
1176 /* regex type enum */
1179 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1180 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1181 GST_SUB_PARSE_REGEX_SUBRIP = 2,
1182 GST_SUB_PARSE_REGEX_DKS = 3,
1186 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1188 gpointer result = NULL;
1189 GError *gerr = NULL;
1191 case GST_SUB_PARSE_REGEX_MDVDSUB:
1193 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}", 0, 0, &gerr);
1194 if (result == NULL) {
1195 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1196 g_error_free (gerr);
1199 case GST_SUB_PARSE_REGEX_SUBRIP:
1200 result = (gpointer) g_regex_new ("^([ 0-9]){0,3}[0-9]\\s*(\x0d)?\x0a"
1201 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9][,.][ 0-9]{0,2}[0-9]"
1202 " +--> +([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9][,.][ 0-9]{0,2}[0-9]",
1204 if (result == NULL) {
1205 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1206 g_error_free (gerr);
1209 case GST_SUB_PARSE_REGEX_DKS:
1210 result = (gpointer) g_regex_new ("^\[[0-9]+:[0-9]+:[0-9]+].*",
1212 if (result == NULL) {
1213 g_warning ("Compilation of dks regex failed: %s", gerr->message);
1214 g_error_free (gerr);
1218 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1224 * FIXME: maybe we should pass along a second argument, the preceding
1225 * text buffer, because that is how this originally worked, even though
1226 * I don't really see the use of that.
1229 static GstSubParseFormat
1230 gst_sub_parse_data_format_autodetect (gchar * match_str)
1234 static GOnce mdvd_rx_once = G_ONCE_INIT;
1235 static GOnce subrip_rx_once = G_ONCE_INIT;
1236 static GOnce dks_rx_once = G_ONCE_INIT;
1242 g_once (&mdvd_rx_once,
1243 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1244 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1245 g_once (&subrip_rx_once,
1246 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1247 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1248 g_once (&dks_rx_once,
1249 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1250 (gpointer) GST_SUB_PARSE_REGEX_DKS);
1252 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1253 subrip_grx = (GRegex *) subrip_rx_once.retval;
1254 dks_grx = (GRegex *) dks_rx_once.retval;
1256 if (g_regex_match (mdvd_grx, match_str, 0, NULL) == TRUE) {
1257 GST_LOG ("MicroDVD (frame based) format detected");
1258 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1260 if (g_regex_match (subrip_grx, match_str, 0, NULL) == TRUE) {
1261 GST_LOG ("SubRip (time based) format detected");
1262 return GST_SUB_PARSE_FORMAT_SUBRIP;
1264 if (g_regex_match (dks_grx, match_str, 0, NULL) == TRUE) {
1265 GST_LOG ("DKS (time based) format detected");
1266 return GST_SUB_PARSE_FORMAT_DKS;
1269 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1270 GST_LOG ("MPSub (time based) format detected");
1271 return GST_SUB_PARSE_FORMAT_MPSUB;
1273 #ifndef GST_DISABLE_XML
1274 if (strstr (match_str, "<SAMI>") != NULL ||
1275 strstr (match_str, "<sami>") != NULL) {
1276 GST_LOG ("SAMI (time based) format detected");
1277 return GST_SUB_PARSE_FORMAT_SAMI;
1280 /* we're boldly assuming the first subtitle appears within the first hour */
1281 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1282 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1283 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1284 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1285 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1286 GST_LOG ("TMPlayer (time based) format detected");
1287 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1289 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1290 GST_LOG ("MPL2 (time based) format detected");
1291 return GST_SUB_PARSE_FORMAT_MPL2;
1293 if (strstr (match_str, "[INFORMATION]") != NULL) {
1294 GST_LOG ("SubViewer (time based) format detected");
1295 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1298 GST_DEBUG ("no subtitle format detected");
1299 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1303 gst_sub_parse_format_autodetect (GstSubParse * self)
1306 GstSubParseFormat format;
1308 if (strlen (self->textbuf->str) < 30) {
1309 GST_DEBUG ("File too small to be a subtitles file");
1313 data = g_strndup (self->textbuf->str, 35);
1314 format = gst_sub_parse_data_format_autodetect (data);
1317 self->parser_type = format;
1318 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1319 parser_state_init (&self->state);
1322 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1323 self->parse_line = parse_mdvdsub;
1324 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1325 case GST_SUB_PARSE_FORMAT_SUBRIP:
1326 self->parse_line = parse_subrip;
1327 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1328 case GST_SUB_PARSE_FORMAT_MPSUB:
1329 self->parse_line = parse_mpsub;
1330 return gst_caps_new_simple ("text/plain", NULL);
1331 #ifndef GST_DISABLE_XML
1332 case GST_SUB_PARSE_FORMAT_SAMI:
1333 self->parse_line = parse_sami;
1334 sami_context_init (&self->state);
1335 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1337 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1338 self->parse_line = parse_tmplayer;
1339 self->state.max_duration = 5 * GST_SECOND;
1340 return gst_caps_new_simple ("text/plain", NULL);
1341 case GST_SUB_PARSE_FORMAT_MPL2:
1342 self->parse_line = parse_mpl2;
1343 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1344 case GST_SUB_PARSE_FORMAT_DKS:
1345 self->parse_line = parse_dks;
1346 return gst_caps_new_simple ("text/plain", NULL);
1347 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1348 self->parse_line = parse_subviewer;
1349 return gst_caps_new_simple ("text/plain", NULL);
1350 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1352 GST_DEBUG ("no subtitle format detected");
1353 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1354 ("The input is not a valid/supported subtitle file"), (NULL));
1360 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1364 gchar *input = NULL;
1366 discont = GST_BUFFER_IS_DISCONT (buf);
1368 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1369 GST_BUFFER_OFFSET (buf) != self->offset) {
1370 self->offset = GST_BUFFER_OFFSET (buf);
1375 GST_INFO ("discontinuity");
1376 /* flush the parser state */
1377 parser_state_init (&self->state);
1378 g_string_truncate (self->textbuf, 0);
1379 gst_adapter_clear (self->adapter);
1380 #ifndef GST_DISABLE_XML
1381 sami_context_reset (&self->state);
1383 /* we could set a flag to make sure that the next buffer we push out also
1384 * has the DISCONT flag set, but there's no point really given that it's
1385 * subtitles which are discontinuous by nature. */
1388 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1389 self->next_offset = self->offset;
1391 gst_adapter_push (self->adapter, buf);
1394 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1395 gst_adapter_available (self->adapter)),
1396 (gsize) gst_adapter_available (self->adapter), &consumed);
1398 if (input && consumed > 0) {
1399 self->textbuf = g_string_append (self->textbuf, input);
1400 gst_adapter_flush (self->adapter, consumed);
1406 static GstFlowReturn
1407 handle_buffer (GstSubParse * self, GstBuffer * buf)
1409 GstFlowReturn ret = GST_FLOW_OK;
1410 GstCaps *caps = NULL;
1411 gchar *line, *subtitle;
1413 if (self->first_buffer) {
1414 self->detected_encoding =
1415 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1416 GST_BUFFER_SIZE (buf));
1417 self->first_buffer = FALSE;
1420 feed_textbuf (self, buf);
1422 /* make sure we know the format */
1423 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1424 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1425 return GST_FLOW_UNEXPECTED;
1427 if (!gst_pad_set_caps (self->srcpad, caps)) {
1428 gst_caps_unref (caps);
1429 return GST_FLOW_UNEXPECTED;
1431 gst_caps_unref (caps);
1434 if (self->subtitle_codec != NULL) {
1437 tags = gst_tag_list_new ();
1438 gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_SUBTITLE_CODEC,
1439 self->subtitle_codec, NULL);
1440 gst_element_found_tags_for_pad (GST_ELEMENT (self), self->srcpad, tags);
1444 while (!self->flushing && (line = get_next_line (self))) {
1447 /* Set segment on our parser state machine */
1448 self->state.segment = &self->segment;
1449 /* Now parse the line, out of segment lines will just return NULL */
1450 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1451 subtitle = self->parse_line (&self->state, line + offset);
1455 guint subtitle_len = strlen (subtitle);
1457 /* +1 for terminating NUL character */
1458 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1459 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1460 GST_PAD_CAPS (self->srcpad), &buf);
1462 if (ret == GST_FLOW_OK) {
1463 /* copy terminating NUL character as well */
1464 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1465 GST_BUFFER_SIZE (buf) = subtitle_len;
1466 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1467 GST_BUFFER_DURATION (buf) = self->state.duration;
1469 /* in some cases (e.g. tmplayer) we can only determine the duration
1470 * of a text chunk from the timestamp of the next text chunk; in those
1471 * cases, we probably want to limit the duration to something
1472 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1473 * just because nothing else is being said during that time */
1474 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1475 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1476 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1479 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1480 self->state.start_time);
1482 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1483 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1484 GST_TIME_ARGS (self->state.duration));
1486 ret = gst_pad_push (self->srcpad, buf);
1489 /* move this forward (the tmplayer parser needs this) */
1490 if (self->state.duration != GST_CLOCK_TIME_NONE)
1491 self->state.start_time += self->state.duration;
1496 if (ret != GST_FLOW_OK) {
1497 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1506 static GstFlowReturn
1507 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1512 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1514 /* Push newsegment if needed */
1515 if (self->need_segment) {
1516 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1519 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1520 self->segment.rate, self->segment.format,
1521 self->segment.last_stop, self->segment.stop, self->segment.time));
1522 self->need_segment = FALSE;
1525 ret = handle_buffer (self, buf);
1531 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1533 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1534 gboolean ret = FALSE;
1536 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1538 switch (GST_EVENT_TYPE (event)) {
1539 case GST_EVENT_EOS:{
1540 /* Make sure the last subrip chunk is pushed out even
1541 * if the file does not have an empty line at the end */
1542 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1543 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1544 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1545 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1547 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1548 GST_BUFFER_DATA (buf)[0] = '\n';
1549 GST_BUFFER_DATA (buf)[1] = '\n';
1550 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1551 GST_BUFFER_SIZE (buf) = 2;
1552 GST_BUFFER_OFFSET (buf) = self->offset;
1553 gst_sub_parse_chain (pad, buf);
1555 ret = gst_pad_event_default (pad, event);
1558 case GST_EVENT_NEWSEGMENT:
1562 gint64 start, stop, time;
1565 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1568 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1570 if (format == GST_FORMAT_TIME) {
1571 gst_segment_set_newsegment (&self->segment, update, rate, format,
1574 /* if not time format, we'll either start with a 0 timestamp anyway or
1575 * it's following a seek in which case we'll have saved the requested
1576 * seek segment and don't want to overwrite it (remember that on a seek
1577 * we always just seek back to the start in BYTES format and just throw
1578 * away all text that's before the requested position; if the subtitles
1579 * come from an upstream demuxer, it won't be able to handle our BYTES
1580 * seek request and instead send us a newsegment from the seek request
1581 * it received via its video pads instead, so all is fine then too) */
1585 gst_event_unref (event);
1588 case GST_EVENT_FLUSH_START:
1590 self->flushing = TRUE;
1592 ret = gst_pad_event_default (pad, event);
1595 case GST_EVENT_FLUSH_STOP:
1597 self->flushing = FALSE;
1599 ret = gst_pad_event_default (pad, event);
1603 ret = gst_pad_event_default (pad, event);
1607 gst_object_unref (self);
1613 static GstStateChangeReturn
1614 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1616 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1617 GstSubParse *self = GST_SUBPARSE (element);
1619 switch (transition) {
1620 case GST_STATE_CHANGE_READY_TO_PAUSED:
1621 /* format detection will init the parser state */
1623 self->next_offset = 0;
1624 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1625 self->valid_utf8 = TRUE;
1626 self->first_buffer = TRUE;
1627 g_free (self->detected_encoding);
1628 self->detected_encoding = NULL;
1629 g_string_truncate (self->textbuf, 0);
1630 gst_adapter_clear (self->adapter);
1636 ret = parent_class->change_state (element, transition);
1637 if (ret == GST_STATE_CHANGE_FAILURE)
1640 switch (transition) {
1641 case GST_STATE_CHANGE_PAUSED_TO_READY:
1642 parser_state_dispose (&self->state);
1643 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1656 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1657 * also, give different subtitle formats really different types */
1658 static GstStaticCaps mpl2_caps =
1659 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1660 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1662 static GstStaticCaps tmp_caps =
1663 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1664 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1666 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1667 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1669 #ifndef GST_DISABLE_XML
1670 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1671 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1674 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
1675 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
1678 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1680 GstSubParseFormat format;
1684 gchar *encoding = NULL;
1687 if (!(data = gst_type_find_peek (tf, 0, 129)))
1690 /* make sure string passed to _autodetect() is NUL-terminated */
1691 str = g_malloc0 (129);
1692 memcpy (str, data, 128);
1694 if ((encoding = detect_encoding (str, 128)) != NULL) {
1695 gchar *converted_str;
1699 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
1700 if (converted_str == NULL) {
1701 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
1707 str = converted_str;
1712 /* Check if at least the first 120 chars are valid UTF8,
1713 * otherwise convert as always */
1714 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
1715 gchar *converted_str;
1720 enc = g_getenv ("GST_SUBTITLE_ENCODING");
1721 if (enc == NULL || *enc == '\0') {
1722 /* if local encoding is UTF-8 and no encoding specified
1723 * via the environment variable, assume ISO-8859-15 */
1724 if (g_get_charset (&enc)) {
1725 enc = "ISO-8859-15";
1728 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, &err);
1729 if (converted_str == NULL) {
1730 GST_DEBUG ("Charset conversion failed: %s", err->message);
1736 str = converted_str;
1740 format = gst_sub_parse_data_format_autodetect (str);
1744 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1745 GST_DEBUG ("MicroDVD format detected");
1748 case GST_SUB_PARSE_FORMAT_SUBRIP:
1749 GST_DEBUG ("SubRip format detected");
1752 case GST_SUB_PARSE_FORMAT_MPSUB:
1753 GST_DEBUG ("MPSub format detected");
1756 #ifndef GST_DISABLE_XML
1757 case GST_SUB_PARSE_FORMAT_SAMI:
1758 GST_DEBUG ("SAMI (time-based) format detected");
1762 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1763 GST_DEBUG ("TMPlayer (time based) format detected");
1766 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1767 * returning a high probability (however, since we registered our
1768 * typefinder here with a rank of MARGINAL we should pretty much only
1769 * be called if most other typefinders have already run */
1770 case GST_SUB_PARSE_FORMAT_MPL2:
1771 GST_DEBUG ("MPL2 (time based) format detected");
1774 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1775 GST_DEBUG ("SubViewer format detected");
1778 case GST_SUB_PARSE_FORMAT_DKS:
1779 GST_DEBUG ("DKS format detected");
1783 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1784 GST_DEBUG ("no subtitle format detected");
1788 /* if we're here, it's ok */
1789 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1793 plugin_init (GstPlugin * plugin)
1795 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1799 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1801 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1802 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1805 if (!gst_element_register (plugin, "subparse",
1806 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1807 !gst_element_register (plugin, "ssaparse",
1808 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1815 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1819 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)