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 #ifdef GST_EXT_ENABLE_SMI
40 #ifdef GST_DISABLE_XML
41 #undef GST_DISABLE_XML
45 GST_DEBUG_CATEGORY (sub_parse_debug);
47 #define DEFAULT_ENCODING NULL
48 #ifdef SUBPARSE_MODIFICATION
49 #define DEFAULT_CURRENT_LANGUAGE NULL
57 #ifdef SUBPARSE_MODIFICATION
58 PROP_EXTSUB_CURRENT_LANGUAGE
63 gst_sub_parse_set_property (GObject * object, guint prop_id,
64 const GValue * value, GParamSpec * pspec);
66 gst_sub_parse_get_property (GObject * object, guint prop_id,
67 GValue * value, GParamSpec * pspec);
70 #ifndef GST_DISABLE_XML
71 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
74 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
75 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
76 "application/x-subtitle-dks; application/x-subtitle-qttext")
79 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
82 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-dks; "
83 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
84 "application/x-subtitle-qttext")
88 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
91 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
94 static void gst_sub_parse_base_init (GstSubParseClass * klass);
95 static void gst_sub_parse_class_init (GstSubParseClass * klass);
96 static void gst_sub_parse_init (GstSubParse * subparse);
98 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
99 static gboolean gst_sub_parse_src_query (GstPad * pad, GstQuery * query);
100 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
102 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
103 GstStateChange transition);
105 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
107 static GstElementClass *parent_class = NULL;
110 gst_sub_parse_get_type (void)
112 static GType sub_parse_type = 0;
114 if (!sub_parse_type) {
115 static const GTypeInfo sub_parse_info = {
116 sizeof (GstSubParseClass),
117 (GBaseInitFunc) gst_sub_parse_base_init,
119 (GClassInitFunc) gst_sub_parse_class_init,
122 sizeof (GstSubParse),
124 (GInstanceInitFunc) gst_sub_parse_init,
127 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
128 "GstSubParse", &sub_parse_info, 0);
131 return sub_parse_type;
135 gst_sub_parse_base_init (GstSubParseClass * klass)
137 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
139 gst_element_class_add_static_pad_template (element_class, &sink_templ);
140 gst_element_class_add_static_pad_template (element_class, &src_templ);
141 gst_element_class_set_details_simple (element_class,
142 "Subtitle parser", "Codec/Parser/Subtitle",
143 "Parses subtitle (.sub) files into text streams",
144 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
145 "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
149 gst_sub_parse_dispose (GObject * object)
151 GstSubParse *subparse = GST_SUBPARSE (object);
153 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
155 switch (subparse->parser_type) {
156 case GST_SUB_PARSE_FORMAT_QTTEXT:
157 qttext_context_deinit (&subparse->state);
159 #ifndef GST_DISABLE_XML
160 case GST_SUB_PARSE_FORMAT_SAMI:
161 sami_context_deinit (&subparse->state);
168 if (subparse->encoding) {
169 g_free (subparse->encoding);
170 subparse->encoding = NULL;
173 if (subparse->detected_encoding) {
174 g_free (subparse->detected_encoding);
175 subparse->detected_encoding = NULL;
178 if (subparse->adapter) {
179 g_object_unref (subparse->adapter);
180 subparse->adapter = NULL;
183 if (subparse->textbuf) {
184 g_string_free (subparse->textbuf, TRUE);
185 subparse->textbuf = NULL;
187 #ifdef SUBPARSE_MODIFICATION
188 if (subparse->state.current_language) {
189 g_free (subparse->state.current_language);
190 subparse->state.current_language = NULL;
193 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
197 gst_sub_parse_class_init (GstSubParseClass * klass)
199 GObjectClass *object_class = G_OBJECT_CLASS (klass);
200 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
202 parent_class = g_type_class_peek_parent (klass);
204 object_class->dispose = gst_sub_parse_dispose;
205 object_class->set_property = gst_sub_parse_set_property;
206 object_class->get_property = gst_sub_parse_get_property;
208 element_class->change_state = gst_sub_parse_change_state;
210 g_object_class_install_property (object_class, PROP_ENCODING,
211 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
212 "Encoding to assume if input subtitles are not in UTF-8 or any other "
213 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
214 "variable will be checked for an encoding to use. If that is not set "
215 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
216 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
218 g_object_class_install_property (object_class, PROP_VIDEOFPS,
219 gst_param_spec_fraction ("video-fps", "Video framerate",
220 "Framerate of the video stream. This is needed by some subtitle "
221 "formats to synchronize subtitles and video properly. If not set "
222 "and the subtitle format requires it subtitles may be out of sync.",
223 0, 1, G_MAXINT, 1, 24000, 1001,
224 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
225 #ifdef SUBPARSE_MODIFICATION
226 g_object_class_install_property (object_class, PROP_EXTSUB_CURRENT_LANGUAGE,
227 g_param_spec_string ("current-language", "Current language",
228 "Current language of the subtitle in external subtitle case.",
229 DEFAULT_CURRENT_LANGUAGE,
230 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235 gst_sub_parse_init (GstSubParse * subparse)
237 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
238 gst_pad_set_chain_function (subparse->sinkpad,
239 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
240 gst_pad_set_event_function (subparse->sinkpad,
241 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
242 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
244 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
245 gst_pad_set_event_function (subparse->srcpad,
246 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
247 gst_pad_set_query_function (subparse->srcpad,
248 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
249 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
251 subparse->textbuf = g_string_new (NULL);
252 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
253 subparse->flushing = FALSE;
254 subparse->discont_sent = FALSE;
255 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
256 subparse->need_segment = TRUE;
257 subparse->encoding = g_strdup (DEFAULT_ENCODING);
258 subparse->detected_encoding = NULL;
259 subparse->adapter = gst_adapter_new ();
261 subparse->fps_n = 24000;
262 subparse->fps_d = 1001;
266 * Source pad functions.
270 gst_sub_parse_src_query (GstPad * pad, GstQuery * query)
272 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
273 gboolean ret = FALSE;
275 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
277 switch (GST_QUERY_TYPE (query)) {
278 case GST_QUERY_POSITION:{
281 gst_query_parse_position (query, &fmt, NULL);
282 if (fmt != GST_FORMAT_TIME) {
283 ret = gst_pad_peer_query (self->sinkpad, query);
286 gst_query_set_position (query, GST_FORMAT_TIME,
287 self->segment.last_stop);
291 case GST_QUERY_SEEKING:
294 gboolean seekable = FALSE;
298 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
299 if (fmt == GST_FORMAT_TIME) {
300 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
302 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
304 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
305 gst_query_unref (peerquery);
308 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
312 ret = gst_pad_peer_query (self->sinkpad, query);
316 gst_object_unref (self);
322 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
324 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
325 gboolean ret = FALSE;
327 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
329 switch (GST_EVENT_TYPE (event)) {
333 GstSeekType start_type, stop_type;
338 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
339 &start_type, &start, &stop_type, &stop);
341 if (format != GST_FORMAT_TIME) {
342 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
343 gst_event_unref (event);
347 /* Apply the seek to our segment */
348 gst_segment_set_seek (&self->segment, rate, format, self->segment_flags,
349 start_type, start, stop_type, stop, &update);
351 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
354 self->next_offset = 0;
355 self->need_segment = TRUE;
357 /* Convert that seek to a seeking in bytes at position 0,
358 FIXME: could use an index */
359 ret = gst_pad_push_event (self->sinkpad,
360 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
361 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
364 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
367 gst_event_unref (event);
371 ret = gst_pad_event_default (pad, event);
376 gst_object_unref (self);
382 gst_sub_parse_set_property (GObject * object, guint prop_id,
383 const GValue * value, GParamSpec * pspec)
385 GstSubParse *subparse = GST_SUBPARSE (object);
387 GST_OBJECT_LOCK (subparse);
390 g_free (subparse->encoding);
391 subparse->encoding = g_value_dup_string (value);
392 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
393 GST_STR_NULL (subparse->encoding));
397 subparse->fps_n = gst_value_get_fraction_numerator (value);
398 subparse->fps_d = gst_value_get_fraction_denominator (value);
399 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
402 if (!subparse->state.have_internal_fps) {
403 subparse->state.fps_n = subparse->fps_n;
404 subparse->state.fps_d = subparse->fps_d;
408 #ifdef SUBPARSE_MODIFICATION
409 case PROP_EXTSUB_CURRENT_LANGUAGE:
410 subparse->state.current_language = g_value_dup_string (value);
411 subparse->state.msl_language = g_value_dup_string (value);
412 GST_LOG_OBJECT (subparse, "subtitle current language set to %s",
413 GST_STR_NULL (subparse->state.current_language));
414 GST_LOG_OBJECT (subparse, "subtitle msl language set to %s",
415 GST_STR_NULL (subparse->state.msl_language));
419 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
422 GST_OBJECT_UNLOCK (subparse);
426 gst_sub_parse_get_property (GObject * object, guint prop_id,
427 GValue * value, GParamSpec * pspec)
429 GstSubParse *subparse = GST_SUBPARSE (object);
431 GST_OBJECT_LOCK (subparse);
434 g_value_set_string (value, subparse->encoding);
437 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
439 #ifdef SUBPARSE_MODIFICATION
440 case PROP_EXTSUB_CURRENT_LANGUAGE:
441 g_value_set_string (value, subparse->state.current_language);
442 GST_LOG("************getting property to %s*********************",subparse->state.current_language);
446 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
449 GST_OBJECT_UNLOCK (subparse);
453 gst_sub_parse_get_format_description (GstSubParseFormat format)
456 case GST_SUB_PARSE_FORMAT_MDVDSUB:
458 case GST_SUB_PARSE_FORMAT_SUBRIP:
460 case GST_SUB_PARSE_FORMAT_MPSUB:
462 case GST_SUB_PARSE_FORMAT_SAMI:
464 case GST_SUB_PARSE_FORMAT_TMPLAYER:
466 case GST_SUB_PARSE_FORMAT_MPL2:
468 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
470 case GST_SUB_PARSE_FORMAT_DKS:
472 case GST_SUB_PARSE_FORMAT_QTTEXT:
475 case GST_SUB_PARSE_FORMAT_UNKNOWN:
482 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
483 gsize * consumed, GError ** err)
488 /* The char cast is necessary in glib < 2.24 */
490 g_convert_with_fallback (str, len, "UTF-8", encoding, (char *) "*",
491 consumed, NULL, err);
495 /* + 3 to skip UTF-8 BOM if it was added */
497 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
498 && (guint8) ret[2] == 0xBF)
499 g_memmove (ret, ret + 3, len + 1 - 3);
505 detect_encoding (const gchar * str, gsize len)
507 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
508 && (guint8) str[2] == 0xBF)
509 return g_strdup ("UTF-8");
511 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
512 return g_strdup ("UTF-16BE");
514 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
515 return g_strdup ("UTF-16LE");
517 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
518 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
519 return g_strdup ("UTF-32BE");
521 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
522 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
523 return g_strdup ("UTF-32LE");
529 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
532 const gchar *encoding;
538 /* First try any detected encoding */
539 if (self->detected_encoding) {
541 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
546 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
547 self->detected_encoding, err->message);
548 g_free (self->detected_encoding);
549 self->detected_encoding = NULL;
551 #ifdef SUBPARSE_MODIFICATION
552 /* You must ensure an error is NULL before it's set */
557 /* Otherwise check if it's UTF8 */
558 if (self->valid_utf8) {
559 if (g_utf8_validate (str, len, NULL)) {
560 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
562 return g_strndup (str, len);
564 GST_INFO_OBJECT (self, "invalid UTF-8!");
565 self->valid_utf8 = FALSE;
568 /* Else try fallback */
569 encoding = self->encoding;
570 if (encoding == NULL || *encoding == '\0') {
571 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
573 if (encoding == NULL || *encoding == '\0') {
574 /* if local encoding is UTF-8 and no encoding specified
575 * via the environment variable, assume ISO-8859-15 */
576 if (g_get_charset (&encoding)) {
577 encoding = "ISO-8859-15";
581 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
584 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
585 encoding, err->message);
587 #ifdef SUBPARSE_MODIFICATION
588 /* You must ensure an error is NULL before it's set */
590 if(!strcmp(self->encoding,"EUC-KR"))
592 GST_WARNING("failback case is occure with EUC-KR,so going with CP949 ");
593 g_free(self->encoding);
594 self->encoding = g_strdup("CP949");
595 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
598 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
599 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
600 #ifdef SUBPARSE_MODIFICATION
605 GST_LOG_OBJECT (self,
606 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
607 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
613 get_next_line (GstSubParse * self)
616 const char *line_end;
618 gboolean have_r = FALSE;
620 line_end = strchr (self->textbuf->str, '\n');
623 /* end-of-line not found; return for more data */
627 /* get rid of '\r' */
628 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
633 line_len = line_end - self->textbuf->str;
634 line = g_strndup (self->textbuf->str, line_len);
635 self->textbuf = g_string_erase (self->textbuf, 0,
636 line_len + (have_r ? 2 : 1));
641 parse_mdvdsub (ParserState * state, const gchar * line)
643 const gchar *line_split;
645 guint start_frame, end_frame;
646 gint64 clip_start = 0, clip_stop = 0;
647 gboolean in_seg = FALSE;
651 /* style variables */
657 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
658 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
659 " format, failed:\n%s", line);
663 /* skip the {%u}{%u} part */
664 line = strchr (line, '}') + 1;
665 line = strchr (line, '}') + 1;
667 /* see if there's a first line with a framerate */
668 if (start_frame == 1 && end_frame == 1) {
669 gchar *rest, *end = NULL;
671 rest = g_strdup (line);
672 g_strdelimit (rest, ",", '.');
673 fps = g_ascii_strtod (rest, &end);
675 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
676 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
684 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
687 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
690 /* Check our segment start/stop */
691 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
692 state->start_time, state->start_time + state->duration, &clip_start,
695 /* No need to parse that text if it's out of segment */
697 state->start_time = clip_start;
698 state->duration = clip_stop - clip_start;
703 markup = g_string_new (NULL);
708 /* parse style markup */
709 if (strncmp (line, "{y:i}", 5) == 0) {
711 line = strchr (line, '}') + 1;
713 if (strncmp (line, "{y:b}", 5) == 0) {
715 line = strchr (line, '}') + 1;
717 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
718 line = strchr (line, '}') + 1;
720 /* forward slashes at beginning/end signify italics too */
721 if (g_str_has_prefix (line, "/")) {
725 if ((line_split = strchr (line, '|')))
726 line_chunk = g_markup_escape_text (line, line_split - line);
728 line_chunk = g_markup_escape_text (line, strlen (line));
730 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
731 * always at the end of a line or can they span multiple lines?) */
732 if (g_str_has_suffix (line_chunk, "/")) {
733 line_chunk[strlen (line_chunk) - 1] = '\0';
736 markup = g_string_append (markup, "<span");
738 g_string_append (markup, " style=\"italic\"");
740 g_string_append (markup, " weight=\"bold\"");
742 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
743 g_string_append_printf (markup, ">%s</span>", line_chunk);
746 g_string_append (markup, "\n");
747 line = line_split + 1;
753 g_string_free (markup, FALSE);
754 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
755 state->start_time / (double) GST_SECOND,
756 state->duration / (double) GST_SECOND, ret);
761 strip_trailing_newlines (gchar * txt)
767 while (len > 1 && txt[len - 1] == '\n') {
774 /* we want to escape text in general, but retain basic markup like
775 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
776 * just unescape a white list of allowed markups again after
777 * escaping everything (the text between these simple markers isn't
778 * necessarily escaped, so it seems best to do it like this) */
780 subrip_unescape_formatting (gchar * txt)
784 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
785 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
786 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
787 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
789 pos[1] = g_ascii_tolower (pos[4]);
791 /* move NUL terminator as well */
792 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
797 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
798 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
799 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
800 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
803 pos[2] = g_ascii_tolower (pos[5]);
805 /* move NUL terminator as well */
806 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
814 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
818 tag = start + strlen ("<");
822 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
827 GST_LOG ("removing unhandled tag '%s'", start);
829 g_memmove (start, stop, strlen (stop) + 1);
833 /* remove tags we haven't explicitly allowed earlier on, like font tags
836 subrip_remove_unhandled_tags (gchar * txt)
840 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
841 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
842 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
848 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
849 * assumes the input has been escaped and subrip_unescape_formatting() has then
850 * been run over the input! This function adds missing closing markup tags and
851 * removes broken closing tags for tags that have never been opened. */
853 subrip_fix_up_markup (gchar ** p_txt)
855 gchar *cur, *next_tag;
857 guint num_open_tags = 0;
859 g_assert (*p_txt != NULL);
862 while (*cur != '\0') {
863 next_tag = strchr (cur, '<');
864 if (next_tag == NULL)
870 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
871 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
872 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
875 /* it's all good, closing tag which is open */
883 if (num_open_tags == G_N_ELEMENTS (open_tags))
884 return; /* something dodgy is going on, stop parsing */
885 open_tags[num_open_tags] = *next_tag;
889 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
890 g_assert_not_reached ();
896 if (num_open_tags > 0) {
899 s = g_string_new (*p_txt);
900 while (num_open_tags > 0) {
901 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
902 g_string_append_c (s, '<');
903 g_string_append_c (s, '/');
904 g_string_append_c (s, open_tags[num_open_tags - 1]);
905 g_string_append_c (s, '>');
909 *p_txt = g_string_free (s, FALSE);
914 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
916 gchar s[128] = { '\0', };
918 guint hour, min, sec, msec, len;
920 while (*ts_string == ' ')
923 g_strlcpy (s, ts_string, sizeof (s));
924 if ((end = strstr (s, "-->")))
928 /* ms may be in these formats:
929 * hh:mm:ss,500 = 500ms
932 * hh:mm:ss, 50 = 50ms
934 * and the same with . instead of ,.
935 * sscanf() doesn't differentiate between ' 5' and '5' so munge
936 * the white spaces within the timestamp to '0' (I'm sure there's a
937 * way to make sscanf() do this for us, but how?)
939 g_strdelimit (s, " ", '0');
940 g_strdelimit (s, ".", ',');
942 /* make sure we have exactly three digits after he comma */
944 g_assert (p != NULL);
951 g_strlcat (&p[len], "0", 2);
955 GST_LOG ("parsing timestamp '%s'", s);
956 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
957 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
961 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
966 parse_subrip (ParserState * state, const gchar * line)
971 switch (state->state) {
973 /* looking for a single integer */
974 if (sscanf (line, "%u", &subnum) == 1)
979 GstClockTime ts_start, ts_end;
982 /* looking for start_time --> end_time */
983 if ((end_time = strstr (line, " --> ")) &&
984 parse_subrip_time (line, &ts_start) &&
985 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
986 state->start_time <= ts_end) {
988 state->start_time = ts_start;
989 state->duration = ts_end - ts_start;
991 GST_DEBUG ("error parsing subrip time line '%s'", line);
998 /* No need to parse that text if it's out of segment */
999 gint64 clip_start = 0, clip_stop = 0;
1000 gboolean in_seg = FALSE;
1002 /* Check our segment start/stop */
1003 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1004 state->start_time, state->start_time + state->duration,
1005 &clip_start, &clip_stop);
1008 state->start_time = clip_start;
1009 state->duration = clip_stop - clip_start;
1015 /* looking for subtitle text; empty line ends this subtitle entry */
1016 if (state->buf->len)
1017 g_string_append_c (state->buf, '\n');
1018 g_string_append (state->buf, line);
1019 if (strlen (line) == 0) {
1020 ret = g_markup_escape_text (state->buf->str, state->buf->len);
1021 g_string_truncate (state->buf, 0);
1023 subrip_unescape_formatting (ret);
1024 subrip_remove_unhandled_tags (ret);
1025 strip_trailing_newlines (ret);
1026 subrip_fix_up_markup (&ret);
1031 g_return_val_if_reached (NULL);
1036 unescape_newlines_br (gchar * read)
1038 gchar *write = read;
1040 /* Replace all occurences of '[br]' with a newline as version 2
1041 * of the subviewer format uses this for newlines */
1043 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1047 if (strncmp (read, "[br]", 4) == 0) {
1061 parse_subviewer (ParserState * state, const gchar * line)
1063 guint h1, m1, s1, ms1;
1064 guint h2, m2, s2, ms2;
1067 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1068 * For examples see the unit test or
1069 * http://www.doom9.org/index.html?/sub.htm */
1071 switch (state->state) {
1073 /* looking for start_time,end_time */
1074 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1075 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1078 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1081 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1082 ms2 * GST_MSECOND - state->start_time;
1087 /* No need to parse that text if it's out of segment */
1088 gint64 clip_start = 0, clip_stop = 0;
1089 gboolean in_seg = FALSE;
1091 /* Check our segment start/stop */
1092 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1093 state->start_time, state->start_time + state->duration,
1094 &clip_start, &clip_stop);
1097 state->start_time = clip_start;
1098 state->duration = clip_stop - clip_start;
1104 /* looking for subtitle text; empty line ends this subtitle entry */
1105 if (state->buf->len)
1106 g_string_append_c (state->buf, '\n');
1107 g_string_append (state->buf, line);
1108 if (strlen (line) == 0) {
1109 ret = g_strdup (state->buf->str);
1110 unescape_newlines_br (ret);
1111 strip_trailing_newlines (ret);
1112 g_string_truncate (state->buf, 0);
1118 g_assert_not_reached ();
1124 parse_mpsub (ParserState * state, const gchar * line)
1129 switch (state->state) {
1131 /* looking for two floats (offset, duration) */
1132 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1134 state->start_time += state->duration + GST_SECOND * t1;
1135 state->duration = GST_SECOND * t2;
1139 { /* No need to parse that text if it's out of segment */
1140 gint64 clip_start = 0, clip_stop = 0;
1141 gboolean in_seg = FALSE;
1143 /* Check our segment start/stop */
1144 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1145 state->start_time, state->start_time + state->duration,
1146 &clip_start, &clip_stop);
1149 state->start_time = clip_start;
1150 state->duration = clip_stop - clip_start;
1156 /* looking for subtitle text; empty line ends this
1158 if (state->buf->len)
1159 g_string_append_c (state->buf, '\n');
1160 g_string_append (state->buf, line);
1161 if (strlen (line) == 0) {
1162 ret = g_strdup (state->buf->str);
1163 g_string_truncate (state->buf, 0);
1169 g_assert_not_reached ();
1174 static const gchar *
1175 dks_skip_timestamp (const gchar * line)
1177 while (*line && *line != ']')
1185 parse_dks (ParserState * state, const gchar * line)
1189 switch (state->state) {
1191 /* Looking for the start time and text */
1192 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1194 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1195 text = dks_skip_timestamp (line);
1198 g_string_append (state->buf, text);
1204 gint64 clip_start = 0, clip_stop = 0;
1208 /* Looking for the end time */
1209 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1211 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1214 GST_WARNING ("Failed to parse subtitle end time");
1218 /* Check if this subtitle is out of the current segment */
1219 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1220 state->start_time, state->start_time + state->duration,
1221 &clip_start, &clip_stop);
1227 state->start_time = clip_start;
1228 state->duration = clip_stop - clip_start;
1230 ret = g_strdup (state->buf->str);
1231 g_string_truncate (state->buf, 0);
1232 unescape_newlines_br (ret);
1236 g_assert_not_reached ();
1242 parser_state_init (ParserState * state)
1244 GST_DEBUG ("initialising parser");
1247 g_string_truncate (state->buf, 0);
1249 state->buf = g_string_new (NULL);
1252 state->start_time = 0;
1253 state->duration = 0;
1254 state->max_duration = 0; /* no limit */
1256 state->segment = NULL;
1257 #ifdef SUBPARSE_MODIFICATION
1258 state->language_list = NULL;
1259 state->current_language = NULL;
1260 state->langlist_msg_posted = FALSE;
1265 parser_state_dispose (GstSubParse * self, ParserState * state)
1268 g_string_free (state->buf, TRUE);
1271 if (state->user_data) {
1272 switch (self->parser_type) {
1273 #ifndef GST_DISABLE_XML
1274 case GST_SUB_PARSE_FORMAT_SAMI:
1275 sami_context_reset (state);
1284 /* regex type enum */
1287 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1288 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1289 GST_SUB_PARSE_REGEX_SUBRIP = 2,
1290 GST_SUB_PARSE_REGEX_DKS = 3,
1294 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1296 gpointer result = NULL;
1297 GError *gerr = NULL;
1299 case GST_SUB_PARSE_REGEX_MDVDSUB:
1301 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}",
1302 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1303 if (result == NULL) {
1304 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1305 g_error_free (gerr);
1308 case GST_SUB_PARSE_REGEX_SUBRIP:
1309 result = (gpointer) g_regex_new ("^ {0,3}[ 0-9]{1,4}\\s*(\x0d)?\x0a"
1310 " ?[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,3}"
1311 " +--> +[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,2}",
1312 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1313 if (result == NULL) {
1314 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1315 g_error_free (gerr);
1318 case GST_SUB_PARSE_REGEX_DKS:
1319 result = (gpointer) g_regex_new ("^\\[[0-9]+:[0-9]+:[0-9]+\\].*",
1320 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1321 if (result == NULL) {
1322 g_warning ("Compilation of dks regex failed: %s", gerr->message);
1323 g_error_free (gerr);
1327 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1333 * FIXME: maybe we should pass along a second argument, the preceding
1334 * text buffer, because that is how this originally worked, even though
1335 * I don't really see the use of that.
1338 static GstSubParseFormat
1339 gst_sub_parse_data_format_autodetect (gchar * match_str)
1343 static GOnce mdvd_rx_once = G_ONCE_INIT;
1344 static GOnce subrip_rx_once = G_ONCE_INIT;
1345 static GOnce dks_rx_once = G_ONCE_INIT;
1351 g_once (&mdvd_rx_once,
1352 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1353 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1354 g_once (&subrip_rx_once,
1355 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1356 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1357 g_once (&dks_rx_once,
1358 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1359 (gpointer) GST_SUB_PARSE_REGEX_DKS);
1361 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1362 subrip_grx = (GRegex *) subrip_rx_once.retval;
1363 dks_grx = (GRegex *) dks_rx_once.retval;
1365 if (g_regex_match (mdvd_grx, match_str, 0, NULL) == TRUE) {
1366 GST_LOG ("MicroDVD (frame based) format detected");
1367 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1369 if (g_regex_match (subrip_grx, match_str, 0, NULL) == TRUE) {
1370 GST_LOG ("SubRip (time based) format detected");
1371 return GST_SUB_PARSE_FORMAT_SUBRIP;
1373 if (g_regex_match (dks_grx, match_str, 0, NULL) == TRUE) {
1374 GST_LOG ("DKS (time based) format detected");
1375 return GST_SUB_PARSE_FORMAT_DKS;
1378 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1379 GST_LOG ("MPSub (time based) format detected");
1380 return GST_SUB_PARSE_FORMAT_MPSUB;
1382 #ifndef GST_DISABLE_XML
1383 if (strstr (match_str, "<SAMI>") != NULL ||
1384 strstr (match_str, "<sami>") != NULL) {
1385 GST_LOG ("SAMI (time based) format detected");
1386 return GST_SUB_PARSE_FORMAT_SAMI;
1389 /* we're boldly assuming the first subtitle appears within the first hour */
1390 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1391 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1392 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1393 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1394 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1395 GST_LOG ("TMPlayer (time based) format detected");
1396 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1398 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1399 GST_LOG ("MPL2 (time based) format detected");
1400 return GST_SUB_PARSE_FORMAT_MPL2;
1402 if (strstr (match_str, "[INFORMATION]") != NULL) {
1403 GST_LOG ("SubViewer (time based) format detected");
1404 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1406 if (strstr (match_str, "{QTtext}") != NULL) {
1407 GST_LOG ("QTtext (time based) format detected");
1408 return GST_SUB_PARSE_FORMAT_QTTEXT;
1411 GST_DEBUG ("no subtitle format detected");
1412 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1416 gst_sub_parse_format_autodetect (GstSubParse * self)
1419 GstSubParseFormat format;
1421 if (strlen (self->textbuf->str) < 30) {
1422 GST_DEBUG ("File too small to be a subtitles file");
1426 data = g_strndup (self->textbuf->str, 35);
1427 format = gst_sub_parse_data_format_autodetect (data);
1430 self->parser_type = format;
1431 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1432 parser_state_init (&self->state);
1435 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1436 self->parse_line = parse_mdvdsub;
1437 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1438 case GST_SUB_PARSE_FORMAT_SUBRIP:
1439 self->parse_line = parse_subrip;
1440 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1441 case GST_SUB_PARSE_FORMAT_MPSUB:
1442 self->parse_line = parse_mpsub;
1443 return gst_caps_new_simple ("text/plain", NULL);
1444 #ifndef GST_DISABLE_XML
1445 case GST_SUB_PARSE_FORMAT_SAMI:
1446 self->parse_line = parse_sami;
1447 sami_context_init (&self->state);
1448 GST_LOG("************setting property to %s*********************", self->state.current_language);
1449 sami_context_change_language (&self->state);
1450 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1452 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1453 self->parse_line = parse_tmplayer;
1454 self->state.max_duration = 5 * GST_SECOND;
1455 return gst_caps_new_simple ("text/plain", NULL);
1456 case GST_SUB_PARSE_FORMAT_MPL2:
1457 self->parse_line = parse_mpl2;
1458 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1459 case GST_SUB_PARSE_FORMAT_DKS:
1460 self->parse_line = parse_dks;
1461 return gst_caps_new_simple ("text/plain", NULL);
1462 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1463 self->parse_line = parse_subviewer;
1464 return gst_caps_new_simple ("text/plain", NULL);
1465 case GST_SUB_PARSE_FORMAT_QTTEXT:
1466 self->parse_line = parse_qttext;
1467 qttext_context_init (&self->state);
1468 return gst_caps_new_simple ("text/x-pango-markup", NULL);
1469 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1471 GST_DEBUG ("no subtitle format detected");
1472 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1473 ("The input is not a valid/supported subtitle file"), (NULL));
1479 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1483 gchar *input = NULL;
1485 discont = GST_BUFFER_IS_DISCONT (buf);
1487 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1488 GST_BUFFER_OFFSET (buf) != self->offset) {
1489 self->offset = GST_BUFFER_OFFSET (buf);
1494 GST_INFO ("discontinuity");
1495 /* flush the parser state */
1496 parser_state_init (&self->state);
1497 g_string_truncate (self->textbuf, 0);
1498 gst_adapter_clear (self->adapter);
1499 #ifndef GST_DISABLE_XML
1500 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1501 sami_context_reset (&self->state);
1503 /* we could set a flag to make sure that the next buffer we push out also
1504 * has the DISCONT flag set, but there's no point really given that it's
1505 * subtitles which are discontinuous by nature. */
1508 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
1509 self->next_offset = self->offset;
1510 GST_INFO("Pushing in the adapter");
1511 gst_adapter_push (self->adapter, buf);
1514 convert_encoding (self, (const gchar *) gst_adapter_peek (self->adapter,
1515 gst_adapter_available (self->adapter)),
1516 (gsize) gst_adapter_available (self->adapter), &consumed);
1517 if (input && consumed > 0) {
1518 self->textbuf = g_string_append (self->textbuf, input);
1519 gst_adapter_flush (self->adapter, consumed);
1525 #ifdef SUBPARSE_MODIFICATION
1527 get_next_sami_sync_line (gchar * line, guint* offset)
1529 const char *line_end = NULL;
1530 gchar* sync_line = NULL;
1533 line_end = strstr (line, "<SYNC");
1536 /* <SYNC not found, or there is only one sync in this line return offset as 0 */
1537 sync_line = (gchar*)g_malloc ((strlen(line)) + 1);
1538 strcpy (sync_line, line);
1539 *(sync_line + strlen(line)) = '\0';
1544 if (line_end == line)
1546 const gchar* tempptr = line_end;
1547 line_end += strlen("<SYNC");
1548 line_end = strstr (line_end, "<SYNC");
1550 /* <SYNC not found, or there is only one sync in this line return offset as 0 */
1552 sync_line = (gchar*)g_malloc ((strlen(line_end)) + 1);
1553 strcpy (sync_line, line_end);
1554 *(sync_line + strlen(line_end)) = '\0';
1560 /* get rid of '\r' */
1561 if (line_end != line && *(line_end - 1) == '\r') {
1566 *offset = line_end - line;
1568 sync_line = g_strndup (line, *offset);
1574 static GstFlowReturn
1575 handle_buffer (GstSubParse * self, GstBuffer * buf)
1577 GstFlowReturn ret = GST_FLOW_OK;
1578 GstCaps *caps = NULL;
1579 gchar *line, *subtitle;
1580 #ifdef SUBPARSE_MODIFICATION
1581 GstMessage *m = NULL;
1584 gboolean discont = FALSE;
1585 gboolean discont_after = FALSE;
1586 if (self->first_buffer) {
1587 self->detected_encoding =
1588 detect_encoding ((gchar *) GST_BUFFER_DATA (buf),
1589 GST_BUFFER_SIZE (buf));
1590 self->first_buffer = FALSE;
1591 self->state.fps_n = self->fps_n;
1592 self->state.fps_d = self->fps_d;
1594 if (!strcmp ((const char*)GST_BUFFER_DATA (buf), "eos")){
1595 GST_DEBUG_OBJECT(self,"eos buffer is recieved");
1596 if (GST_BUFFER_FLAG_IS_SET(buf,GST_BUFFER_FLAG_GAP)) {
1597 GST_DEBUG_OBJECT(self,"eos buffer with flag is recieved recieved");
1598 ret = gst_pad_push (self->srcpad, buf);
1602 discont = GST_BUFFER_IS_DISCONT (buf);
1604 self->discont_sent = FALSE;
1605 feed_textbuf (self, buf);
1607 /* make sure we know the format */
1608 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1609 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1610 return GST_FLOW_UNEXPECTED;
1612 if (!gst_pad_set_caps (self->srcpad, caps)) {
1613 gst_caps_unref (caps);
1614 return GST_FLOW_UNEXPECTED;
1616 gst_caps_unref (caps);
1619 if (self->subtitle_codec != NULL) {
1622 tags = gst_tag_list_new ();
1623 gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_SUBTITLE_CODEC,
1624 self->subtitle_codec, NULL);
1625 gst_element_found_tags_for_pad (GST_ELEMENT (self), self->srcpad, tags);
1629 while (!self->flushing && (line = get_next_line (self))) {
1631 #ifdef SUBPARSE_MODIFICATION
1632 guint suboffset = 0;
1633 gchar* sync_line = NULL;
1635 /* Set segment on our parser state machine */
1636 self->state.segment = &self->segment;
1637 #ifdef SUBPARSE_MODIFICATION
1638 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI) {
1640 /* Now parse the line, out of segment lines will just return NULL */
1641 sync_line = get_next_sami_sync_line(line + offset, &suboffset);
1642 offset += suboffset;
1643 GST_LOG_OBJECT (self, "Parsing line '%s'", sync_line);
1644 subtitle = self->parse_line (&self->state, sync_line);
1648 if (!self->state.langlist_msg_posted && self->state.language_list) {
1649 if(self->state.language_list) {
1650 m = gst_message_new_element (GST_OBJECT_CAST (self), gst_structure_new("Ext_Sub_Language_List",
1651 "lang_list", G_TYPE_POINTER, self->state.language_list, NULL));
1653 gst_element_post_message (GST_ELEMENT_CAST (self), m);
1654 self->state.langlist_msg_posted = TRUE;
1656 GST_DEBUG_OBJECT (self, "LANGLIST POSTED with current language as : %s ",self->state.current_language);
1658 GST_DEBUG_OBJECT (self, "parse_line returned %x", subtitle);
1661 guint subtitle_len = strlen (subtitle);
1663 /* +1 for terminating NUL character */
1664 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1665 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1666 GST_PAD_CAPS (self->srcpad), &buf);
1668 if (ret == GST_FLOW_OK) {
1669 /* copy terminating NUL character as well */
1670 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1671 GST_BUFFER_SIZE (buf) = subtitle_len;
1672 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1673 GST_BUFFER_DURATION (buf) = self->state.duration;
1674 if (discont && !counter) {
1675 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1676 GST_DEBUG("setting the true for discont flag and self is %p with ts is %" GST_TIME_FORMAT "\n",self,GST_TIME_ARGS(GST_BUFFER_TIMESTAMP (buf)));
1677 self->discont_sent = TRUE;
1679 } else if (!self->discont_sent && !counter) {
1680 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1681 GST_DEBUG("setting the true for discont flag and self is %p with ts is %" GST_TIME_FORMAT "\n",self,GST_TIME_ARGS(GST_BUFFER_TIMESTAMP (buf)));
1682 self->discont_sent = TRUE;
1686 /* in some cases (e.g. tmplayer) we can only determine the duration
1687 * of a text chunk from the timestamp of the next text chunk; in those
1688 * cases, we probably want to limit the duration to something
1689 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1690 * just because nothing else is being said during that time */
1691 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1692 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1693 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1696 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME, self->state.start_time);
1698 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1699 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1700 GST_TIME_ARGS (self->state.duration));
1702 ret = gst_pad_push (self->srcpad, buf);
1705 /* move this forward (the tmplayer parser needs this) */
1706 if (self->state.duration != GST_CLOCK_TIME_NONE)
1707 self->state.start_time += self->state.duration;
1712 } while (suboffset);
1718 /* Now parse the line, out of segment lines will just return NULL */
1719 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1720 subtitle = self->parse_line (&self->state, line + offset);
1723 GST_DEBUG_OBJECT (self, "parse_line returned %x", subtitle);
1726 guint subtitle_len = strlen (subtitle);
1728 /* +1 for terminating NUL character */
1729 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1730 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1731 GST_PAD_CAPS (self->srcpad), &buf);
1733 if (ret == GST_FLOW_OK) {
1734 /* copy terminating NUL character as well */
1735 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1736 GST_BUFFER_SIZE (buf) = subtitle_len;
1737 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1738 GST_BUFFER_DURATION (buf) = self->state.duration;
1740 /* in some cases (e.g. tmplayer) we can only determine the duration
1741 * of a text chunk from the timestamp of the next text chunk; in those
1742 * cases, we probably want to limit the duration to something
1743 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1744 * just because nothing else is being said during that time */
1745 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1746 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1747 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1750 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1751 self->state.start_time);
1753 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1754 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1755 GST_TIME_ARGS (self->state.duration));
1756 if (discont && !counter) {
1757 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1758 GST_DEBUG("setting the true for discont flag and self is %p with ts is %" GST_TIME_FORMAT "\n",self,GST_TIME_ARGS(GST_BUFFER_TIMESTAMP (buf)));
1759 self->discont_sent = TRUE;
1761 } else if (!self->discont_sent && !counter) {
1762 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1763 GST_DEBUG("setting the true for discont flag and self is %p with ts is %" GST_TIME_FORMAT "\n",self,GST_TIME_ARGS(GST_BUFFER_TIMESTAMP (buf)));
1764 self->discont_sent = TRUE;
1767 GST_DEBUG_OBJECT (self, "Sent buffer with TS %" GST_TIME_FORMAT, GST_TIME_ARGS(GST_BUFFER_TIMESTAMP (buf)));
1769 ret = gst_pad_push (self->srcpad, buf);
1772 /* move this forward (the tmplayer parser needs this) */
1773 if (self->state.duration != GST_CLOCK_TIME_NONE)
1774 self->state.start_time += self->state.duration;
1781 if (ret != GST_FLOW_OK) {
1782 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1786 /* Now parse the line, out of segment lines will just return NULL */
1787 GST_LOG_OBJECT (self, "Parsing line '%s'", line + offset);
1788 subtitle = self->parse_line (&self->state, line + offset);
1792 guint subtitle_len = strlen (subtitle);
1794 /* +1 for terminating NUL character */
1795 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
1796 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
1797 GST_PAD_CAPS (self->srcpad), &buf);
1799 if (ret == GST_FLOW_OK) {
1800 /* copy terminating NUL character as well */
1801 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
1802 GST_BUFFER_SIZE (buf) = subtitle_len;
1803 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1804 GST_BUFFER_DURATION (buf) = self->state.duration;
1806 /* in some cases (e.g. tmplayer) we can only determine the duration
1807 * of a text chunk from the timestamp of the next text chunk; in those
1808 * cases, we probably want to limit the duration to something
1809 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1810 * just because nothing else is being said during that time */
1811 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1812 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1813 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1816 gst_segment_set_last_stop (&self->segment, GST_FORMAT_TIME,
1817 self->state.start_time);
1819 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1820 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1821 GST_TIME_ARGS (self->state.duration));
1823 ret = gst_pad_push (self->srcpad, buf);
1826 /* move this forward (the tmplayer parser needs this) */
1827 if (self->state.duration != GST_CLOCK_TIME_NONE)
1828 self->state.start_time += self->state.duration;
1833 if (ret != GST_FLOW_OK) {
1834 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1844 static GstFlowReturn
1845 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
1850 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
1852 /* Push newsegment if needed */
1853 if (self->need_segment) {
1854 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1857 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
1858 self->segment.rate, self->segment.format,
1859 self->segment.start, self->segment.stop, self->segment.time));
1860 self->need_segment = FALSE;
1863 ret = handle_buffer (self, buf);
1869 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
1871 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
1872 gboolean ret = FALSE;
1874 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1876 switch (GST_EVENT_TYPE (event)) {
1877 case GST_EVENT_EOS:{
1878 /* Make sure the last subrip chunk is pushed out even
1879 * if the file does not have an empty line at the end */
1880 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1881 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1882 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1883 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT) {
1884 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1886 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1887 GST_BUFFER_DATA (buf)[0] = '\n';
1888 GST_BUFFER_DATA (buf)[1] = '\n';
1889 GST_BUFFER_DATA (buf)[2] = '\0'; /* play it safe */
1890 GST_BUFFER_SIZE (buf) = 2;
1891 GST_BUFFER_OFFSET (buf) = self->offset;
1892 gst_sub_parse_chain (pad, buf);
1894 ret = gst_pad_event_default (pad, event);
1897 case GST_EVENT_NEWSEGMENT:
1901 gint64 start, stop, time;
1904 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1907 GST_DEBUG_OBJECT (self, "newsegment (%s)", gst_format_get_name (format));
1908 self->need_segment = TRUE;
1909 if (format == GST_FORMAT_TIME) {
1910 gst_segment_set_newsegment (&self->segment, update, rate, format,
1913 /* if not time format, we'll either start with a 0 timestamp anyway or
1914 * it's following a seek in which case we'll have saved the requested
1915 * seek segment and don't want to overwrite it (remember that on a seek
1916 * we always just seek back to the start in BYTES format and just throw
1917 * away all text that's before the requested position; if the subtitles
1918 * come from an upstream demuxer, it won't be able to handle our BYTES
1919 * seek request and instead send us a newsegment from the seek request
1920 * it received via its video pads instead, so all is fine then too) */
1924 gst_event_unref (event);
1927 case GST_EVENT_FLUSH_START:
1929 self->flushing = TRUE;
1931 ret = gst_pad_event_default (pad, event);
1934 case GST_EVENT_FLUSH_STOP:
1936 self->flushing = FALSE;
1938 ret = gst_pad_event_default (pad, event);
1942 ret = gst_pad_event_default (pad, event);
1946 gst_object_unref (self);
1952 static GstStateChangeReturn
1953 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1955 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1956 GstSubParse *self = GST_SUBPARSE (element);
1958 switch (transition) {
1959 case GST_STATE_CHANGE_READY_TO_PAUSED:
1960 /* format detection will init the parser state */
1962 self->next_offset = 0;
1963 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1964 self->valid_utf8 = TRUE;
1965 self->first_buffer = TRUE;
1966 g_free (self->detected_encoding);
1967 self->detected_encoding = NULL;
1968 g_string_truncate (self->textbuf, 0);
1969 gst_adapter_clear (self->adapter);
1975 ret = parent_class->change_state (element, transition);
1976 if (ret == GST_STATE_CHANGE_FAILURE)
1979 switch (transition) {
1980 case GST_STATE_CHANGE_PAUSED_TO_READY:
1981 parser_state_dispose (self, &self->state);
1982 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1995 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1996 * also, give different subtitle formats really different types */
1997 static GstStaticCaps mpl2_caps =
1998 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1999 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
2001 static GstStaticCaps tmp_caps =
2002 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
2003 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
2005 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
2006 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
2008 #ifndef GST_DISABLE_XML
2009 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
2010 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
2013 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
2014 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
2016 static GstStaticCaps qttext_caps =
2017 GST_STATIC_CAPS ("application/x-subtitle-qttext");
2018 #define QTTEXT_CAPS (gst_static_caps_get (&qttext_caps))
2021 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
2023 GstSubParseFormat format;
2027 gchar *encoding = NULL;
2030 if (!(data = gst_type_find_peek (tf, 0, 129)))
2033 /* make sure string passed to _autodetect() is NUL-terminated */
2034 str = g_malloc0 (129);
2035 memcpy (str, data, 128);
2037 if ((encoding = detect_encoding (str, 128)) != NULL) {
2038 gchar *converted_str;
2042 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
2043 if (converted_str == NULL) {
2044 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
2050 str = converted_str;
2055 /* Check if at least the first 120 chars are valid UTF8,
2056 * otherwise convert as always */
2057 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
2058 gchar *converted_str;
2063 enc = g_getenv ("GST_SUBTITLE_ENCODING");
2064 if (enc == NULL || *enc == '\0') {
2065 /* if local encoding is UTF-8 and no encoding specified
2066 * via the environment variable, assume ISO-8859-15 */
2067 if (g_get_charset (&enc)) {
2068 enc = "ISO-8859-15";
2071 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, &err);
2072 if (converted_str != NULL) {
2074 str = converted_str;
2078 format = gst_sub_parse_data_format_autodetect (str);
2082 case GST_SUB_PARSE_FORMAT_MDVDSUB:
2083 GST_DEBUG ("MicroDVD format detected");
2086 case GST_SUB_PARSE_FORMAT_SUBRIP:
2087 GST_DEBUG ("SubRip format detected");
2090 case GST_SUB_PARSE_FORMAT_MPSUB:
2091 GST_DEBUG ("MPSub format detected");
2094 #ifndef GST_DISABLE_XML
2095 case GST_SUB_PARSE_FORMAT_SAMI:
2096 GST_DEBUG ("SAMI (time-based) format detected");
2100 case GST_SUB_PARSE_FORMAT_TMPLAYER:
2101 GST_DEBUG ("TMPlayer (time based) format detected");
2104 /* FIXME: our MPL2 typefinding is not really good enough to warrant
2105 * returning a high probability (however, since we registered our
2106 * typefinder here with a rank of MARGINAL we should pretty much only
2107 * be called if most other typefinders have already run */
2108 case GST_SUB_PARSE_FORMAT_MPL2:
2109 GST_DEBUG ("MPL2 (time based) format detected");
2112 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
2113 GST_DEBUG ("SubViewer format detected");
2116 case GST_SUB_PARSE_FORMAT_DKS:
2117 GST_DEBUG ("DKS format detected");
2120 case GST_SUB_PARSE_FORMAT_QTTEXT:
2121 GST_DEBUG ("QTtext format detected");
2125 case GST_SUB_PARSE_FORMAT_UNKNOWN:
2126 GST_DEBUG ("no subtitle format detected");
2130 /* if we're here, it's ok */
2131 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
2135 plugin_init (GstPlugin * plugin)
2137 static const gchar *sub_exts[] =
2138 { "srt", "sub", "mpsub", "mdvd", "smi", "txt", "dks", NULL };
2140 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
2142 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
2143 gst_subparse_type_find, (gchar **) sub_exts, SUB_CAPS, NULL, NULL))
2146 if (!gst_element_register (plugin, "subparse",
2147 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
2148 !gst_element_register (plugin, "ssaparse",
2149 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
2156 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2160 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)