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"
37 #include "qttextparse.h"
39 GST_DEBUG_CATEGORY (sub_parse_debug);
41 #define DEFAULT_ENCODING NULL
51 gst_sub_parse_set_property (GObject * object, guint prop_id,
52 const GValue * value, GParamSpec * pspec);
54 gst_sub_parse_get_property (GObject * object, guint prop_id,
55 GValue * value, GParamSpec * pspec);
58 #ifndef GST_DISABLE_XML
59 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
62 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
63 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
64 "application/x-subtitle-dks; application/x-subtitle-qttext")
67 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
70 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-dks; "
71 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
72 "application/x-subtitle-qttext")
76 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
79 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
82 static void gst_sub_parse_base_init (GstSubParseClass * klass);
83 static void gst_sub_parse_class_init (GstSubParseClass * klass);
84 static void gst_sub_parse_init (GstSubParse * subparse);
86 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
87 static gboolean gst_sub_parse_src_query (GstPad * pad, GstQuery * query);
88 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
90 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
91 GstStateChange transition);
93 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
95 static GstElementClass *parent_class = NULL;
98 gst_sub_parse_get_type (void)
100 static GType sub_parse_type = 0;
102 if (!sub_parse_type) {
103 static const GTypeInfo sub_parse_info = {
104 sizeof (GstSubParseClass),
105 (GBaseInitFunc) gst_sub_parse_base_init,
107 (GClassInitFunc) gst_sub_parse_class_init,
110 sizeof (GstSubParse),
112 (GInstanceInitFunc) gst_sub_parse_init,
115 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
116 "GstSubParse", &sub_parse_info, 0);
119 return sub_parse_type;
123 gst_sub_parse_base_init (GstSubParseClass * klass)
125 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
127 gst_element_class_add_static_pad_template (element_class, &sink_templ);
128 gst_element_class_add_static_pad_template (element_class, &src_templ);
129 gst_element_class_set_details_simple (element_class,
130 "Subtitle parser", "Codec/Parser/Subtitle",
131 "Parses subtitle (.sub) files into text streams",
132 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
133 "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
137 gst_sub_parse_dispose (GObject * object)
139 GstSubParse *subparse = GST_SUBPARSE (object);
141 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
143 switch (subparse->parser_type) {
144 case GST_SUB_PARSE_FORMAT_QTTEXT:
145 qttext_context_deinit (&subparse->state);
147 #ifndef GST_DISABLE_XML
148 case GST_SUB_PARSE_FORMAT_SAMI:
149 sami_context_deinit (&subparse->state);
156 if (subparse->encoding) {
157 g_free (subparse->encoding);
158 subparse->encoding = NULL;
161 if (subparse->detected_encoding) {
162 g_free (subparse->detected_encoding);
163 subparse->detected_encoding = NULL;
166 if (subparse->adapter) {
167 g_object_unref (subparse->adapter);
168 subparse->adapter = NULL;
171 if (subparse->textbuf) {
172 g_string_free (subparse->textbuf, TRUE);
173 subparse->textbuf = NULL;
176 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
180 gst_sub_parse_class_init (GstSubParseClass * klass)
182 GObjectClass *object_class = G_OBJECT_CLASS (klass);
183 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
185 parent_class = g_type_class_peek_parent (klass);
187 object_class->dispose = gst_sub_parse_dispose;
188 object_class->set_property = gst_sub_parse_set_property;
189 object_class->get_property = gst_sub_parse_get_property;
191 element_class->change_state = gst_sub_parse_change_state;
193 g_object_class_install_property (object_class, PROP_ENCODING,
194 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
195 "Encoding to assume if input subtitles are not in UTF-8 or any other "
196 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
197 "variable will be checked for an encoding to use. If that is not set "
198 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
199 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201 g_object_class_install_property (object_class, PROP_VIDEOFPS,
202 gst_param_spec_fraction ("video-fps", "Video framerate",
203 "Framerate of the video stream. This is needed by some subtitle "
204 "formats to synchronize subtitles and video properly. If not set "
205 "and the subtitle format requires it subtitles may be out of sync.",
206 0, 1, G_MAXINT, 1, 24000, 1001,
207 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
211 gst_sub_parse_init (GstSubParse * subparse)
213 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
214 gst_pad_set_chain_function (subparse->sinkpad,
215 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
216 gst_pad_set_event_function (subparse->sinkpad,
217 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
218 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
220 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
221 gst_pad_set_event_function (subparse->srcpad,
222 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
223 gst_pad_set_query_function (subparse->srcpad,
224 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
225 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
227 subparse->textbuf = g_string_new (NULL);
228 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
229 subparse->flushing = FALSE;
230 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
231 subparse->need_segment = TRUE;
232 subparse->encoding = g_strdup (DEFAULT_ENCODING);
233 subparse->detected_encoding = NULL;
234 subparse->adapter = gst_adapter_new ();
236 subparse->fps_n = 24000;
237 subparse->fps_d = 1001;
241 * Source pad functions.
245 gst_sub_parse_src_query (GstPad * pad, GstQuery * query)
247 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
248 gboolean ret = FALSE;
250 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
252 switch (GST_QUERY_TYPE (query)) {
253 case GST_QUERY_POSITION:{
256 gst_query_parse_position (query, &fmt, NULL);
257 if (fmt != GST_FORMAT_TIME) {
258 ret = gst_pad_peer_query (self->sinkpad, query);
261 gst_query_set_position (query, GST_FORMAT_TIME,
262 self->segment.last_stop);
266 case GST_QUERY_SEEKING:
269 gboolean seekable = FALSE;
273 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
274 if (fmt == GST_FORMAT_TIME) {
275 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
277 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
279 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
280 gst_query_unref (peerquery);
283 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
287 ret = gst_pad_peer_query (self->sinkpad, query);
291 gst_object_unref (self);
297 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
299 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
300 gboolean ret = FALSE;
302 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
304 switch (GST_EVENT_TYPE (event)) {
308 GstSeekType start_type, stop_type;
313 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
314 &start_type, &start, &stop_type, &stop);
316 if (format != GST_FORMAT_TIME) {
317 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
318 gst_event_unref (event);
322 /* Convert that seek to a seeking in bytes at position 0,
323 FIXME: could use an index */
324 ret = gst_pad_push_event (self->sinkpad,
325 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
326 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
329 /* Apply the seek to our segment */
330 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
331 start_type, start, stop_type, stop, &update);
333 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
336 self->next_offset = 0;
338 self->need_segment = TRUE;
340 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
343 gst_event_unref (event);
347 ret = gst_pad_event_default (pad, event);
352 gst_object_unref (self);
358 gst_sub_parse_set_property (GObject * object, guint prop_id,
359 const GValue * value, GParamSpec * pspec)
361 GstSubParse *subparse = GST_SUBPARSE (object);
363 GST_OBJECT_LOCK (subparse);
366 g_free (subparse->encoding);
367 subparse->encoding = g_value_dup_string (value);
368 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
369 GST_STR_NULL (subparse->encoding));
373 subparse->fps_n = gst_value_get_fraction_numerator (value);
374 subparse->fps_d = gst_value_get_fraction_denominator (value);
375 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
378 if (!subparse->state.have_internal_fps) {
379 subparse->state.fps_n = subparse->fps_n;
380 subparse->state.fps_d = subparse->fps_d;
385 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
388 GST_OBJECT_UNLOCK (subparse);
392 gst_sub_parse_get_property (GObject * object, guint prop_id,
393 GValue * value, GParamSpec * pspec)
395 GstSubParse *subparse = GST_SUBPARSE (object);
397 GST_OBJECT_LOCK (subparse);
400 g_value_set_string (value, subparse->encoding);
403 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
406 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
409 GST_OBJECT_UNLOCK (subparse);
413 gst_sub_parse_get_format_description (GstSubParseFormat format)
416 case GST_SUB_PARSE_FORMAT_MDVDSUB:
418 case GST_SUB_PARSE_FORMAT_SUBRIP:
420 case GST_SUB_PARSE_FORMAT_MPSUB:
422 case GST_SUB_PARSE_FORMAT_SAMI:
424 case GST_SUB_PARSE_FORMAT_TMPLAYER:
426 case GST_SUB_PARSE_FORMAT_MPL2:
428 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
430 case GST_SUB_PARSE_FORMAT_DKS:
432 case GST_SUB_PARSE_FORMAT_QTTEXT:
435 case GST_SUB_PARSE_FORMAT_UNKNOWN:
442 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
443 gsize * consumed, GError ** err)
448 /* The char cast is necessary in glib < 2.24 */
450 g_convert_with_fallback (str, len, "UTF-8", encoding, (char *) "*",
451 consumed, NULL, err);
455 /* + 3 to skip UTF-8 BOM if it was added */
457 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
458 && (guint8) ret[2] == 0xBF)
459 g_memmove (ret, ret + 3, len + 1 - 3);
465 detect_encoding (const gchar * str, gsize len)
467 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
468 && (guint8) str[2] == 0xBF)
469 return g_strdup ("UTF-8");
471 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
472 return g_strdup ("UTF-16BE");
474 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
475 return g_strdup ("UTF-16LE");
477 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
478 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
479 return g_strdup ("UTF-32BE");
481 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
482 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
483 return g_strdup ("UTF-32LE");
489 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
492 const gchar *encoding;
498 /* First try any detected encoding */
499 if (self->detected_encoding) {
501 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
506 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
507 self->detected_encoding, err->message);
508 g_free (self->detected_encoding);
509 self->detected_encoding = NULL;
513 /* Otherwise check if it's UTF8 */
514 if (self->valid_utf8) {
515 if (g_utf8_validate (str, len, NULL)) {
516 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
518 return g_strndup (str, len);
520 GST_INFO_OBJECT (self, "invalid UTF-8!");
521 self->valid_utf8 = FALSE;
524 /* Else try fallback */
525 encoding = self->encoding;
526 if (encoding == NULL || *encoding == '\0') {
527 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
529 if (encoding == NULL || *encoding == '\0') {
530 /* if local encoding is UTF-8 and no encoding specified
531 * via the environment variable, assume ISO-8859-15 */
532 if (g_get_charset (&encoding)) {
533 encoding = "ISO-8859-15";
537 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
540 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
541 encoding, err->message);
544 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
545 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
548 GST_LOG_OBJECT (self,
549 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
550 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
556 get_next_line (GstSubParse * self)
559 const char *line_end;
561 gboolean have_r = FALSE;
563 line_end = strchr (self->textbuf->str, '\n');
566 /* end-of-line not found; return for more data */
570 /* get rid of '\r' */
571 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
576 line_len = line_end - self->textbuf->str;
577 line = g_strndup (self->textbuf->str, line_len);
578 self->textbuf = g_string_erase (self->textbuf, 0,
579 line_len + (have_r ? 2 : 1));
584 parse_mdvdsub (ParserState * state, const gchar * line)
586 const gchar *line_split;
588 guint start_frame, end_frame;
589 gint64 clip_start = 0, clip_stop = 0;
590 gboolean in_seg = FALSE;
594 /* style variables */
600 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
601 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
602 " format, failed:\n%s", line);
606 /* skip the {%u}{%u} part */
607 line = strchr (line, '}') + 1;
608 line = strchr (line, '}') + 1;
610 /* see if there's a first line with a framerate */
611 if (start_frame == 1 && end_frame == 1) {
612 gchar *rest, *end = NULL;
614 rest = g_strdup (line);
615 g_strdelimit (rest, ",", '.');
616 fps = g_ascii_strtod (rest, &end);
618 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
619 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
627 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
630 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
633 /* Check our segment start/stop */
634 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
635 state->start_time, state->start_time + state->duration, &clip_start,
638 /* No need to parse that text if it's out of segment */
640 state->start_time = clip_start;
641 state->duration = clip_stop - clip_start;
646 markup = g_string_new (NULL);
651 /* parse style markup */
652 if (strncmp (line, "{y:i}", 5) == 0) {
654 line = strchr (line, '}') + 1;
656 if (strncmp (line, "{y:b}", 5) == 0) {
658 line = strchr (line, '}') + 1;
660 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
661 line = strchr (line, '}') + 1;
663 /* forward slashes at beginning/end signify italics too */
664 if (g_str_has_prefix (line, "/")) {
668 if ((line_split = strchr (line, '|')))
669 line_chunk = g_markup_escape_text (line, line_split - line);
671 line_chunk = g_markup_escape_text (line, strlen (line));
673 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
674 * always at the end of a line or can they span multiple lines?) */
675 if (g_str_has_suffix (line_chunk, "/")) {
676 line_chunk[strlen (line_chunk) - 1] = '\0';
679 markup = g_string_append (markup, "<span");
681 g_string_append (markup, " style=\"italic\"");
683 g_string_append (markup, " weight=\"bold\"");
685 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
686 g_string_append_printf (markup, ">%s</span>", line_chunk);
689 g_string_append (markup, "\n");
690 line = line_split + 1;
696 g_string_free (markup, FALSE);
697 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
698 state->start_time / (double) GST_SECOND,
699 state->duration / (double) GST_SECOND, ret);
704 strip_trailing_newlines (gchar * txt)
710 while (len > 1 && txt[len - 1] == '\n') {
717 /* we want to escape text in general, but retain basic markup like
718 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
719 * just unescape a white list of allowed markups again after
720 * escaping everything (the text between these simple markers isn't
721 * necessarily escaped, so it seems best to do it like this) */
723 subrip_unescape_formatting (gchar * txt)
727 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
728 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
729 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
730 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
732 pos[1] = g_ascii_tolower (pos[4]);
734 /* move NUL terminator as well */
735 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
740 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
741 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
742 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
743 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
746 pos[2] = g_ascii_tolower (pos[5]);
748 /* move NUL terminator as well */
749 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
757 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
761 tag = start + strlen ("<");
765 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
770 GST_LOG ("removing unhandled tag '%s'", start);
772 g_memmove (start, stop, strlen (stop) + 1);
776 /* remove tags we haven't explicitly allowed earlier on, like font tags
779 subrip_remove_unhandled_tags (gchar * txt)
783 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
784 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
785 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
791 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
792 * assumes the input has been escaped and subrip_unescape_formatting() has then
793 * been run over the input! This function adds missing closing markup tags and
794 * removes broken closing tags for tags that have never been opened. */
796 subrip_fix_up_markup (gchar ** p_txt)
798 gchar *cur, *next_tag;
800 guint num_open_tags = 0;
802 g_assert (*p_txt != NULL);
805 while (*cur != '\0') {
806 next_tag = strchr (cur, '<');
807 if (next_tag == NULL)
813 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
814 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
815 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
818 /* it's all good, closing tag which is open */
826 if (num_open_tags == G_N_ELEMENTS (open_tags))
827 return; /* something dodgy is going on, stop parsing */
828 open_tags[num_open_tags] = *next_tag;
832 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
833 g_assert_not_reached ();
839 if (num_open_tags > 0) {
842 s = g_string_new (*p_txt);
843 while (num_open_tags > 0) {
844 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
845 g_string_append_c (s, '<');
846 g_string_append_c (s, '/');
847 g_string_append_c (s, open_tags[num_open_tags - 1]);
848 g_string_append_c (s, '>');
852 *p_txt = g_string_free (s, FALSE);
857 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
859 gchar s[128] = { '\0', };
861 guint hour, min, sec, msec, len;
863 while (*ts_string == ' ')
866 g_strlcpy (s, ts_string, sizeof (s));
867 if ((end = strstr (s, "-->")))
871 /* ms may be in these formats:
872 * hh:mm:ss,500 = 500ms
875 * hh:mm:ss, 50 = 50ms
877 * and the same with . instead of ,.
878 * sscanf() doesn't differentiate between ' 5' and '5' so munge
879 * the white spaces within the timestamp to '0' (I'm sure there's a
880 * way to make sscanf() do this for us, but how?)
882 g_strdelimit (s, " ", '0');
883 g_strdelimit (s, ".", ',');
885 /* make sure we have exactly three digits after he comma */
887 g_assert (p != NULL);
894 g_strlcat (&p[len], "0", 2);
898 GST_LOG ("parsing timestamp '%s'", s);
899 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
900 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
904 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
909 parse_subrip (ParserState * state, const gchar * line)
914 switch (state->state) {
916 /* looking for a single integer */
917 if (sscanf (line, "%u", &subnum) == 1)
922 GstClockTime ts_start, ts_end;
925 /* looking for start_time --> end_time */
926 if ((end_time = strstr (line, " --> ")) &&
927 parse_subrip_time (line, &ts_start) &&
928 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
929 state->start_time <= ts_end) {
931 state->start_time = ts_start;
932 state->duration = ts_end - ts_start;
934 GST_DEBUG ("error parsing subrip time line '%s'", line);
941 /* No need to parse that text if it's out of segment */
942 gint64 clip_start = 0, clip_stop = 0;
943 gboolean in_seg = FALSE;
945 /* Check our segment start/stop */
946 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
947 state->start_time, state->start_time + state->duration,
948 &clip_start, &clip_stop);
951 state->start_time = clip_start;
952 state->duration = clip_stop - clip_start;
958 /* looking for subtitle text; empty line ends this subtitle entry */
960 g_string_append_c (state->buf, '\n');
961 g_string_append (state->buf, line);
962 if (strlen (line) == 0) {
963 ret = g_markup_escape_text (state->buf->str, state->buf->len);
964 g_string_truncate (state->buf, 0);
966 subrip_unescape_formatting (ret);
967 subrip_remove_unhandled_tags (ret);
968 strip_trailing_newlines (ret);
969 subrip_fix_up_markup (&ret);
974 g_return_val_if_reached (NULL);
979 unescape_newlines_br (gchar * read)
983 /* Replace all occurences of '[br]' with a newline as version 2
984 * of the subviewer format uses this for newlines */
986 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
990 if (strncmp (read, "[br]", 4) == 0) {
1004 parse_subviewer (ParserState * state, const gchar * line)
1006 guint h1, m1, s1, ms1;
1007 guint h2, m2, s2, ms2;
1010 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1011 * For examples see the unit test or
1012 * http://www.doom9.org/index.html?/sub.htm */
1014 switch (state->state) {
1016 /* looking for start_time,end_time */
1017 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1018 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1021 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1024 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1025 ms2 * GST_MSECOND - state->start_time;
1030 /* No need to parse that text if it's out of segment */
1031 gint64 clip_start = 0, clip_stop = 0;
1032 gboolean in_seg = FALSE;
1034 /* Check our segment start/stop */
1035 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1036 state->start_time, state->start_time + state->duration,
1037 &clip_start, &clip_stop);
1040 state->start_time = clip_start;
1041 state->duration = clip_stop - clip_start;
1047 /* looking for subtitle text; empty line ends this subtitle entry */
1048 if (state->buf->len)
1049 g_string_append_c (state->buf, '\n');
1050 g_string_append (state->buf, line);
1051 if (strlen (line) == 0) {
1052 ret = g_strdup (state->buf->str);
1053 unescape_newlines_br (ret);
1054 strip_trailing_newlines (ret);
1055 g_string_truncate (state->buf, 0);
1061 g_assert_not_reached ();
1067 parse_mpsub (ParserState * state, const gchar * line)
1072 switch (state->state) {
1074 /* looking for two floats (offset, duration) */
1075 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1077 state->start_time += state->duration + GST_SECOND * t1;
1078 state->duration = GST_SECOND * t2;
1082 { /* No need to parse that text if it's out of segment */
1083 gint64 clip_start = 0, clip_stop = 0;
1084 gboolean in_seg = FALSE;
1086 /* Check our segment start/stop */
1087 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1088 state->start_time, state->start_time + state->duration,
1089 &clip_start, &clip_stop);
1092 state->start_time = clip_start;
1093 state->duration = clip_stop - clip_start;
1099 /* looking for subtitle text; empty line ends this
1101 if (state->buf->len)
1102 g_string_append_c (state->buf, '\n');
1103 g_string_append (state->buf, line);
1104 if (strlen (line) == 0) {
1105 ret = g_strdup (state->buf->str);
1106 g_string_truncate (state->buf, 0);
1112 g_assert_not_reached ();
1117 static const gchar *
1118 dks_skip_timestamp (const gchar * line)
1120 while (*line && *line != ']')
1128 parse_dks (ParserState * state, const gchar * line)
1132 switch (state->state) {
1134 /* Looking for the start time and text */
1135 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1137 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1138 text = dks_skip_timestamp (line);
1141 g_string_append (state->buf, text);
1147 gint64 clip_start = 0, clip_stop = 0;
1151 /* Looking for the end time */
1152 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1154 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1157 GST_WARNING ("Failed to parse subtitle end time");
1161 /* Check if this subtitle is out of the current segment */
1162 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1163 state->start_time, state->start_time + state->duration,
1164 &clip_start, &clip_stop);
1170 state->start_time = clip_start;
1171 state->duration = clip_stop - clip_start;
1173 ret = g_strdup (state->buf->str);
1174 g_string_truncate (state->buf, 0);
1175 unescape_newlines_br (ret);
1179 g_assert_not_reached ();
1185 parser_state_init (ParserState * state)
1187 GST_DEBUG ("initialising parser");
1190 g_string_truncate (state->buf, 0);
1192 state->buf = g_string_new (NULL);
1195 state->start_time = 0;
1196 state->duration = 0;
1197 state->max_duration = 0; /* no limit */
1199 state->segment = NULL;
1203 parser_state_dispose (GstSubParse * self, ParserState * state)
1206 g_string_free (state->buf, TRUE);
1209 if (state->user_data) {
1210 switch (self->parser_type) {
1211 #ifndef GST_DISABLE_XML
1212 case GST_SUB_PARSE_FORMAT_SAMI:
1213 sami_context_reset (state);
1222 /* regex type enum */
1225 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1226 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1227 GST_SUB_PARSE_REGEX_SUBRIP = 2,
1228 GST_SUB_PARSE_REGEX_DKS = 3,
1232 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1234 gpointer result = NULL;
1235 GError *gerr = NULL;
1237 case GST_SUB_PARSE_REGEX_MDVDSUB:
1239 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}",
1240 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1241 if (result == NULL) {
1242 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1243 g_error_free (gerr);
1246 case GST_SUB_PARSE_REGEX_SUBRIP:
1247 result = (gpointer) g_regex_new ("^ {0,3}[ 0-9]{1,4}\\s*(\x0d)?\x0a"
1248 " ?[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,3}"
1249 " +--> +[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,2}",
1250 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1251 if (result == NULL) {
1252 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1253 g_error_free (gerr);
1256 case GST_SUB_PARSE_REGEX_DKS:
1257 result = (gpointer) g_regex_new ("^\\[[0-9]+:[0-9]+:[0-9]+\\].*",
1258 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1259 if (result == NULL) {
1260 g_warning ("Compilation of dks regex failed: %s", gerr->message);
1261 g_error_free (gerr);
1265 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1271 * FIXME: maybe we should pass along a second argument, the preceding
1272 * text buffer, because that is how this originally worked, even though
1273 * I don't really see the use of that.
1276 static GstSubParseFormat
1277 gst_sub_parse_data_format_autodetect (gchar * match_str)
1281 static GOnce mdvd_rx_once = G_ONCE_INIT;
1282 static GOnce subrip_rx_once = G_ONCE_INIT;
1283 static GOnce dks_rx_once = G_ONCE_INIT;
1289 g_once (&mdvd_rx_once,
1290 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1291 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1292 g_once (&subrip_rx_once,
1293 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1294 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1295 g_once (&dks_rx_once,
1296 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1297 (gpointer) GST_SUB_PARSE_REGEX_DKS);
1299 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1300 subrip_grx = (GRegex *) subrip_rx_once.retval;
1301 dks_grx = (GRegex *) dks_rx_once.retval;
1303 if (g_regex_match (mdvd_grx, match_str, 0, NULL) == TRUE) {
1304 GST_LOG ("MicroDVD (frame based) format detected");
1305 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1307 if (g_regex_match (subrip_grx, match_str, 0, NULL) == TRUE) {
1308 GST_LOG ("SubRip (time based) format detected");
1309 return GST_SUB_PARSE_FORMAT_SUBRIP;
1311 if (g_regex_match (dks_grx, match_str, 0, NULL) == TRUE) {
1312 GST_LOG ("DKS (time based) format detected");
1313 return GST_SUB_PARSE_FORMAT_DKS;
1316 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1317 GST_LOG ("MPSub (time based) format detected");
1318 return GST_SUB_PARSE_FORMAT_MPSUB;
1320 #ifndef GST_DISABLE_XML
1321 if (strstr (match_str, "<SAMI>") != NULL ||
1322 strstr (match_str, "<sami>") != NULL) {
1323 GST_LOG ("SAMI (time based) format detected");
1324 return GST_SUB_PARSE_FORMAT_SAMI;
1327 /* we're boldly assuming the first subtitle appears within the first hour */
1328 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1329 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1330 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1331 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1332 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1333 GST_LOG ("TMPlayer (time based) format detected");
1334 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1336 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1337 GST_LOG ("MPL2 (time based) format detected");
1338 return GST_SUB_PARSE_FORMAT_MPL2;
1340 if (strstr (match_str, "[INFORMATION]") != NULL) {
1341 GST_LOG ("SubViewer (time based) format detected");
1342 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1344 if (strstr (match_str, "{QTtext}") != NULL) {
1345 GST_LOG ("QTtext (time based) format detected");
1346 return GST_SUB_PARSE_FORMAT_QTTEXT;
1349 GST_DEBUG ("no subtitle format detected");
1350 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1354 gst_sub_parse_format_autodetect (GstSubParse * self)
1357 GstSubParseFormat format;
1359 if (strlen (self->textbuf->str) < 30) {
1360 GST_DEBUG ("File too small to be a subtitles file");
1364 data = g_strndup (self->textbuf->str, 35);
1365 format = gst_sub_parse_data_format_autodetect (data);
1368 self->parser_type = format;
1369 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1370 parser_state_init (&self->state);
1373 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1374 self->parse_line = parse_mdvdsub;
1375 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1376 case GST_SUB_PARSE_FORMAT_SUBRIP:
1377 self->parse_line = parse_subrip;
1378 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1379 case GST_SUB_PARSE_FORMAT_MPSUB:
1380 self->parse_line = parse_mpsub;
1381 return gst_caps_new_simple ("text/plain", NULL);
1382 #ifndef GST_DISABLE_XML
1383 case GST_SUB_PARSE_FORMAT_SAMI:
1384 self->parse_line = parse_sami;
1385 sami_context_init (&self->state);
1386 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1388 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1389 self->parse_line = parse_tmplayer;
1390 self->state.max_duration = 5 * GST_SECOND;
1391 return gst_caps_new_simple ("text/plain", NULL);
1392 case GST_SUB_PARSE_FORMAT_MPL2:
1393 self->parse_line = parse_mpl2;
1394 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1395 case GST_SUB_PARSE_FORMAT_DKS:
1396 self->parse_line = parse_dks;
1397 return gst_caps_new_simple ("text/plain", NULL);
1398 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1399 self->parse_line = parse_subviewer;
1400 return gst_caps_new_simple ("text/plain", NULL);
1401 case GST_SUB_PARSE_FORMAT_QTTEXT:
1402 self->parse_line = parse_qttext;
1403 qttext_context_init (&self->state);
1404 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1405 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1407 GST_DEBUG ("no subtitle format detected");
1408 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1409 ("The input is not a valid/supported subtitle file"), (NULL));
1415 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1419 gchar *input = NULL;
1421 discont = GST_BUFFER_IS_DISCONT (buf);
1423 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1424 GST_BUFFER_OFFSET (buf) != self->offset) {
1425 self->offset = GST_BUFFER_OFFSET (buf);
1430 GST_INFO ("discontinuity");
1431 /* flush the parser state */
1432 parser_state_init (&self->state);
1433 g_string_truncate (self->textbuf, 0);
1434 gst_adapter_clear (self->adapter);
1435 #ifndef GST_DISABLE_XML
1436 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1437 sami_context_reset (&self->state);
1439 /* we could set a flag to make sure that the next buffer we push out also
1440 * has the DISCONT flag set, but there's no point really given that it's
1441 * subtitles which are discontinuous by nature. */
1444 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1445 self->next_offset = self->offset;
1447 gst_adapter_push (self->adapter, buf);
1450 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1451 gst_adapter_available (self->adapter)),
1452 (gsize) gst_adapter_available (self->adapter), &consumed);
1454 if (input && consumed > 0) {
1455 self->textbuf = g_string_append (self->textbuf, input);
1456 gst_adapter_flush (self->adapter, consumed);
1462 static GstFlowReturn
1463 handle_buffer (GstSubParse * self, GstBuffer * buf)
1465 GstFlowReturn ret = GST_FLOW_OK;
1466 GstCaps *caps = NULL;
1467 gchar *line, *subtitle;
1469 if (self->first_buffer) {
1470 self->detected_encoding =
1471 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1472 GST_BUFFER_SIZE (buf));
1473 self->first_buffer = FALSE;
1474 self->state.fps_n = self->fps_n;
1475 self->state.fps_d = self->fps_d;
1478 feed_textbuf (self, buf);
1480 /* make sure we know the format */
1481 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1482 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1483 return GST_FLOW_UNEXPECTED;
1485 if (!gst_pad_set_caps (self->srcpad, caps)) {
1486 gst_caps_unref (caps);
1487 return GST_FLOW_UNEXPECTED;
1489 gst_caps_unref (caps);
1492 if (self->subtitle_codec != NULL) {
1495 tags = gst_tag_list_new ();
1496 gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_SUBTITLE_CODEC,
1497 self->subtitle_codec, NULL);
1498 gst_element_found_tags_for_pad (GST_ELEMENT (self), self->srcpad, tags);
1502 while (!self->flushing && (line = get_next_line (self))) {
1505 /* Set segment on our parser state machine */
1506 self->state.segment = &self->segment;
1507 /* Now parse the line, out of segment lines will just return NULL */
1508 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1509 subtitle = self->parse_line (&self->state, line + offset);
1513 guint subtitle_len = strlen (subtitle);
1515 /* +1 for terminating NUL character */
1516 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1517 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1518 GST_PAD_CAPS (self->srcpad), &buf);
1520 if (ret == GST_FLOW_OK) {
1521 /* copy terminating NUL character as well */
1522 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1523 GST_BUFFER_SIZE (buf) = subtitle_len;
1524 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1525 GST_BUFFER_DURATION (buf) = self->state.duration;
1527 /* in some cases (e.g. tmplayer) we can only determine the duration
1528 * of a text chunk from the timestamp of the next text chunk; in those
1529 * cases, we probably want to limit the duration to something
1530 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1531 * just because nothing else is being said during that time */
1532 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1533 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1534 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1537 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1538 self->state.start_time);
1540 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1541 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1542 GST_TIME_ARGS (self->state.duration));
1544 ret = gst_pad_push (self->srcpad, buf);
1547 /* move this forward (the tmplayer parser needs this) */
1548 if (self->state.duration != GST_CLOCK_TIME_NONE)
1549 self->state.start_time += self->state.duration;
1554 if (ret != GST_FLOW_OK) {
1555 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1564 static GstFlowReturn
1565 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1570 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1572 /* Push newsegment if needed */
1573 if (self->need_segment) {
1574 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1577 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1578 self->segment.rate, self->segment.format,
1579 self->segment.last_stop, self->segment.stop, self->segment.time));
1580 self->need_segment = FALSE;
1583 ret = handle_buffer (self, buf);
1589 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1591 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1592 gboolean ret = FALSE;
1594 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1596 switch (GST_EVENT_TYPE (event)) {
1597 case GST_EVENT_EOS:{
1598 /* Make sure the last subrip chunk is pushed out even
1599 * if the file does not have an empty line at the end */
1600 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1601 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1602 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1603 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT) {
1604 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1606 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1607 GST_BUFFER_DATA (buf)[0] = '\n';
1608 GST_BUFFER_DATA (buf)[1] = '\n';
1609 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1610 GST_BUFFER_SIZE (buf) = 2;
1611 GST_BUFFER_OFFSET (buf) = self->offset;
1612 gst_sub_parse_chain (pad, buf);
1614 ret = gst_pad_event_default (pad, event);
1617 case GST_EVENT_NEWSEGMENT:
1621 gint64 start, stop, time;
1624 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1627 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1629 if (format == GST_FORMAT_TIME) {
1630 gst_segment_set_newsegment (&self->segment, update, rate, format,
1633 /* if not time format, we'll either start with a 0 timestamp anyway or
1634 * it's following a seek in which case we'll have saved the requested
1635 * seek segment and don't want to overwrite it (remember that on a seek
1636 * we always just seek back to the start in BYTES format and just throw
1637 * away all text that's before the requested position; if the subtitles
1638 * come from an upstream demuxer, it won't be able to handle our BYTES
1639 * seek request and instead send us a newsegment from the seek request
1640 * it received via its video pads instead, so all is fine then too) */
1644 gst_event_unref (event);
1647 case GST_EVENT_FLUSH_START:
1649 self->flushing = TRUE;
1651 ret = gst_pad_event_default (pad, event);
1654 case GST_EVENT_FLUSH_STOP:
1656 self->flushing = FALSE;
1658 ret = gst_pad_event_default (pad, event);
1662 ret = gst_pad_event_default (pad, event);
1666 gst_object_unref (self);
1672 static GstStateChangeReturn
1673 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1675 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1676 GstSubParse *self = GST_SUBPARSE (element);
1678 switch (transition) {
1679 case GST_STATE_CHANGE_READY_TO_PAUSED:
1680 /* format detection will init the parser state */
1682 self->next_offset = 0;
1683 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1684 self->valid_utf8 = TRUE;
1685 self->first_buffer = TRUE;
1686 g_free (self->detected_encoding);
1687 self->detected_encoding = NULL;
1688 g_string_truncate (self->textbuf, 0);
1689 gst_adapter_clear (self->adapter);
1695 ret = parent_class->change_state (element, transition);
1696 if (ret == GST_STATE_CHANGE_FAILURE)
1699 switch (transition) {
1700 case GST_STATE_CHANGE_PAUSED_TO_READY:
1701 parser_state_dispose (self, &self->state);
1702 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1715 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1716 * also, give different subtitle formats really different types */
1717 static GstStaticCaps mpl2_caps =
1718 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1719 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1721 static GstStaticCaps tmp_caps =
1722 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1723 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1725 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1726 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1728 #ifndef GST_DISABLE_XML
1729 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1730 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1733 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
1734 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
1736 static GstStaticCaps qttext_caps =
1737 GST_STATIC_CAPS ("application/x-subtitle-qttext");
1738 #define QTTEXT_CAPS (gst_static_caps_get (&qttext_caps))
1741 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1743 GstSubParseFormat format;
1747 gchar *encoding = NULL;
1750 if (!(data = gst_type_find_peek (tf, 0, 129)))
1753 /* make sure string passed to _autodetect() is NUL-terminated */
1754 str = g_malloc0 (129);
1755 memcpy (str, data, 128);
1757 if ((encoding = detect_encoding (str, 128)) != NULL) {
1758 gchar *converted_str;
1762 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
1763 if (converted_str == NULL) {
1764 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
1770 str = converted_str;
1775 /* Check if at least the first 120 chars are valid UTF8,
1776 * otherwise convert as always */
1777 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
1778 gchar *converted_str;
1783 enc = g_getenv ("GST_SUBTITLE_ENCODING");
1784 if (enc == NULL || *enc == '\0') {
1785 /* if local encoding is UTF-8 and no encoding specified
1786 * via the environment variable, assume ISO-8859-15 */
1787 if (g_get_charset (&enc)) {
1788 enc = "ISO-8859-15";
1791 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, &err);
1792 if (converted_str != NULL) {
1794 str = converted_str;
1798 format = gst_sub_parse_data_format_autodetect (str);
1802 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1803 GST_DEBUG ("MicroDVD format detected");
1806 case GST_SUB_PARSE_FORMAT_SUBRIP:
1807 GST_DEBUG ("SubRip format detected");
1810 case GST_SUB_PARSE_FORMAT_MPSUB:
1811 GST_DEBUG ("MPSub format detected");
1814 #ifndef GST_DISABLE_XML
1815 case GST_SUB_PARSE_FORMAT_SAMI:
1816 GST_DEBUG ("SAMI (time-based) format detected");
1820 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1821 GST_DEBUG ("TMPlayer (time based) format detected");
1824 /* FIXME: our MPL2 typefinding is not really good enough to warrant
1825 * returning a high probability (however, since we registered our
1826 * typefinder here with a rank of MARGINAL we should pretty much only
1827 * be called if most other typefinders have already run */
1828 case GST_SUB_PARSE_FORMAT_MPL2:
1829 GST_DEBUG ("MPL2 (time based) format detected");
1832 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1833 GST_DEBUG ("SubViewer format detected");
1836 case GST_SUB_PARSE_FORMAT_DKS:
1837 GST_DEBUG ("DKS format detected");
1840 case GST_SUB_PARSE_FORMAT_QTTEXT:
1841 GST_DEBUG ("QTtext format detected");
1845 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1846 GST_DEBUG ("no subtitle format detected");
1850 /* if we're here, it's ok */
1851 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1855 plugin_init (GstPlugin * plugin)
1857 static const gchar *sub_exts[] =
1858 { "srt", "sub", "mpsub", "mdvd", "smi", "txt", "dks", NULL };
1860 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1862 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1863 gst_subparse_type_find, (gchar **) sub_exts, SUB_CAPS, NULL, NULL))
1866 if (!gst_element_register (plugin, "subparse",
1867 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1868 !gst_element_register (plugin, "ssaparse",
1869 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1876 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1880 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)