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>
5 * Copyright (C) 2016 Philippe Normand <pnormand@igalia.com>
6 * Copyright (C) 2016 Jan Schmidt <jan@centricular.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
31 #include <sys/types.h>
34 #include "gstsubparse.h"
35 #include "gstssaparse.h"
36 #include "samiparse.h"
37 #include "tmplayerparse.h"
38 #include "mpl2parse.h"
39 #include "qttextparse.h"
41 GST_DEBUG_CATEGORY (sub_parse_debug);
43 #define DEFAULT_ENCODING NULL
44 #define ATTRIBUTE_REGEX "\\s?[a-zA-Z0-9\\. \t\\(\\)]*"
45 static const gchar *allowed_srt_tags[] = { "i", "b", "u", NULL };
46 static const gchar *allowed_vtt_tags[] =
47 { "i", "b", "c", "u", "v", "ruby", "rt", NULL };
57 gst_sub_parse_set_property (GObject * object, guint prop_id,
58 const GValue * value, GParamSpec * pspec);
60 gst_sub_parse_get_property (GObject * object, guint prop_id,
61 GValue * value, GParamSpec * pspec);
64 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
67 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
68 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
69 "application/x-subtitle-dks; application/x-subtitle-qttext;"
70 "application/x-subtitle-lrc; application/x-subtitle-vtt")
73 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
76 GST_STATIC_CAPS ("text/x-raw, format= { pango-markup, utf8 }")
80 static gboolean gst_sub_parse_src_event (GstPad * pad, GstObject * parent,
82 static gboolean gst_sub_parse_src_query (GstPad * pad, GstObject * parent,
84 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstObject * parent,
87 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
88 GstStateChange transition);
90 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent,
93 #define gst_sub_parse_parent_class parent_class
94 G_DEFINE_TYPE (GstSubParse, gst_sub_parse, GST_TYPE_ELEMENT);
97 gst_sub_parse_dispose (GObject * object)
99 GstSubParse *subparse = GST_SUBPARSE (object);
101 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
103 if (subparse->encoding) {
104 g_free (subparse->encoding);
105 subparse->encoding = NULL;
108 if (subparse->detected_encoding) {
109 g_free (subparse->detected_encoding);
110 subparse->detected_encoding = NULL;
113 if (subparse->adapter) {
114 g_object_unref (subparse->adapter);
115 subparse->adapter = NULL;
118 if (subparse->textbuf) {
119 g_string_free (subparse->textbuf, TRUE);
120 subparse->textbuf = NULL;
123 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
127 gst_sub_parse_class_init (GstSubParseClass * klass)
129 GObjectClass *object_class = G_OBJECT_CLASS (klass);
130 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
132 object_class->dispose = gst_sub_parse_dispose;
133 object_class->set_property = gst_sub_parse_set_property;
134 object_class->get_property = gst_sub_parse_get_property;
136 gst_element_class_add_static_pad_template (element_class, &sink_templ);
137 gst_element_class_add_static_pad_template (element_class, &src_templ);
138 gst_element_class_set_static_metadata (element_class,
139 "Subtitle parser", "Codec/Parser/Subtitle",
140 "Parses subtitle (.sub) files into text streams",
141 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
142 "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
144 element_class->change_state = gst_sub_parse_change_state;
146 g_object_class_install_property (object_class, PROP_ENCODING,
147 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
148 "Encoding to assume if input subtitles are not in UTF-8 or any other "
149 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
150 "variable will be checked for an encoding to use. If that is not set "
151 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
152 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
154 g_object_class_install_property (object_class, PROP_VIDEOFPS,
155 gst_param_spec_fraction ("video-fps", "Video framerate",
156 "Framerate of the video stream. This is needed by some subtitle "
157 "formats to synchronize subtitles and video properly. If not set "
158 "and the subtitle format requires it subtitles may be out of sync.",
159 0, 1, G_MAXINT, 1, 24000, 1001,
160 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164 gst_sub_parse_init (GstSubParse * subparse)
166 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
167 gst_pad_set_chain_function (subparse->sinkpad,
168 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
169 gst_pad_set_event_function (subparse->sinkpad,
170 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
171 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
173 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
174 gst_pad_set_event_function (subparse->srcpad,
175 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
176 gst_pad_set_query_function (subparse->srcpad,
177 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
178 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
180 subparse->textbuf = g_string_new (NULL);
181 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
182 subparse->flushing = FALSE;
183 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
184 subparse->need_segment = TRUE;
185 subparse->encoding = g_strdup (DEFAULT_ENCODING);
186 subparse->detected_encoding = NULL;
187 subparse->adapter = gst_adapter_new ();
189 subparse->fps_n = 24000;
190 subparse->fps_d = 1001;
194 * Source pad functions.
198 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
200 GstSubParse *self = GST_SUBPARSE (parent);
201 gboolean ret = FALSE;
203 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
205 switch (GST_QUERY_TYPE (query)) {
206 case GST_QUERY_POSITION:{
209 gst_query_parse_position (query, &fmt, NULL);
210 if (fmt != GST_FORMAT_TIME) {
211 ret = gst_pad_peer_query (self->sinkpad, query);
214 gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
218 case GST_QUERY_SEEKING:
221 gboolean seekable = FALSE;
225 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
226 if (fmt == GST_FORMAT_TIME) {
227 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
229 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
231 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
232 gst_query_unref (peerquery);
235 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
239 ret = gst_pad_query_default (pad, parent, query);
247 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
249 GstSubParse *self = GST_SUBPARSE (parent);
250 gboolean ret = FALSE;
252 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
254 switch (GST_EVENT_TYPE (event)) {
259 GstSeekType start_type, stop_type;
264 gst_event_parse_seek (event, &rate, &format, &flags,
265 &start_type, &start, &stop_type, &stop);
267 if (format != GST_FORMAT_TIME) {
268 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
269 gst_event_unref (event);
273 /* Convert that seek to a seeking in bytes at position 0,
274 FIXME: could use an index */
275 ret = gst_pad_push_event (self->sinkpad,
276 gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
277 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
280 /* Apply the seek to our segment */
281 gst_segment_do_seek (&self->segment, rate, format, flags,
282 start_type, start, stop_type, stop, &update);
284 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
287 /* will mark need_segment when receiving segment from upstream,
288 * after FLUSH and all that has happened,
289 * rather than racing with chain */
291 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
294 gst_event_unref (event);
298 ret = gst_pad_event_default (pad, parent, event);
307 gst_sub_parse_set_property (GObject * object, guint prop_id,
308 const GValue * value, GParamSpec * pspec)
310 GstSubParse *subparse = GST_SUBPARSE (object);
312 GST_OBJECT_LOCK (subparse);
315 g_free (subparse->encoding);
316 subparse->encoding = g_value_dup_string (value);
317 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
318 GST_STR_NULL (subparse->encoding));
322 subparse->fps_n = gst_value_get_fraction_numerator (value);
323 subparse->fps_d = gst_value_get_fraction_denominator (value);
324 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
327 if (!subparse->state.have_internal_fps) {
328 subparse->state.fps_n = subparse->fps_n;
329 subparse->state.fps_d = subparse->fps_d;
334 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
337 GST_OBJECT_UNLOCK (subparse);
341 gst_sub_parse_get_property (GObject * object, guint prop_id,
342 GValue * value, GParamSpec * pspec)
344 GstSubParse *subparse = GST_SUBPARSE (object);
346 GST_OBJECT_LOCK (subparse);
349 g_value_set_string (value, subparse->encoding);
352 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
355 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
358 GST_OBJECT_UNLOCK (subparse);
362 gst_sub_parse_get_format_description (GstSubParseFormat format)
365 case GST_SUB_PARSE_FORMAT_MDVDSUB:
367 case GST_SUB_PARSE_FORMAT_SUBRIP:
369 case GST_SUB_PARSE_FORMAT_MPSUB:
371 case GST_SUB_PARSE_FORMAT_SAMI:
373 case GST_SUB_PARSE_FORMAT_TMPLAYER:
375 case GST_SUB_PARSE_FORMAT_MPL2:
377 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
379 case GST_SUB_PARSE_FORMAT_DKS:
381 case GST_SUB_PARSE_FORMAT_VTT:
383 case GST_SUB_PARSE_FORMAT_QTTEXT:
385 case GST_SUB_PARSE_FORMAT_LRC:
388 case GST_SUB_PARSE_FORMAT_UNKNOWN:
395 gst_convert_to_utf8 (const gchar * str, gsize len, const gchar * encoding,
396 gsize * consumed, GError ** err)
401 /* The char cast is necessary in glib < 2.24 */
403 g_convert_with_fallback (str, len, "UTF-8", encoding, (char *) "*",
404 consumed, NULL, err);
408 /* + 3 to skip UTF-8 BOM if it was added */
410 if (len >= 3 && (guint8) ret[0] == 0xEF && (guint8) ret[1] == 0xBB
411 && (guint8) ret[2] == 0xBF)
412 memmove (ret, ret + 3, len + 1 - 3);
418 detect_encoding (const gchar * str, gsize len)
420 if (len >= 3 && (guint8) str[0] == 0xEF && (guint8) str[1] == 0xBB
421 && (guint8) str[2] == 0xBF)
422 return g_strdup ("UTF-8");
424 if (len >= 2 && (guint8) str[0] == 0xFE && (guint8) str[1] == 0xFF)
425 return g_strdup ("UTF-16BE");
427 if (len >= 2 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE)
428 return g_strdup ("UTF-16LE");
430 if (len >= 4 && (guint8) str[0] == 0x00 && (guint8) str[1] == 0x00
431 && (guint8) str[2] == 0xFE && (guint8) str[3] == 0xFF)
432 return g_strdup ("UTF-32BE");
434 if (len >= 4 && (guint8) str[0] == 0xFF && (guint8) str[1] == 0xFE
435 && (guint8) str[2] == 0x00 && (guint8) str[3] == 0x00)
436 return g_strdup ("UTF-32LE");
442 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
445 const gchar *encoding;
451 /* First try any detected encoding */
452 if (self->detected_encoding) {
454 gst_convert_to_utf8 (str, len, self->detected_encoding, consumed, &err);
459 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
460 self->detected_encoding, err->message);
461 g_free (self->detected_encoding);
462 self->detected_encoding = NULL;
463 g_clear_error (&err);
466 /* Otherwise check if it's UTF8 */
467 if (self->valid_utf8) {
468 if (g_utf8_validate (str, len, NULL)) {
469 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
471 return g_strndup (str, len);
473 GST_INFO_OBJECT (self, "invalid UTF-8!");
474 self->valid_utf8 = FALSE;
477 /* Else try fallback */
478 encoding = self->encoding;
479 if (encoding == NULL || *encoding == '\0') {
480 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
482 if (encoding == NULL || *encoding == '\0') {
483 /* if local encoding is UTF-8 and no encoding specified
484 * via the environment variable, assume ISO-8859-15 */
485 if (g_get_charset (&encoding)) {
486 encoding = "ISO-8859-15";
490 ret = gst_convert_to_utf8 (str, len, encoding, consumed, &err);
493 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
494 encoding, err->message);
495 g_clear_error (&err);
497 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
498 ret = gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed, NULL);
501 GST_LOG_OBJECT (self,
502 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
503 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
509 get_next_line (GstSubParse * self)
512 const char *line_end;
514 gboolean have_r = FALSE;
516 line_end = strchr (self->textbuf->str, '\n');
519 /* end-of-line not found; return for more data */
523 /* get rid of '\r' */
524 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
529 line_len = line_end - self->textbuf->str;
530 line = g_strndup (self->textbuf->str, line_len);
531 self->textbuf = g_string_erase (self->textbuf, 0,
532 line_len + (have_r ? 2 : 1));
537 parse_mdvdsub (ParserState * state, const gchar * line)
539 const gchar *line_split;
541 guint start_frame, end_frame;
542 guint64 clip_start = 0, clip_stop = 0;
543 gboolean in_seg = FALSE;
547 /* style variables */
553 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
554 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
555 " format, failed:\n%s", line);
559 /* skip the {%u}{%u} part */
560 line = strchr (line, '}') + 1;
561 line = strchr (line, '}') + 1;
563 /* see if there's a first line with a framerate */
564 if (start_frame == 1 && end_frame == 1) {
565 gchar *rest, *end = NULL;
567 rest = g_strdup (line);
568 g_strdelimit (rest, ",", '.');
569 fps = g_ascii_strtod (rest, &end);
571 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
572 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
580 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
583 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
586 /* Check our segment start/stop */
587 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
588 state->start_time, state->start_time + state->duration, &clip_start,
591 /* No need to parse that text if it's out of segment */
593 state->start_time = clip_start;
594 state->duration = clip_stop - clip_start;
599 markup = g_string_new (NULL);
604 /* parse style markup */
605 if (strncmp (line, "{y:i}", 5) == 0) {
607 line = strchr (line, '}') + 1;
609 if (strncmp (line, "{y:b}", 5) == 0) {
611 line = strchr (line, '}') + 1;
613 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
614 line = strchr (line, '}') + 1;
616 /* forward slashes at beginning/end signify italics too */
617 if (g_str_has_prefix (line, "/")) {
621 if ((line_split = strchr (line, '|')))
622 line_chunk = g_markup_escape_text (line, line_split - line);
624 line_chunk = g_markup_escape_text (line, strlen (line));
626 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
627 * always at the end of a line or can they span multiple lines?) */
628 if (g_str_has_suffix (line_chunk, "/")) {
629 line_chunk[strlen (line_chunk) - 1] = '\0';
632 markup = g_string_append (markup, "<span");
634 g_string_append (markup, " style=\"italic\"");
636 g_string_append (markup, " weight=\"bold\"");
638 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
639 g_string_append_printf (markup, ">%s</span>", line_chunk);
642 g_string_append (markup, "\n");
643 line = line_split + 1;
649 g_string_free (markup, FALSE);
650 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
651 state->start_time / (double) GST_SECOND,
652 state->duration / (double) GST_SECOND, ret);
657 strip_trailing_newlines (gchar * txt)
663 while (len > 1 && txt[len - 1] == '\n') {
670 /* we want to escape text in general, but retain basic markup like
671 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
672 * just unescape a white list of allowed markups again after
673 * escaping everything (the text between these simple markers isn't
674 * necessarily escaped, so it seems best to do it like this) */
676 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
677 gboolean allows_tag_attributes)
681 gchar *allowed_tags_pattern, *search_pattern;
682 const gchar *replace_pattern;
684 /* No processing needed if no escaped tag marker found in the string. */
685 if (strstr (txt, "<") == NULL)
688 /* Build a list of alternates for our regexp.
689 * FIXME: Could be built once and stored */
690 allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
691 /* Look for starting/ending escaped tags with optional attributes. */
692 search_pattern = g_strdup_printf ("<(/)?\\ *(%s)(%s)>",
693 allowed_tags_pattern, ATTRIBUTE_REGEX);
694 /* And unescape appropriately */
695 if (allows_tag_attributes) {
696 replace_pattern = "<\\1\\2\\3>";
698 replace_pattern = "<\\1\\2>";
701 tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
702 res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
703 replace_pattern, 0, NULL);
705 /* res will always be shorter than the input or identical, so this
710 g_free (search_pattern);
711 g_free (allowed_tags_pattern);
713 g_regex_unref (tag_regex);
718 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
722 tag = start + strlen ("<");
726 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
731 GST_LOG ("removing unhandled tag '%s'", start);
733 memmove (start, stop, strlen (stop) + 1);
737 /* remove tags we haven't explicitly allowed earlier on, like font tags
740 subrip_remove_unhandled_tags (gchar * txt)
744 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
745 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
746 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
752 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
753 * take a simple approach. This code assumes the input has been
754 * escaped and subrip_unescape_formatting() has then been run over the
755 * input! This function adds missing closing markup tags and removes
756 * broken closing tags for tags that have never been opened. */
758 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
760 gchar *cur, *next_tag;
761 gchar *open_tags[32];
762 guint num_open_tags = 0;
763 const gchar *iter_tag;
769 GMatchInfo *match_info;
770 gchar **allowed_tags = (gchar **) allowed_tags_ptr;
772 g_assert (*p_txt != NULL);
775 while (*cur != '\0') {
776 next_tag = strchr (cur, '<');
777 if (next_tag == NULL)
781 while (index < g_strv_length (allowed_tags)) {
782 iter_tag = allowed_tags[index];
783 /* Look for a white listed tag */
784 cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
785 tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
786 (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
788 if (g_match_info_matches (match_info)) {
789 gint start_pos, end_pos;
790 gchar *word = g_match_info_fetch (match_info, 0);
791 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
792 if (start_pos == 0) {
793 offset = strlen (word);
797 g_match_info_free (match_info);
798 g_regex_unref (tag_regex);
802 /* OK we found a tag, let's keep track of it */
803 open_tags[num_open_tags] = g_strdup (iter_tag);
815 if (*next_tag == '<' && *(next_tag + 1) == '/') {
816 end_tag = strchr (cur, '>');
818 if (num_open_tags == 0
819 || g_ascii_strncasecmp (end_tag - 1, open_tags[num_open_tags - 1],
820 strlen (open_tags[num_open_tags - 1]))) {
821 GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
822 memmove (next_tag, end_tag + 1, strlen (end_tag) + 1);
823 next_tag -= strlen (end_tag);
826 g_free (open_tags[num_open_tags]);
834 if (num_open_tags > 0) {
837 s = g_string_new (*p_txt);
838 while (num_open_tags > 0) {
839 GST_LOG ("adding missing closing tag '%s'", open_tags[num_open_tags - 1]);
840 g_string_append_c (s, '<');
841 g_string_append_c (s, '/');
842 g_string_append (s, open_tags[num_open_tags - 1]);
843 g_string_append_c (s, '>');
844 g_free (open_tags[num_open_tags - 1]);
848 *p_txt = g_string_free (s, FALSE);
853 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
855 gchar s[128] = { '\0', };
857 guint hour, min, sec, msec, len;
859 while (*ts_string == ' ')
862 g_strlcpy (s, ts_string, sizeof (s));
863 if ((end = strstr (s, "-->")))
867 /* ms may be in these formats:
868 * hh:mm:ss,500 = 500ms
871 * hh:mm:ss, 50 = 50ms
873 * and the same with . instead of ,.
874 * sscanf() doesn't differentiate between ' 5' and '5' so munge
875 * the white spaces within the timestamp to '0' (I'm sure there's a
876 * way to make sscanf() do this for us, but how?)
878 g_strdelimit (s, " ", '0');
879 g_strdelimit (s, ".", ',');
881 /* make sure we have exactly three digits after he comma */
883 g_assert (p != NULL);
890 g_strlcat (&p[len], "0", 2);
894 GST_LOG ("parsing timestamp '%s'", s);
895 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
896 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
900 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
904 /* cue settings are part of the WebVTT specification. They are
905 * declared after the time interval in the first line of the
906 * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
907 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
910 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
912 gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
914 gint16 text_position, text_size;
915 gint16 line_position;
916 gboolean vertical_found = FALSE;
917 gboolean alignment_found = FALSE;
919 while (i < g_strv_length (splitted_settings)) {
920 gboolean valid_tag = FALSE;
921 switch (splitted_settings[i][0]) {
923 if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
924 &text_position) > 0) {
925 state->text_position = (guint8) text_position;
930 if (strlen (splitted_settings[i]) > 2) {
931 vertical_found = TRUE;
932 g_free (state->vertical);
933 state->vertical = g_strdup (splitted_settings[i] + 2);
938 if (g_str_has_suffix (splitted_settings[i], "%")) {
939 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
940 &line_position) > 0) {
941 state->line_position = line_position;
945 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
946 &line_position) > 0) {
947 state->line_number = line_position;
953 if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
955 state->text_size = (guint8) text_size;
960 if (strlen (splitted_settings[i]) > 2) {
961 g_free (state->alignment);
962 state->alignment = g_strdup (splitted_settings[i] + 2);
963 alignment_found = TRUE;
971 GST_LOG ("Invalid or unrecognised setting found: %s",
972 splitted_settings[i]);
976 g_strfreev (splitted_settings);
977 if (!vertical_found) {
978 g_free (state->vertical);
979 state->vertical = g_strdup ("");
981 if (!alignment_found) {
982 g_free (state->alignment);
983 state->alignment = g_strdup ("");
988 parse_subrip (ParserState * state, const gchar * line)
992 switch (state->state) {
997 /* looking for a single integer as a Cue ID, but we
998 * don't actually use it */
1000 id = g_ascii_strtoull (line, &endptr, 10);
1001 if (id == G_MAXUINT64 && errno == ERANGE)
1003 else if (id == 0 && errno == EINVAL)
1005 else if (endptr != line && *endptr == '\0')
1011 GstClockTime ts_start, ts_end;
1014 /* looking for start_time --> end_time */
1015 if ((end_time = strstr (line, " --> ")) &&
1016 parse_subrip_time (line, &ts_start) &&
1017 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1018 state->start_time <= ts_end) {
1020 state->start_time = ts_start;
1021 state->duration = ts_end - ts_start;
1023 GST_DEBUG ("error parsing subrip time line '%s'", line);
1030 /* No need to parse that text if it's out of segment */
1031 guint64 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_markup_escape_text (state->buf->str, state->buf->len);
1053 g_string_truncate (state->buf, 0);
1055 subrip_unescape_formatting (ret, state->allowed_tags,
1056 state->allows_tag_attributes);
1057 subrip_remove_unhandled_tags (ret);
1058 strip_trailing_newlines (ret);
1059 subrip_fix_up_markup (&ret, state->allowed_tags);
1064 g_return_val_if_reached (NULL);
1069 parse_lrc (ParserState * state, const gchar * line)
1078 if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1079 sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1082 start = strchr (line, ']');
1083 if (start - line == 9)
1088 state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1089 + gst_util_uint64_scale (s, GST_SECOND, 1)
1090 + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1091 state->duration = GST_CLOCK_TIME_NONE;
1093 return g_strdup (start + 1);
1096 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1097 * element. This format is similar to Subrip, the biggest differences
1098 * are that there can be cue settings detailing how to display the cue
1099 * text and more markup tags are allowed.
1100 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1103 parse_webvtt (ParserState * state, const gchar * line)
1105 /* Cue IDs are optional in WebVTT, but not in subrip,
1106 * so when in state 0 (cue ID), also check if we're
1107 * already at the start --> end time marker */
1108 if (state->state == 0 || state->state == 1) {
1109 GstClockTime ts_start, ts_end;
1111 gchar *cue_settings = NULL;
1113 /* looking for start_time --> end_time */
1114 if ((end_time = strstr (line, " --> ")) &&
1115 parse_subrip_time (line, &ts_start) &&
1116 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1117 state->start_time <= ts_end) {
1119 state->start_time = ts_start;
1120 state->duration = ts_end - ts_start;
1121 cue_settings = strstr (end_time + strlen (" --> "), " ");
1123 GST_DEBUG ("error parsing subrip time line '%s'", line);
1127 state->text_position = 0;
1128 state->text_size = 0;
1129 state->line_position = 0;
1130 state->line_number = 0;
1133 parse_webvtt_cue_settings (state, cue_settings + 1);
1135 g_free (state->vertical);
1136 state->vertical = g_strdup ("");
1137 g_free (state->alignment);
1138 state->alignment = g_strdup ("");
1143 return parse_subrip (state, line);
1147 unescape_newlines_br (gchar * read)
1149 gchar *write = read;
1151 /* Replace all occurences of '[br]' with a newline as version 2
1152 * of the subviewer format uses this for newlines */
1154 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1158 if (strncmp (read, "[br]", 4) == 0) {
1172 parse_subviewer (ParserState * state, const gchar * line)
1174 guint h1, m1, s1, ms1;
1175 guint h2, m2, s2, ms2;
1178 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1179 * For examples see the unit test or
1180 * http://www.doom9.org/index.html?/sub.htm */
1182 switch (state->state) {
1184 /* looking for start_time,end_time */
1185 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1186 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1189 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1192 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1193 ms2 * GST_MSECOND - state->start_time;
1198 /* No need to parse that text if it's out of segment */
1199 guint64 clip_start = 0, clip_stop = 0;
1200 gboolean in_seg = FALSE;
1202 /* Check our segment start/stop */
1203 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1204 state->start_time, state->start_time + state->duration,
1205 &clip_start, &clip_stop);
1208 state->start_time = clip_start;
1209 state->duration = clip_stop - clip_start;
1215 /* looking for subtitle text; empty line ends this subtitle entry */
1216 if (state->buf->len)
1217 g_string_append_c (state->buf, '\n');
1218 g_string_append (state->buf, line);
1219 if (strlen (line) == 0) {
1220 ret = g_strdup (state->buf->str);
1221 unescape_newlines_br (ret);
1222 strip_trailing_newlines (ret);
1223 g_string_truncate (state->buf, 0);
1229 g_assert_not_reached ();
1235 parse_mpsub (ParserState * state, const gchar * line)
1240 switch (state->state) {
1242 /* looking for two floats (offset, duration) */
1243 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1245 state->start_time += state->duration + GST_SECOND * t1;
1246 state->duration = GST_SECOND * t2;
1250 { /* No need to parse that text if it's out of segment */
1251 guint64 clip_start = 0, clip_stop = 0;
1252 gboolean in_seg = FALSE;
1254 /* Check our segment start/stop */
1255 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1256 state->start_time, state->start_time + state->duration,
1257 &clip_start, &clip_stop);
1260 state->start_time = clip_start;
1261 state->duration = clip_stop - clip_start;
1267 /* looking for subtitle text; empty line ends this
1269 if (state->buf->len)
1270 g_string_append_c (state->buf, '\n');
1271 g_string_append (state->buf, line);
1272 if (strlen (line) == 0) {
1273 ret = g_strdup (state->buf->str);
1274 g_string_truncate (state->buf, 0);
1280 g_assert_not_reached ();
1285 static const gchar *
1286 dks_skip_timestamp (const gchar * line)
1288 while (*line && *line != ']')
1296 parse_dks (ParserState * state, const gchar * line)
1300 switch (state->state) {
1302 /* Looking for the start time and text */
1303 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1305 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1306 text = dks_skip_timestamp (line);
1309 g_string_append (state->buf, text);
1315 guint64 clip_start = 0, clip_stop = 0;
1319 /* Looking for the end time */
1320 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1322 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1325 GST_WARNING ("Failed to parse subtitle end time");
1329 /* Check if this subtitle is out of the current segment */
1330 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1331 state->start_time, state->start_time + state->duration,
1332 &clip_start, &clip_stop);
1338 state->start_time = clip_start;
1339 state->duration = clip_stop - clip_start;
1341 ret = g_strdup (state->buf->str);
1342 g_string_truncate (state->buf, 0);
1343 unescape_newlines_br (ret);
1347 g_assert_not_reached ();
1353 parser_state_init (ParserState * state)
1355 GST_DEBUG ("initialising parser");
1358 g_string_truncate (state->buf, 0);
1360 state->buf = g_string_new (NULL);
1363 state->start_time = 0;
1364 state->duration = 0;
1365 state->max_duration = 0; /* no limit */
1367 state->segment = NULL;
1371 parser_state_dispose (GstSubParse * self, ParserState * state)
1374 g_string_free (state->buf, TRUE);
1378 g_free (state->vertical);
1379 state->vertical = NULL;
1380 g_free (state->alignment);
1381 state->alignment = NULL;
1383 if (state->user_data) {
1384 switch (self->parser_type) {
1385 case GST_SUB_PARSE_FORMAT_QTTEXT:
1386 qttext_context_deinit (state);
1388 case GST_SUB_PARSE_FORMAT_SAMI:
1389 sami_context_deinit (state);
1395 state->allowed_tags = NULL;
1398 /* regex type enum */
1401 GST_SUB_PARSE_REGEX_UNKNOWN = 0,
1402 GST_SUB_PARSE_REGEX_MDVDSUB = 1,
1403 GST_SUB_PARSE_REGEX_SUBRIP = 2,
1404 GST_SUB_PARSE_REGEX_DKS = 3,
1405 GST_SUB_PARSE_REGEX_VTT = 4,
1409 gst_sub_parse_data_format_autodetect_regex_once (GstSubParseRegex regtype)
1411 gpointer result = NULL;
1412 GError *gerr = NULL;
1414 case GST_SUB_PARSE_REGEX_MDVDSUB:
1416 (gpointer) g_regex_new ("^\\{[0-9]+\\}\\{[0-9]+\\}",
1417 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1418 if (result == NULL) {
1419 g_warning ("Compilation of mdvd regex failed: %s", gerr->message);
1420 g_clear_error (&gerr);
1423 case GST_SUB_PARSE_REGEX_SUBRIP:
1425 g_regex_new ("^[\\s\\n]*[\\n]? {0,3}[ 0-9]{1,4}\\s*(\x0d)?\x0a"
1426 " ?[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,3}"
1427 " +--> +[0-9]{1,2}: ?[0-9]{1,2}: ?[0-9]{1,2}[,.] {0,2}[0-9]{1,2}",
1428 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1429 if (result == NULL) {
1430 g_warning ("Compilation of subrip regex failed: %s", gerr->message);
1431 g_clear_error (&gerr);
1434 case GST_SUB_PARSE_REGEX_DKS:
1435 result = (gpointer) g_regex_new ("^\\[[0-9]+:[0-9]+:[0-9]+\\].*",
1436 G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, &gerr);
1437 if (result == NULL) {
1438 g_warning ("Compilation of dks regex failed: %s", gerr->message);
1439 g_clear_error (&gerr);
1442 case GST_SUB_PARSE_REGEX_VTT:
1444 g_regex_new ("^(\\xef\\xbb\\xbf)?WEBVTT[\\xa\\xd\\x20\\x9]", 0, 0,
1446 if (result == NULL) {
1447 g_warning ("Compilation of vtt regex failed: %s", gerr->message);
1448 g_error_free (gerr);
1453 GST_WARNING ("Trying to allocate regex of unknown type %u", regtype);
1459 * FIXME: maybe we should pass along a second argument, the preceding
1460 * text buffer, because that is how this originally worked, even though
1461 * I don't really see the use of that.
1464 static GstSubParseFormat
1465 gst_sub_parse_data_format_autodetect (gchar * match_str)
1469 static GOnce mdvd_rx_once = G_ONCE_INIT;
1470 static GOnce subrip_rx_once = G_ONCE_INIT;
1471 static GOnce dks_rx_once = G_ONCE_INIT;
1472 static GOnce vtt_rx_once = G_ONCE_INIT;
1479 g_once (&mdvd_rx_once,
1480 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1481 (gpointer) GST_SUB_PARSE_REGEX_MDVDSUB);
1482 g_once (&subrip_rx_once,
1483 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1484 (gpointer) GST_SUB_PARSE_REGEX_SUBRIP);
1485 g_once (&dks_rx_once,
1486 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1487 (gpointer) GST_SUB_PARSE_REGEX_DKS);
1488 g_once (&vtt_rx_once,
1489 (GThreadFunc) gst_sub_parse_data_format_autodetect_regex_once,
1490 (gpointer) GST_SUB_PARSE_REGEX_VTT);
1492 mdvd_grx = (GRegex *) mdvd_rx_once.retval;
1493 subrip_grx = (GRegex *) subrip_rx_once.retval;
1494 dks_grx = (GRegex *) dks_rx_once.retval;
1495 vtt_grx = (GRegex *) vtt_rx_once.retval;
1497 if (g_regex_match (mdvd_grx, match_str, 0, NULL)) {
1498 GST_LOG ("MicroDVD (frame based) format detected");
1499 return GST_SUB_PARSE_FORMAT_MDVDSUB;
1501 if (g_regex_match (subrip_grx, match_str, 0, NULL)) {
1502 GST_LOG ("SubRip (time based) format detected");
1503 return GST_SUB_PARSE_FORMAT_SUBRIP;
1505 if (g_regex_match (dks_grx, match_str, 0, NULL)) {
1506 GST_LOG ("DKS (time based) format detected");
1507 return GST_SUB_PARSE_FORMAT_DKS;
1509 if (g_regex_match (vtt_grx, match_str, 0, NULL) == TRUE) {
1510 GST_LOG ("WebVTT (time based) format detected");
1511 return GST_SUB_PARSE_FORMAT_VTT;
1514 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
1515 GST_LOG ("MPSub (time based) format detected");
1516 return GST_SUB_PARSE_FORMAT_MPSUB;
1518 if (strstr (match_str, "<SAMI>") != NULL ||
1519 strstr (match_str, "<sami>") != NULL) {
1520 GST_LOG ("SAMI (time based) format detected");
1521 return GST_SUB_PARSE_FORMAT_SAMI;
1523 /* we're boldly assuming the first subtitle appears within the first hour */
1524 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
1525 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
1526 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
1527 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
1528 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
1529 GST_LOG ("TMPlayer (time based) format detected");
1530 return GST_SUB_PARSE_FORMAT_TMPLAYER;
1532 if (sscanf (match_str, "[%u][%u]", &n1, &n2) == 2) {
1533 GST_LOG ("MPL2 (time based) format detected");
1534 return GST_SUB_PARSE_FORMAT_MPL2;
1536 if (strstr (match_str, "[INFORMATION]") != NULL) {
1537 GST_LOG ("SubViewer (time based) format detected");
1538 return GST_SUB_PARSE_FORMAT_SUBVIEWER;
1540 if (strstr (match_str, "{QTtext}") != NULL) {
1541 GST_LOG ("QTtext (time based) format detected");
1542 return GST_SUB_PARSE_FORMAT_QTTEXT;
1544 /* We assume the LRC file starts immediately */
1545 if (match_str[0] == '[') {
1546 gboolean all_lines_good = TRUE;
1550 ptr = split = g_strsplit (match_str, "\n", -1);
1551 while (*ptr && *(ptr + 1)) {
1553 gint len = strlen (str);
1555 if (sscanf (str, "[%u:%02u.%02u]", &n1, &n2, &n3) == 3 ||
1556 sscanf (str, "[%u:%02u.%03u]", &n1, &n2, &n3) == 3) {
1557 all_lines_good = TRUE;
1558 } else if (str[len - 1] == ']' && strchr (str, ':') != NULL) {
1559 all_lines_good = TRUE;
1561 all_lines_good = FALSE;
1570 return GST_SUB_PARSE_FORMAT_LRC;
1573 GST_DEBUG ("no subtitle format detected");
1574 return GST_SUB_PARSE_FORMAT_UNKNOWN;
1578 gst_sub_parse_format_autodetect (GstSubParse * self)
1581 GstSubParseFormat format;
1583 if (strlen (self->textbuf->str) < 30) {
1584 GST_DEBUG ("File too small to be a subtitles file");
1588 data = g_strndup (self->textbuf->str, 35);
1589 format = gst_sub_parse_data_format_autodetect (data);
1592 self->parser_type = format;
1593 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1594 parser_state_init (&self->state);
1595 self->state.allowed_tags = NULL;
1598 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1599 self->parse_line = parse_mdvdsub;
1600 return gst_caps_new_simple ("text/x-raw",
1601 "format", G_TYPE_STRING, "pango-markup", NULL);
1602 case GST_SUB_PARSE_FORMAT_SUBRIP:
1603 self->state.allowed_tags = (gpointer) allowed_srt_tags;
1604 self->state.allows_tag_attributes = FALSE;
1605 self->parse_line = parse_subrip;
1606 return gst_caps_new_simple ("text/x-raw",
1607 "format", G_TYPE_STRING, "pango-markup", NULL);
1608 case GST_SUB_PARSE_FORMAT_MPSUB:
1609 self->parse_line = parse_mpsub;
1610 return gst_caps_new_simple ("text/x-raw",
1611 "format", G_TYPE_STRING, "utf8", NULL);
1612 case GST_SUB_PARSE_FORMAT_SAMI:
1613 self->parse_line = parse_sami;
1614 sami_context_init (&self->state);
1615 return gst_caps_new_simple ("text/x-raw",
1616 "format", G_TYPE_STRING, "pango-markup", NULL);
1617 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1618 self->parse_line = parse_tmplayer;
1619 self->state.max_duration = 5 * GST_SECOND;
1620 return gst_caps_new_simple ("text/x-raw",
1621 "format", G_TYPE_STRING, "utf8", NULL);
1622 case GST_SUB_PARSE_FORMAT_MPL2:
1623 self->parse_line = parse_mpl2;
1624 return gst_caps_new_simple ("text/x-raw",
1625 "format", G_TYPE_STRING, "pango-markup", NULL);
1626 case GST_SUB_PARSE_FORMAT_DKS:
1627 self->parse_line = parse_dks;
1628 return gst_caps_new_simple ("text/x-raw",
1629 "format", G_TYPE_STRING, "utf8", NULL);
1630 case GST_SUB_PARSE_FORMAT_VTT:
1631 self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1632 self->state.allows_tag_attributes = TRUE;
1633 self->parse_line = parse_webvtt;
1634 return gst_caps_new_simple ("text/x-raw",
1635 "format", G_TYPE_STRING, "pango-markup", NULL);
1636 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1637 self->parse_line = parse_subviewer;
1638 return gst_caps_new_simple ("text/x-raw",
1639 "format", G_TYPE_STRING, "utf8", NULL);
1640 case GST_SUB_PARSE_FORMAT_QTTEXT:
1641 self->parse_line = parse_qttext;
1642 qttext_context_init (&self->state);
1643 return gst_caps_new_simple ("text/x-raw",
1644 "format", G_TYPE_STRING, "pango-markup", NULL);
1645 case GST_SUB_PARSE_FORMAT_LRC:
1646 self->parse_line = parse_lrc;
1647 return gst_caps_new_simple ("text/x-raw",
1648 "format", G_TYPE_STRING, "utf8", NULL);
1649 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1651 GST_DEBUG ("no subtitle format detected");
1652 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1653 ("The input is not a valid/supported subtitle file"), (NULL));
1659 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1663 gchar *input = NULL;
1667 discont = GST_BUFFER_IS_DISCONT (buf);
1669 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1670 GST_BUFFER_OFFSET (buf) != self->offset) {
1671 self->offset = GST_BUFFER_OFFSET (buf);
1676 GST_INFO ("discontinuity");
1677 /* flush the parser state */
1678 parser_state_init (&self->state);
1679 g_string_truncate (self->textbuf, 0);
1680 gst_adapter_clear (self->adapter);
1681 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1682 sami_context_reset (&self->state);
1683 /* we could set a flag to make sure that the next buffer we push out also
1684 * has the DISCONT flag set, but there's no point really given that it's
1685 * subtitles which are discontinuous by nature. */
1688 self->offset += gst_buffer_get_size (buf);
1690 gst_adapter_push (self->adapter, buf);
1692 avail = gst_adapter_available (self->adapter);
1693 data = gst_adapter_map (self->adapter, avail);
1694 input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1696 if (input && consumed > 0) {
1697 self->textbuf = g_string_append (self->textbuf, input);
1698 gst_adapter_unmap (self->adapter);
1699 gst_adapter_flush (self->adapter, consumed);
1701 gst_adapter_unmap (self->adapter);
1707 static GstFlowReturn
1708 handle_buffer (GstSubParse * self, GstBuffer * buf)
1710 GstFlowReturn ret = GST_FLOW_OK;
1711 GstCaps *caps = NULL;
1712 gchar *line, *subtitle;
1713 gboolean need_tags = FALSE;
1715 if (self->first_buffer) {
1718 gst_buffer_map (buf, &map, GST_MAP_READ);
1719 self->detected_encoding = detect_encoding ((gchar *) map.data, map.size);
1720 gst_buffer_unmap (buf, &map);
1721 self->first_buffer = FALSE;
1722 self->state.fps_n = self->fps_n;
1723 self->state.fps_d = self->fps_d;
1726 feed_textbuf (self, buf);
1728 /* make sure we know the format */
1729 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1730 if (!(caps = gst_sub_parse_format_autodetect (self))) {
1731 return GST_FLOW_EOS;
1733 if (!gst_pad_set_caps (self->srcpad, caps)) {
1734 gst_caps_unref (caps);
1735 return GST_FLOW_EOS;
1737 gst_caps_unref (caps);
1741 /* Push newsegment if needed */
1742 if (self->need_segment) {
1743 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1746 gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1747 self->need_segment = FALSE;
1752 if (self->subtitle_codec != NULL) {
1755 tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1757 gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1761 while (!self->flushing && (line = get_next_line (self))) {
1764 /* Set segment on our parser state machine */
1765 self->state.segment = &self->segment;
1766 /* Now parse the line, out of segment lines will just return NULL */
1767 GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1769 subtitle = self->parse_line (&self->state, line + offset);
1773 guint subtitle_len = strlen (subtitle);
1775 /* +1 for terminating NUL character */
1776 buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1778 /* copy terminating NUL character as well */
1779 gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1780 gst_buffer_set_size (buf, subtitle_len);
1782 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1783 GST_BUFFER_DURATION (buf) = self->state.duration;
1785 /* in some cases (e.g. tmplayer) we can only determine the duration
1786 * of a text chunk from the timestamp of the next text chunk; in those
1787 * cases, we probably want to limit the duration to something
1788 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1789 * just because nothing else is being said during that time */
1790 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1791 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1792 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1795 self->segment.position = self->state.start_time;
1797 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1798 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1799 GST_TIME_ARGS (self->state.duration));
1801 g_free (self->state.vertical);
1802 self->state.vertical = NULL;
1803 g_free (self->state.alignment);
1804 self->state.alignment = NULL;
1806 ret = gst_pad_push (self->srcpad, buf);
1808 /* move this forward (the tmplayer parser needs this) */
1809 if (self->state.duration != GST_CLOCK_TIME_NONE)
1810 self->state.start_time += self->state.duration;
1815 if (ret != GST_FLOW_OK) {
1816 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1825 static GstFlowReturn
1826 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1831 self = GST_SUBPARSE (parent);
1833 ret = handle_buffer (self, buf);
1839 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1841 GstSubParse *self = GST_SUBPARSE (parent);
1842 gboolean ret = FALSE;
1844 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
1846 switch (GST_EVENT_TYPE (event)) {
1847 case GST_EVENT_EOS:{
1848 /* Make sure the last subrip chunk is pushed out even
1849 * if the file does not have an empty line at the end */
1850 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1851 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1852 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1853 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT) {
1854 gchar term_chars[] = { '\n', '\n', '\0' };
1855 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1857 GST_DEBUG ("EOS. Pushing remaining text (if any)");
1858 gst_buffer_fill (buf, 0, term_chars, 3);
1859 gst_buffer_set_size (buf, 2);
1861 GST_BUFFER_OFFSET (buf) = self->offset;
1862 gst_sub_parse_chain (pad, parent, buf);
1864 ret = gst_pad_event_default (pad, parent, event);
1867 case GST_EVENT_SEGMENT:
1869 const GstSegment *s;
1870 gst_event_parse_segment (event, &s);
1871 if (s->format == GST_FORMAT_TIME)
1872 gst_event_copy_segment (event, &self->segment);
1873 GST_DEBUG_OBJECT (self, "newsegment (%s)",
1874 gst_format_get_name (self->segment.format));
1876 /* if not time format, we'll either start with a 0 timestamp anyway or
1877 * it's following a seek in which case we'll have saved the requested
1878 * seek segment and don't want to overwrite it (remember that on a seek
1879 * we always just seek back to the start in BYTES format and just throw
1880 * away all text that's before the requested position; if the subtitles
1881 * come from an upstream demuxer, it won't be able to handle our BYTES
1882 * seek request and instead send us a newsegment from the seek request
1883 * it received via its video pads instead, so all is fine then too) */
1885 gst_event_unref (event);
1886 /* in either case, let's not simply discard this event;
1887 * trigger sending of the saved requested seek segment
1888 * or the one taken here from upstream */
1889 self->need_segment = TRUE;
1892 case GST_EVENT_FLUSH_START:
1894 self->flushing = TRUE;
1896 ret = gst_pad_event_default (pad, parent, event);
1899 case GST_EVENT_FLUSH_STOP:
1901 self->flushing = FALSE;
1903 ret = gst_pad_event_default (pad, parent, event);
1907 ret = gst_pad_event_default (pad, parent, event);
1915 static GstStateChangeReturn
1916 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1918 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1919 GstSubParse *self = GST_SUBPARSE (element);
1921 switch (transition) {
1922 case GST_STATE_CHANGE_READY_TO_PAUSED:
1923 /* format detection will init the parser state */
1925 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1926 self->valid_utf8 = TRUE;
1927 self->first_buffer = TRUE;
1928 g_free (self->detected_encoding);
1929 self->detected_encoding = NULL;
1930 g_string_truncate (self->textbuf, 0);
1931 gst_adapter_clear (self->adapter);
1937 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1938 if (ret == GST_STATE_CHANGE_FAILURE)
1941 switch (transition) {
1942 case GST_STATE_CHANGE_PAUSED_TO_READY:
1943 parser_state_dispose (self, &self->state);
1944 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1957 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1958 * also, give different subtitle formats really different types */
1959 static GstStaticCaps mpl2_caps =
1960 GST_STATIC_CAPS ("application/x-subtitle-mpl2");
1961 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1963 static GstStaticCaps tmp_caps =
1964 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1965 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1967 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1968 #define MPL2_CAPS (gst_static_caps_get (&mpl2_caps))
1970 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1971 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1973 static GstStaticCaps dks_caps = GST_STATIC_CAPS ("application/x-subtitle-dks");
1974 #define DKS_CAPS (gst_static_caps_get (&dks_caps))
1976 static GstStaticCaps vtt_caps = GST_STATIC_CAPS ("application/x-subtitle-vtt");
1977 #define VTT_CAPS (gst_static_caps_get (&vtt_caps))
1979 static GstStaticCaps qttext_caps =
1980 GST_STATIC_CAPS ("application/x-subtitle-qttext");
1981 #define QTTEXT_CAPS (gst_static_caps_get (&qttext_caps))
1983 static GstStaticCaps lrc_caps = GST_STATIC_CAPS ("application/x-subtitle-lrc");
1984 #define LRC_CAPS (gst_static_caps_get (&lrc_caps))
1987 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1989 GstSubParseFormat format;
1993 gchar *encoding = NULL;
1996 if (!(data = gst_type_find_peek (tf, 0, 129)))
1999 /* make sure string passed to _autodetect() is NUL-terminated */
2000 str = g_malloc0 (129);
2001 memcpy (str, data, 128);
2003 if ((encoding = detect_encoding (str, 128)) != NULL) {
2004 gchar *converted_str;
2008 converted_str = gst_convert_to_utf8 (str, 128, encoding, &tmp, &err);
2009 if (converted_str == NULL) {
2010 GST_DEBUG ("Encoding '%s' detected but conversion failed: %s", encoding,
2012 g_clear_error (&err);
2015 str = converted_str;
2020 /* Check if at least the first 120 chars are valid UTF8,
2021 * otherwise convert as always */
2022 if (!g_utf8_validate (str, 128, &end) && (end - str) < 120) {
2023 gchar *converted_str;
2027 enc = g_getenv ("GST_SUBTITLE_ENCODING");
2028 if (enc == NULL || *enc == '\0') {
2029 /* if local encoding is UTF-8 and no encoding specified
2030 * via the environment variable, assume ISO-8859-15 */
2031 if (g_get_charset (&enc)) {
2032 enc = "ISO-8859-15";
2035 converted_str = gst_convert_to_utf8 (str, 128, enc, &tmp, NULL);
2036 if (converted_str != NULL) {
2038 str = converted_str;
2042 format = gst_sub_parse_data_format_autodetect (str);
2046 case GST_SUB_PARSE_FORMAT_MDVDSUB:
2047 GST_DEBUG ("MicroDVD format detected");
2050 case GST_SUB_PARSE_FORMAT_SUBRIP:
2051 GST_DEBUG ("SubRip format detected");
2054 case GST_SUB_PARSE_FORMAT_MPSUB:
2055 GST_DEBUG ("MPSub format detected");
2058 case GST_SUB_PARSE_FORMAT_SAMI:
2059 GST_DEBUG ("SAMI (time-based) format detected");
2062 case GST_SUB_PARSE_FORMAT_TMPLAYER:
2063 GST_DEBUG ("TMPlayer (time based) format detected");
2066 /* FIXME: our MPL2 typefinding is not really good enough to warrant
2067 * returning a high probability (however, since we registered our
2068 * typefinder here with a rank of MARGINAL we should pretty much only
2069 * be called if most other typefinders have already run */
2070 case GST_SUB_PARSE_FORMAT_MPL2:
2071 GST_DEBUG ("MPL2 (time based) format detected");
2074 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
2075 GST_DEBUG ("SubViewer format detected");
2078 case GST_SUB_PARSE_FORMAT_DKS:
2079 GST_DEBUG ("DKS format detected");
2082 case GST_SUB_PARSE_FORMAT_QTTEXT:
2083 GST_DEBUG ("QTtext format detected");
2086 case GST_SUB_PARSE_FORMAT_LRC:
2087 GST_DEBUG ("LRC format detected");
2090 case GST_SUB_PARSE_FORMAT_VTT:
2091 GST_DEBUG ("WebVTT format detected");
2095 case GST_SUB_PARSE_FORMAT_UNKNOWN:
2096 GST_DEBUG ("no subtitle format detected");
2100 /* if we're here, it's ok */
2101 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
2105 plugin_init (GstPlugin * plugin)
2107 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
2109 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
2110 gst_subparse_type_find, "srt,sub,mpsub,mdvd,smi,txt,dks,vtt",
2111 SUB_CAPS, NULL, NULL))
2114 if (!gst_element_register (plugin, "subparse",
2115 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
2116 !gst_element_register (plugin, "ssaparse",
2117 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
2124 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2128 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)