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
50 gst_sub_parse_set_property (GObject * object, guint prop_id,
51 const GValue * value, GParamSpec * pspec);
53 gst_sub_parse_get_property (GObject * object, guint prop_id,
54 GValue * value, GParamSpec * pspec);
57 static const GstElementDetails sub_parse_details =
58 GST_ELEMENT_DETAILS ("Subtitle parser",
59 "Codec/Parser/Subtitle",
60 "Parses subtitle (.sub) files into text streams",
61 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
62 "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
64 #ifndef GST_DISABLE_XML
65 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
68 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
69 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
70 "application/x-subtitle-dks")
73 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
76 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-dks")
80 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
83 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
86 static void gst_sub_parse_base_init (GstSubParseClass * klass);
87 static void gst_sub_parse_class_init (GstSubParseClass * klass);
88 static void gst_sub_parse_init (GstSubParse * subparse);
90 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
91 static gboolean gst_sub_parse_src_query (GstPad * pad, GstQuery * query);
92 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
94 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
95 GstStateChange transition);
97 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
99 static GstElementClass *parent_class = NULL;
102 gst_sub_parse_get_type (void)
104 static GType sub_parse_type = 0;
106 if (!sub_parse_type) {
107 static const GTypeInfo sub_parse_info = {
108 sizeof (GstSubParseClass),
109 (GBaseInitFunc) gst_sub_parse_base_init,
111 (GClassInitFunc) gst_sub_parse_class_init,
114 sizeof (GstSubParse),
116 (GInstanceInitFunc) gst_sub_parse_init,
119 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
120 "GstSubParse", &sub_parse_info, 0);
123 return sub_parse_type;
127 gst_sub_parse_base_init (GstSubParseClass * klass)
129 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
131 gst_element_class_add_pad_template (element_class,
132 gst_static_pad_template_get (&sink_templ));
133 gst_element_class_add_pad_template (element_class,
134 gst_static_pad_template_get (&src_templ));
135 gst_element_class_set_details (element_class, &sub_parse_details);
139 gst_sub_parse_dispose (GObject * object)
141 GstSubParse *subparse = GST_SUBPARSE (object);
143 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
145 if (subparse->encoding) {
146 g_free (subparse->encoding);
147 subparse->encoding = NULL;
150 if (subparse->detected_encoding) {
151 g_free (subparse->detected_encoding);
152 subparse->detected_encoding = NULL;
155 if (subparse->adapter) {
156 g_object_unref (subparse->adapter);
157 subparse->adapter = NULL;
160 if (subparse->textbuf) {
161 g_string_free (subparse->textbuf, TRUE);
162 subparse->textbuf = NULL;
164 #ifndef GST_DISABLE_XML
165 sami_context_deinit (&subparse->state);
168 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
172 gst_sub_parse_class_init (GstSubParseClass * klass)
174 GObjectClass *object_class = G_OBJECT_CLASS (klass);
175 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
177 parent_class = g_type_class_peek_parent (klass);
179 object_class->dispose = gst_sub_parse_dispose;
180 object_class->set_property = gst_sub_parse_set_property;
181 object_class->get_property = gst_sub_parse_get_property;
183 element_class->change_state = gst_sub_parse_change_state;
185 g_object_class_install_property (object_class, PROP_ENCODING,
186 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
187 "Encoding to assume if input subtitles are not in UTF-8 or any other "
188 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
189 "variable will be checked for an encoding to use. If that is not set "
190 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
191 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
193 g_object_class_install_property (object_class, PROP_VIDEOFPS,
194 gst_param_spec_fraction ("video-fps", "Video framerate",
195 "Framerate of the video stream. This is needed by some subtitle "
196 "formats to synchronize subtitles and video properly. If not set "
197 "and the subtitle format requires it subtitles may be out of sync.",
198 0, 1, G_MAXINT, 1, 24000, 1001, G_PARAM_READWRITE));
202 gst_sub_parse_init (GstSubParse * subparse)
204 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
205 gst_pad_set_chain_function (subparse->sinkpad,
206 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
207 gst_pad_set_event_function (subparse->sinkpad,
208 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
209 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
211 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
212 gst_pad_set_event_function (subparse->srcpad,
213 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
214 gst_pad_set_query_function (subparse->srcpad,
215 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
216 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
218 subparse->textbuf = g_string_new (NULL);
219 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
220 subparse->flushing = FALSE;
221 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
222 subparse->need_segment = TRUE;
223 subparse->encoding = g_strdup (DEFAULT_ENCODING);
224 subparse->detected_encoding = NULL;
225 subparse->adapter = gst_adapter_new ();
227 subparse->fps_n = 24000;
228 subparse->fps_d = 1001;
232 * Source pad functions.
236 gst_sub_parse_src_query (GstPad * pad, GstQuery * query)
238 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
239 gboolean ret = FALSE;
241 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
243 switch (GST_QUERY_TYPE (query)) {
244 case GST_QUERY_POSITION:{
247 gst_query_parse_position (query, &fmt, NULL);
248 if (fmt != GST_FORMAT_TIME) {
249 ret = gst_pad_peer_query (self->sinkpad, query);
252 gst_query_set_position (query, GST_FORMAT_TIME,
253 self->segment.last_stop);
256 case GST_QUERY_SEEKING:
259 gboolean seekable = FALSE;
263 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
264 if (fmt == GST_FORMAT_TIME) {
265 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
267 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
269 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
270 gst_query_unref (peerquery);
273 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
278 ret = gst_pad_peer_query (self->sinkpad, query);
282 gst_object_unref (self);
288 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
290 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
291 gboolean ret = FALSE;
293 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
295 switch (GST_EVENT_TYPE (event)) {
299 GstSeekType start_type, stop_type;
304 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
305 &start_type, &start, &stop_type, &stop);
307 if (format != GST_FORMAT_TIME) {
308 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
309 gst_event_unref (event);
313 /* Convert that seek to a seeking in bytes at position 0,
314 FIXME: could use an index */
315 ret = gst_pad_push_event (self->sinkpad,
316 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
317 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
320 /* Apply the seek to our segment */
321 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
322 start_type, start, stop_type, stop, &update);
324 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
327 self->next_offset = 0;
329 self->need_segment = TRUE;
331 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
334 gst_event_unref (event);
338 ret = gst_pad_event_default (pad, event);
343 gst_object_unref (self);
349 gst_sub_parse_set_property (GObject * object, guint prop_id,
350 const GValue * value, GParamSpec * pspec)
352 GstSubParse *subparse = GST_SUBPARSE (object);
354 GST_OBJECT_LOCK (subparse);
357 g_free (subparse->encoding);
358 subparse->encoding = g_value_dup_string (value);
359 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
360 GST_STR_NULL (subparse->encoding));
364 subparse->fps_n = gst_value_get_fraction_numerator (value);
365 subparse->fps_d = gst_value_get_fraction_denominator (value);
366 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
369 if (!subparse->state.have_internal_fps) {
370 subparse->state.fps_n = subparse->fps_n;
371 subparse->state.fps_d = subparse->fps_d;
376 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
379 GST_OBJECT_UNLOCK (subparse);
383 gst_sub_parse_get_property (GObject * object, guint prop_id,
384 GValue * value, GParamSpec * pspec)
386 GstSubParse *subparse = GST_SUBPARSE (object);
388 GST_OBJECT_LOCK (subparse);
391 g_value_set_string (value, subparse->encoding);
394 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
397 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
400 GST_OBJECT_UNLOCK (subparse);
404 gst_sub_parse_get_format_description (GstSubParseFormat format)
407 case GST_SUB_PARSE_FORMAT_MDVDSUB:
409 case GST_SUB_PARSE_FORMAT_SUBRIP:
411 case GST_SUB_PARSE_FORMAT_MPSUB:
413 case GST_SUB_PARSE_FORMAT_SAMI:
415 case GST_SUB_PARSE_FORMAT_TMPLAYER:
417 case GST_SUB_PARSE_FORMAT_MPL2:
419 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
421 case GST_SUB_PARSE_FORMAT_DKS:
424 case GST_SUB_PARSE_FORMAT_UNKNOWN:
431 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
432 gsize * consumed, GError ** err)
438 g_convert_with_fallback (str, len, "UTF-8", encoding, "*", consumed, NULL,
443 /* + 3 to skip UTF-8 BOM if it was added */
445 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
446 && (guint8) ret[2] == 0xBF)
447 g_memmove (ret, ret + 3, len + 1 - 3);
453 detect_encoding (const gchar * str, gsize len)
455 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
456 && (guint8) str[2] == 0xBF)
457 return g_strdup ("UTF-8");
459 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
460 return g_strdup ("UTF-16BE");
462 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
463 return g_strdup ("UTF-16LE");
465 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
466 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
467 return g_strdup ("UTF-32BE");
469 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
470 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
471 return g_strdup ("UTF-32LE");
477 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
480 const gchar *encoding;
486 /* First try any detected encoding */
487 if (self->detected_encoding) {
489 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
494 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
495 self->detected_encoding, err->message);
496 g_free (self->detected_encoding);
497 self->detected_encoding = NULL;
501 /* Otherwise check if it's UTF8 */
502 if (self->valid_utf8) {
503 if (g_utf8_validate (str, len, NULL)) {
504 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
506 return g_strndup (str, len);
508 GST_INFO_OBJECT (self, "invalid UTF-8!");
509 self->valid_utf8 = FALSE;
512 /* Else try fallback */
513 encoding = self->encoding;
514 if (encoding == NULL || *encoding == '\0') {
515 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
517 if (encoding == NULL || *encoding == '\0') {
518 /* if local encoding is UTF-8 and no encoding specified
519 * via the environment variable, assume ISO-8859-15 */
520 if (g_get_charset (&encoding)) {
521 encoding = "ISO-8859-15";
525 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
528 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
529 encoding, err->message);
532 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
533 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
536 GST_LOG_OBJECT (self,
537 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
538 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
544 get_next_line (GstSubParse * self)
547 const char *line_end;
549 gboolean have_r = FALSE;
551 line_end = strchr (self->textbuf->str, '\n');
554 /* end-of-line not found; return for more data */
558 /* get rid of '\r' */
559 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
564 line_len = line_end - self->textbuf->str;
565 line = g_strndup (self->textbuf->str, line_len);
566 self->textbuf = g_string_erase (self->textbuf, 0,
567 line_len + (have_r ? 2 : 1));
572 parse_mdvdsub (ParserState * state, const gchar * line)
574 const gchar *line_split;
576 guint start_frame, end_frame;
577 gint64 clip_start = 0, clip_stop = 0;
578 gboolean in_seg = FALSE;
582 /* style variables */
588 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
589 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
590 " format, failed:\n%s", line);
594 /* skip the {%u}{%u} part */
595 line = strchr (line, '}') + 1;
596 line = strchr (line, '}') + 1;
598 /* see if there's a first line with a framerate */
599 if (start_frame == 1 && end_frame == 1) {
600 gchar *rest, *end = NULL;
602 rest = g_strdup (line);
603 g_strdelimit (rest, ",", '.');
604 fps = g_ascii_strtod (rest, &end);
606 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
607 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
615 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
618 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
621 /* Check our segment start/stop */
622 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
623 state->start_time, state->start_time + state->duration, &clip_start,
626 /* No need to parse that text if it's out of segment */
628 state->start_time = clip_start;
629 state->duration = clip_stop - clip_start;
634 markup = g_string_new (NULL);
639 /* parse style markup */
640 if (strncmp (line, "{y:i}", 5) == 0) {
642 line = strchr (line, '}') + 1;
644 if (strncmp (line, "{y:b}", 5) == 0) {
646 line = strchr (line, '}') + 1;
648 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
649 line = strchr (line, '}') + 1;
651 /* forward slashes at beginning/end signify italics too */
652 if (g_str_has_prefix (line, "/")) {
656 if ((line_split = strchr (line, '|')))
657 line_chunk = g_markup_escape_text (line, line_split - line);
659 line_chunk = g_markup_escape_text (line, strlen (line));
661 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
662 * always at the end of a line or can they span multiple lines?) */
663 if (g_str_has_suffix (line_chunk, "/")) {
664 line_chunk[strlen (line_chunk) - 1] = '\0';
667 markup = g_string_append (markup, "<span");
669 g_string_append (markup, " style=\"italic\"");
671 g_string_append (markup, " weight=\"bold\"");
673 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
674 g_string_append_printf (markup, ">%s</span>", line_chunk);
677 g_string_append (markup, "\n");
678 line = line_split + 1;
684 g_string_free (markup, FALSE);
685 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
686 state->start_time / (double) GST_SECOND,
687 state->duration / (double) GST_SECOND, ret);
692 strip_trailing_newlines (gchar * txt)
698 while (len > 1 && txt[len - 1] == '\n') {
705 /* we want to escape text in general, but retain basic markup like
706 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
707 * just unescape a white list of allowed markups again after
708 * escaping everything (the text between these simple markers isn't
709 * necessarily escaped, so it seems best to do it like this) */
711 subrip_unescape_formatting (gchar * txt)
715 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
716 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
717 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
718 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
720 pos[1] = g_ascii_tolower (pos[4]);
722 /* move NUL terminator as well */
723 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
728 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
729 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
730 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
731 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
734 pos[2] = g_ascii_tolower (pos[5]);
736 /* move NUL terminator as well */
737 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
745 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
749 tag = start + strlen ("<");
753 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
758 GST_LOG ("removing unhandled tag '%s'", start);
760 g_memmove (start, stop, strlen (stop) + 1);
764 /* remove tags we haven't explicitly allowed earlier on, like font tags
767 subrip_remove_unhandled_tags (gchar * txt)
771 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
772 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
773 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
779 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
780 * assumes the input has been escaped and subrip_unescape_formatting() has then
781 * been run over the input! This function adds missing closing markup tags and
782 * removes broken closing tags for tags that have never been opened. */
784 subrip_fix_up_markup (gchar ** p_txt)
786 gchar *cur, *next_tag;
788 guint num_open_tags = 0;
790 g_assert (*p_txt != NULL);
793 while (*cur != '\0') {
794 next_tag = strchr (cur, '<');
795 if (next_tag == NULL)
801 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
802 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
803 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
806 /* it's all good, closing tag which is open */
814 if (num_open_tags == G_N_ELEMENTS (open_tags))
815 return; /* something dodgy is going on, stop parsing */
816 open_tags[num_open_tags] = *next_tag;
820 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
821 g_assert_not_reached ();
827 if (num_open_tags > 0) {
830 s = g_string_new (*p_txt);
831 while (num_open_tags > 0) {
832 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
833 g_string_append_c (s, '<');
834 g_string_append_c (s, '/');
835 g_string_append_c (s, open_tags[num_open_tags - 1]);
836 g_string_append_c (s, '>');
840 *p_txt = g_string_free (s, FALSE);
845 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
847 gchar s[128] = { '\0', };
849 guint hour, min, sec, msec, len;
851 while (*ts_string == ' ')
854 g_strlcpy (s, ts_string, sizeof (s));
855 if ((end = strstr (s, "-->")))
859 /* ms may be in these formats:
860 * hh:mm:ss,500 = 500ms
863 * hh:mm:ss, 50 = 50ms
865 * and the same with . instead of ,.
866 * sscanf() doesn't differentiate between ' 5' and '5' so munge
867 * the white spaces within the timestamp to '0' (I'm sure there's a
868 * way to make sscanf() do this for us, but how?)
870 g_strdelimit (s, " ", '0');
871 g_strdelimit (s, ".", ',');
873 /* make sure we have exactly three digits after he comma */
875 g_assert (p != NULL);
882 g_strlcat (&p[len], "0", 2);
886 GST_LOG ("parsing timestamp '%s'", s);
887 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
888 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
892 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
897 parse_subrip (ParserState * state, const gchar * line)
902 switch (state->state) {
904 /* looking for a single integer */
905 if (sscanf (line, "%u", &subnum) == 1)
910 GstClockTime ts_start, ts_end;
913 /* looking for start_time --> end_time */
914 if ((end_time = strstr (line, " --> ")) &&
915 parse_subrip_time (line, &ts_start) &&
916 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
917 state->start_time <= ts_end) {
919 state->start_time = ts_start;
920 state->duration = ts_end - ts_start;
922 GST_DEBUG ("error parsing subrip time line '%s'", line);
929 /* No need to parse that text if it's out of segment */
930 gint64 clip_start = 0, clip_stop = 0;
931 gboolean in_seg = FALSE;
933 /* Check our segment start/stop */
934 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
935 state->start_time, state->start_time + state->duration,
936 &clip_start, &clip_stop);
939 state->start_time = clip_start;
940 state->duration = clip_stop - clip_start;
946 /* looking for subtitle text; empty line ends this subtitle entry */
948 g_string_append_c (state->buf, '\n');
949 g_string_append (state->buf, line);
950 if (strlen (line) == 0) {
951 ret = g_markup_escape_text (state->buf->str, state->buf->len);
952 g_string_truncate (state->buf, 0);
954 subrip_unescape_formatting (ret);
955 subrip_remove_unhandled_tags (ret);
956 strip_trailing_newlines (ret);
957 subrip_fix_up_markup (&ret);
962 g_return_val_if_reached (NULL);
967 unescape_newlines_br (gchar * read)
971 /* Replace all occurences of '[br]' with a newline as version 2
972 * of the subviewer format uses this for newlines */
974 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
978 if (strncmp (read, "[br]", 4) == 0) {
992 parse_subviewer (ParserState * state, const gchar * line)
994 guint h1, m1, s1, ms1;
995 guint h2, m2, s2, ms2;
998 /* TODO: Maybe also parse the fields in the header, especially DELAY.
999 * For examples see the unit test or
1000 * http://www.doom9.org/index.html?/sub.htm */
1002 switch (state->state) {
1004 /* looking for start_time,end_time */
1005 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1006 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1009 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1012 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1013 ms2 * GST_MSECOND - state->start_time;
1018 /* No need to parse that text if it's out of segment */
1019 gint64 clip_start = 0, clip_stop = 0;
1020 gboolean in_seg = FALSE;
1022 /* Check our segment start/stop */
1023 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1024 state->start_time, state->start_time + state->duration,
1025 &clip_start, &clip_stop);
1028 state->start_time = clip_start;
1029 state->duration = clip_stop - clip_start;
1035 /* looking for subtitle text; empty line ends this subtitle entry */
1036 if (state->buf->len)
1037 g_string_append_c (state->buf, '\n');
1038 g_string_append (state->buf, line);
1039 if (strlen (line) == 0) {
1040 ret = g_strdup (state->buf->str);
1041 unescape_newlines_br (ret);
1042 strip_trailing_newlines (ret);
1043 g_string_truncate (state->buf, 0);
1049 g_assert_not_reached ();
1055 parse_mpsub (ParserState * state, const gchar * line)
1060 switch (state->state) {
1062 /* looking for two floats (offset, duration) */
1063 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1065 state->start_time += state->duration + GST_SECOND * t1;
1066 state->duration = GST_SECOND * t2;
1070 { /* No need to parse that text if it's out of segment */
1071 gint64 clip_start = 0, clip_stop = 0;
1072 gboolean in_seg = FALSE;
1074 /* Check our segment start/stop */
1075 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1076 state->start_time, state->start_time + state->duration,
1077 &clip_start, &clip_stop);
1080 state->start_time = clip_start;
1081 state->duration = clip_stop - clip_start;
1087 /* looking for subtitle text; empty line ends this
1089 if (state->buf->len)
1090 g_string_append_c (state->buf, '\n');
1091 g_string_append (state->buf, line);
1092 if (strlen (line) == 0) {
1093 ret = g_strdup (state->buf->str);
1094 g_string_truncate (state->buf, 0);
1100 g_assert_not_reached ();
1105 static const gchar *
1106 dks_skip_timestamp (const gchar * line)
1108 while (*line && *line != ']')
1116 parse_dks (ParserState * state, const gchar * line)
1120 switch (state->state) {
1122 /* Looking for the start time and text */
1123 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1125 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1126 text = dks_skip_timestamp (line);
1129 g_string_append (state->buf, text);
1135 gint64 clip_start = 0, clip_stop = 0;
1139 /* Looking for the end time */
1140 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1142 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1145 GST_WARNING ("Failed to parse subtitle end time");
1149 /* Check if this subtitle is out of the current segment */
1150 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1151 state->start_time, state->start_time + state->duration,
1152 &clip_start, &clip_stop);
1158 state->start_time = clip_start;
1159 state->duration = clip_stop - clip_start;
1161 ret = g_strdup (state->buf->str);
1162 g_string_truncate (state->buf, 0);
1163 unescape_newlines_br (ret);
1167 g_assert_not_reached ();
1173 parser_state_init (ParserState * state)
1175 GST_DEBUG ("initialising parser");
1178 g_string_truncate (state->buf, 0);
1180 state->buf = g_string_new (NULL);
1183 state->start_time = 0;
1184 state->duration = 0;
1185 state->max_duration = 0; /* no limit */
1187 state->segment = NULL;
1191 parser_state_dispose (ParserState * state)
1194 g_string_free (state->buf, TRUE);
1197 #ifndef GST_DISABLE_XML
1198 if (state->user_data) {
1199 sami_context_reset (state);
1204 /* regex type enum */
1207 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1208 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1209 GST_SUB_PARSE_REGEX_SUBRIP = 2,
1210 GST_SUB_PARSE_REGEX_DKS = 3,
1214 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1216 gpointer result = NULL;
1217 GError *gerr = NULL;
1219 case GST_SUB_PARSE_REGEX_MDVDSUB:
1221 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}", 0, 0, &gerr);
1222 if (result == NULL) {
1223 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1224 g_error_free (gerr);
1227 case GST_SUB_PARSE_REGEX_SUBRIP:
1228 result = (gpointer) g_regex_new ("^([ 0-9]){0,3}[0-9]\\s*(\x0d)?\x0a"
1229 "[ 0-9][0-9]:[ 0-9][0-9]:[ 0-9][0-9][,.][ 0-9]{0,2}[0-9]"
1230 " +--> +([ 0-9])?[0-9]:[ 0-9][0-9]:[ 0-9][0-9][,.][ 0-9]{0,2}[0-9]",
1232 if (result == NULL) {
1233 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1234 g_error_free (gerr);
1237 case GST_SUB_PARSE_REGEX_DKS:
1238 result = (gpointer) g_regex_new ("^\[[0-9]+:[0-9]+:[0-9]+].*",
1240 if (result == NULL) {
1241 g_warning ("Compilation of dks regex failed: %s", gerr->message);
1242 g_error_free (gerr);
1246 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1252 * FIXME: maybe we should pass along a second argument, the preceding
1253 * text buffer, because that is how this originally worked, even though
1254 * I don't really see the use of that.
1257 static GstSubParseFormat
1258 gst_sub_parse_data_format_autodetect (gchar * match_str)
1262 static GOnce mdvd_rx_once = G_ONCE_INIT;
1263 static GOnce subrip_rx_once = G_ONCE_INIT;
1264 static GOnce dks_rx_once = G_ONCE_INIT;
1270 g_once (&mdvd_rx_once,
1271 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1272 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1273 g_once (&subrip_rx_once,
1274 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1275 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1276 g_once (&dks_rx_once,
1277 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1278 (gpointer) GST_SUB_PARSE_REGEX_DKS);
1280 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1281 subrip_grx = (GRegex *) subrip_rx_once.retval;
1282 dks_grx = (GRegex *) dks_rx_once.retval;
1284 if (g_regex_match (mdvd_grx, match_str, 0, NULL) == TRUE) {
1285 GST_LOG ("MicroDVD (frame based) format detected");
1286 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1288 if (g_regex_match (subrip_grx, match_str, 0, NULL) == TRUE) {
1289 GST_LOG ("SubRip (time based) format detected");
1290 return GST_SUB_PARSE_FORMAT_SUBRIP;
1292 if (g_regex_match (dks_grx, match_str, 0, NULL) == TRUE) {
1293 GST_LOG ("DKS (time based) format detected");
1294 return GST_SUB_PARSE_FORMAT_DKS;
1297 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1298 GST_LOG ("MPSub (time based) format detected");
1299 return GST_SUB_PARSE_FORMAT_MPSUB;
1301 #ifndef GST_DISABLE_XML
1302 if (strstr (match_str, "<SAMI>") != NULL ||
1303 strstr (match_str, "<sami>") != NULL) {
1304 GST_LOG ("SAMI (time based) format detected");
1305 return GST_SUB_PARSE_FORMAT_SAMI;
1308 /* we're boldly assuming the first subtitle appears within the first hour */
1309 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1310 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1311 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1312 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1313 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1314 GST_LOG ("TMPlayer (time based) format detected");
1315 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1317 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1318 GST_LOG ("MPL2 (time based) format detected");
1319 return GST_SUB_PARSE_FORMAT_MPL2;
1321 if (strstr (match_str, "[INFORMATION]") != NULL) {
1322 GST_LOG ("SubViewer (time based) format detected");
1323 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1326 GST_DEBUG ("no subtitle format detected");
1327 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1331 gst_sub_parse_format_autodetect (GstSubParse * self)
1334 GstSubParseFormat format;
1336 if (strlen (self->textbuf->str) < 30) {
1337 GST_DEBUG ("File too small to be a subtitles file");
1341 data = g_strndup (self->textbuf->str, 35);
1342 format = gst_sub_parse_data_format_autodetect (data);
1345 self->parser_type = format;
1346 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1347 parser_state_init (&self->state);
1350 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1351 self->parse_line = parse_mdvdsub;
1352 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1353 case GST_SUB_PARSE_FORMAT_SUBRIP:
1354 self->parse_line = parse_subrip;
1355 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1356 case GST_SUB_PARSE_FORMAT_MPSUB:
1357 self->parse_line = parse_mpsub;
1358 return gst_caps_new_simple ("text/plain", NULL);
1359 #ifndef GST_DISABLE_XML
1360 case GST_SUB_PARSE_FORMAT_SAMI:
1361 self->parse_line = parse_sami;
1362 sami_context_init (&self->state);
1363 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1365 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1366 self->parse_line = parse_tmplayer;
1367 self->state.max_duration = 5 * GST_SECOND;
1368 return gst_caps_new_simple ("text/plain", NULL);
1369 case GST_SUB_PARSE_FORMAT_MPL2:
1370 self->parse_line = parse_mpl2;
1371 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1372 case GST_SUB_PARSE_FORMAT_DKS:
1373 self->parse_line = parse_dks;
1374 return gst_caps_new_simple ("text/plain", NULL);
1375 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1376 self->parse_line = parse_subviewer;
1377 return gst_caps_new_simple ("text/plain", NULL);
1378 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1380 GST_DEBUG ("no subtitle format detected");
1381 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1382 ("The input is not a valid/supported subtitle file"), (NULL));
1388 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1392 gchar *input = NULL;
1394 discont = GST_BUFFER_IS_DISCONT (buf);
1396 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1397 GST_BUFFER_OFFSET (buf) != self->offset) {
1398 self->offset = GST_BUFFER_OFFSET (buf);
1403 GST_INFO ("discontinuity");
1404 /* flush the parser state */
1405 parser_state_init (&self->state);
1406 g_string_truncate (self->textbuf, 0);
1407 gst_adapter_clear (self->adapter);
1408 #ifndef GST_DISABLE_XML
1409 sami_context_reset (&self->state);
1411 /* we could set a flag to make sure that the next buffer we push out also
1412 * has the DISCONT flag set, but there's no point really given that it's
1413 * subtitles which are discontinuous by nature. */
1416 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1417 self->next_offset = self->offset;
1419 gst_adapter_push (self->adapter, buf);
1422 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1423 gst_adapter_available (self->adapter)),
1424 (gsize) gst_adapter_available (self->adapter), &consumed);
1426 if (input && consumed > 0) {
1427 self->textbuf = g_string_append (self->textbuf, input);
1428 gst_adapter_flush (self->adapter, consumed);
1434 static GstFlowReturn
1435 handle_buffer (GstSubParse * self, GstBuffer * buf)
1437 GstFlowReturn ret = GST_FLOW_OK;
1438 GstCaps *caps = NULL;
1439 gchar *line, *subtitle;
1441 if (self->first_buffer) {
1442 self->detected_encoding =
1443 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1444 GST_BUFFER_SIZE (buf));
1445 self->first_buffer = FALSE;
1446 self->state.fps_n = self->fps_n;
1447 self->state.fps_d = self->fps_d;
1450 feed_textbuf (self, buf);
1452 /* make sure we know the format */
1453 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1454 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1455 return GST_FLOW_UNEXPECTED;
1457 if (!gst_pad_set_caps (self->srcpad, caps)) {
1458 gst_caps_unref (caps);
1459 return GST_FLOW_UNEXPECTED;
1461 gst_caps_unref (caps);
1464 if (self->subtitle_codec != NULL) {
1467 tags = gst_tag_list_new ();
1468 gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_SUBTITLE_CODEC,
1469 self->subtitle_codec, NULL);
1470 gst_element_found_tags_for_pad (GST_ELEMENT (self), self->srcpad, tags);
1474 while (!self->flushing && (line = get_next_line (self))) {
1477 /* Set segment on our parser state machine */
1478 self->state.segment = &self->segment;
1479 /* Now parse the line, out of segment lines will just return NULL */
1480 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1481 subtitle = self->parse_line (&self->state, line + offset);
1485 guint subtitle_len = strlen (subtitle);
1487 /* +1 for terminating NUL character */
1488 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1489 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1490 GST_PAD_CAPS (self->srcpad), &buf);
1492 if (ret == GST_FLOW_OK) {
1493 /* copy terminating NUL character as well */
1494 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1495 GST_BUFFER_SIZE (buf) = subtitle_len;
1496 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1497 GST_BUFFER_DURATION (buf) = self->state.duration;
1499 /* in some cases (e.g. tmplayer) we can only determine the duration
1500 * of a text chunk from the timestamp of the next text chunk; in those
1501 * cases, we probably want to limit the duration to something
1502 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1503 * just because nothing else is being said during that time */
1504 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1505 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1506 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1509 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1510 self->state.start_time);
1512 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1513 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1514 GST_TIME_ARGS (self->state.duration));
1516 ret = gst_pad_push (self->srcpad, buf);
1519 /* move this forward (the tmplayer parser needs this) */
1520 if (self->state.duration != GST_CLOCK_TIME_NONE)
1521 self->state.start_time += self->state.duration;
1526 if (ret != GST_FLOW_OK) {
1527 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1536 static GstFlowReturn
1537 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1542 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1544 /* Push newsegment if needed */
1545 if (self->need_segment) {
1546 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1549 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1550 self->segment.rate, self->segment.format,
1551 self->segment.last_stop, self->segment.stop, self->segment.time));
1552 self->need_segment = FALSE;
1555 ret = handle_buffer (self, buf);
1561 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1563 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1564 gboolean ret = FALSE;
1566 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1568 switch (GST_EVENT_TYPE (event)) {
1569 case GST_EVENT_EOS:{
1570 /* Make sure the last subrip chunk is pushed out even
1571 * if the file does not have an empty line at the end */
1572 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1573 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1574 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2) {
1575 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1577 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1578 GST_BUFFER_DATA (buf)[0] = '\n';
1579 GST_BUFFER_DATA (buf)[1] = '\n';
1580 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1581 GST_BUFFER_SIZE (buf) = 2;
1582 GST_BUFFER_OFFSET (buf) = self->offset;
1583 gst_sub_parse_chain (pad, buf);
1585 ret = gst_pad_event_default (pad, event);
1588 case GST_EVENT_NEWSEGMENT:
1592 gint64 start, stop, time;
1595 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1598 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1600 if (format == GST_FORMAT_TIME) {
1601 gst_segment_set_newsegment (&self->segment, update, rate, format,
1604 /* if not time format, we'll either start with a 0 timestamp anyway or
1605 * it's following a seek in which case we'll have saved the requested
1606 * seek segment and don't want to overwrite it (remember that on a seek
1607 * we always just seek back to the start in BYTES format and just throw
1608 * away all text that's before the requested position; if the subtitles
1609 * come from an upstream demuxer, it won't be able to handle our BYTES
1610 * seek request and instead send us a newsegment from the seek request
1611 * it received via its video pads instead, so all is fine then too) */
1615 gst_event_unref (event);
1618 case GST_EVENT_FLUSH_START:
1620 self->flushing = TRUE;
1622 ret = gst_pad_event_default (pad, event);
1625 case GST_EVENT_FLUSH_STOP:
1627 self->flushing = FALSE;
1629 ret = gst_pad_event_default (pad, event);
1633 ret = gst_pad_event_default (pad, event);
1637 gst_object_unref (self);
1643 static GstStateChangeReturn
1644 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1646 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1647 GstSubParse *self = GST_SUBPARSE (element);
1649 switch (transition) {
1650 case GST_STATE_CHANGE_READY_TO_PAUSED:
1651 /* format detection will init the parser state */
1653 self->next_offset = 0;
1654 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1655 self->valid_utf8 = TRUE;
1656 self->first_buffer = TRUE;
1657 g_free (self->detected_encoding);
1658 self->detected_encoding = NULL;
1659 g_string_truncate (self->textbuf, 0);
1660 gst_adapter_clear (self->adapter);
1666 ret = parent_class->change_state (element, transition);
1667 if (ret == GST_STATE_CHANGE_FAILURE)
1670 switch (transition) {
1671 case GST_STATE_CHANGE_PAUSED_TO_READY:
1672 parser_state_dispose (&self->state);
1673 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1686 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1687 * also, give different subtitle formats really different types */
1688 static GstStaticCaps mpl2_caps =
1689 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1690 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1692 static GstStaticCaps tmp_caps =
1693 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1694 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1696 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1697 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1699 #ifndef GST_DISABLE_XML
1700 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1701 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1704 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
1705 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
1708 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1710 GstSubParseFormat format;
1714 gchar *encoding = NULL;
1717 if (!(data = gst_type_find_peek (tf, 0, 129)))
1720 /* make sure string passed to _autodetect() is NUL-terminated */
1721 str = g_malloc0 (129);
1722 memcpy (str, data, 128);
1724 if ((encoding = detect_encoding (str, 128)) != NULL) {
1725 gchar *converted_str;
1729 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
1730 if (converted_str == NULL) {
1731 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
1737 str = converted_str;
1742 /* Check if at least the first 120 chars are valid UTF8,
1743 * otherwise convert as always */
1744 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
1745 gchar *converted_str;
1750 enc = g_getenv ("GST_SUBTITLE_ENCODING");
1751 if (enc == NULL || *enc == '\0') {
1752 /* if local encoding is UTF-8 and no encoding specified
1753 * via the environment variable, assume ISO-8859-15 */
1754 if (g_get_charset (&enc)) {
1755 enc = "ISO-8859-15";
1758 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, &err);
1759 if (converted_str == NULL) {
1760 GST_DEBUG ("Charset conversion failed: %s", err->message);
1766 str = converted_str;
1770 format = gst_sub_parse_data_format_autodetect (str);
1774 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1775 GST_DEBUG ("MicroDVD format detected");
1778 case GST_SUB_PARSE_FORMAT_SUBRIP:
1779 GST_DEBUG ("SubRip format detected");
1782 case GST_SUB_PARSE_FORMAT_MPSUB:
1783 GST_DEBUG ("MPSub format detected");
1786 #ifndef GST_DISABLE_XML
1787 case GST_SUB_PARSE_FORMAT_SAMI:
1788 GST_DEBUG ("SAMI (time-based) format detected");
1792 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1793 GST_DEBUG ("TMPlayer (time based) format detected");
1796 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1797 * returning a high probability (however, since we registered our
1798 * typefinder here with a rank of MARGINAL we should pretty much only
1799 * be called if most other typefinders have already run */
1800 case GST_SUB_PARSE_FORMAT_MPL2:
1801 GST_DEBUG ("MPL2 (time based) format detected");
1804 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1805 GST_DEBUG ("SubViewer format detected");
1808 case GST_SUB_PARSE_FORMAT_DKS:
1809 GST_DEBUG ("DKS format detected");
1813 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1814 GST_DEBUG ("no subtitle format detected");
1818 /* if we're here, it's ok */
1819 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1823 plugin_init (GstPlugin * plugin)
1825 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1829 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1831 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1832 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1835 if (!gst_element_register (plugin, "subparse",
1836 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1837 !gst_element_register (plugin, "ssaparse",
1838 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1845 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1849 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)