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"
36 #include "gstssaparse.h"
37 #include "samiparse.h"
38 #include "tmplayerparse.h"
39 #include "mpl2parse.h"
40 #include "qttextparse.h"
41 #include "gstsubparseelements.h"
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);
96 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (subparse, "subparse",
97 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE, sub_parse_element_init (plugin))
100 static void gst_sub_parse_dispose (GObject * object)
102 GstSubParse *subparse = GST_SUBPARSE (object);
104 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
106 if (subparse->encoding) {
107 g_free (subparse->encoding);
108 subparse->encoding = NULL;
111 if (subparse->detected_encoding) {
112 g_free (subparse->detected_encoding);
113 subparse->detected_encoding = NULL;
116 if (subparse->adapter) {
117 g_object_unref (subparse->adapter);
118 subparse->adapter = NULL;
121 if (subparse->textbuf) {
122 g_string_free (subparse->textbuf, TRUE);
123 subparse->textbuf = NULL;
126 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
130 gst_sub_parse_class_init (GstSubParseClass * klass)
132 GObjectClass *object_class = G_OBJECT_CLASS (klass);
133 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
135 object_class->dispose = gst_sub_parse_dispose;
136 object_class->set_property = gst_sub_parse_set_property;
137 object_class->get_property = gst_sub_parse_get_property;
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_static_metadata (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.freedesktop.org>");
147 element_class->change_state = gst_sub_parse_change_state;
149 g_object_class_install_property (object_class, PROP_ENCODING,
150 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
151 "Encoding to assume if input subtitles are not in UTF-8 or any other "
152 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
153 "variable will be checked for an encoding to use. If that is not set "
154 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
155 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
157 g_object_class_install_property (object_class, PROP_VIDEOFPS,
158 gst_param_spec_fraction ("video-fps", "Video framerate",
159 "Framerate of the video stream. This is needed by some subtitle "
160 "formats to synchronize subtitles and video properly. If not set "
161 "and the subtitle format requires it subtitles may be out of sync.",
162 0, 1, G_MAXINT, 1, 24000, 1001,
163 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
167 gst_sub_parse_init (GstSubParse * subparse)
169 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
170 gst_pad_set_chain_function (subparse->sinkpad,
171 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
172 gst_pad_set_event_function (subparse->sinkpad,
173 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
174 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
176 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
177 gst_pad_set_event_function (subparse->srcpad,
178 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
179 gst_pad_set_query_function (subparse->srcpad,
180 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
181 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
183 subparse->textbuf = g_string_new (NULL);
184 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
185 subparse->strip_pango_markup = FALSE;
186 subparse->flushing = FALSE;
187 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
188 subparse->segment_seqnum = gst_util_seqnum_next ();
189 subparse->need_segment = TRUE;
190 subparse->encoding = g_strdup (DEFAULT_ENCODING);
191 subparse->detected_encoding = NULL;
192 subparse->adapter = gst_adapter_new ();
194 subparse->fps_n = 24000;
195 subparse->fps_d = 1001;
199 * Source pad functions.
203 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
205 GstSubParse *self = GST_SUBPARSE (parent);
206 gboolean ret = FALSE;
208 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
210 switch (GST_QUERY_TYPE (query)) {
211 case GST_QUERY_POSITION:{
214 gst_query_parse_position (query, &fmt, NULL);
215 if (fmt != GST_FORMAT_TIME) {
216 ret = gst_pad_peer_query (self->sinkpad, query);
219 gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
223 case GST_QUERY_SEEKING:
226 gboolean seekable = FALSE;
230 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
231 if (fmt == GST_FORMAT_TIME) {
232 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
234 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
236 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
237 gst_query_unref (peerquery);
240 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
244 ret = gst_pad_query_default (pad, parent, query);
252 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
254 GstSubParse *self = GST_SUBPARSE (parent);
255 gboolean ret = FALSE;
257 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
259 switch (GST_EVENT_TYPE (event)) {
264 GstSeekType start_type, stop_type;
269 gst_event_parse_seek (event, &rate, &format, &flags,
270 &start_type, &start, &stop_type, &stop);
272 if (format != GST_FORMAT_TIME) {
273 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
274 gst_event_unref (event);
278 /* Convert that seek to a seeking in bytes at position 0,
279 FIXME: could use an index */
280 ret = gst_pad_push_event (self->sinkpad,
281 gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
282 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
285 /* Apply the seek to our segment */
286 gst_segment_do_seek (&self->segment, rate, format, flags,
287 start_type, start, stop_type, stop, &update);
289 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
292 /* will mark need_segment when receiving segment from upstream,
293 * after FLUSH and all that has happened,
294 * rather than racing with chain */
296 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
299 gst_event_unref (event);
303 ret = gst_pad_event_default (pad, parent, event);
312 gst_sub_parse_set_property (GObject * object, guint prop_id,
313 const GValue * value, GParamSpec * pspec)
315 GstSubParse *subparse = GST_SUBPARSE (object);
317 GST_OBJECT_LOCK (subparse);
320 g_free (subparse->encoding);
321 subparse->encoding = g_value_dup_string (value);
322 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
323 GST_STR_NULL (subparse->encoding));
327 subparse->fps_n = gst_value_get_fraction_numerator (value);
328 subparse->fps_d = gst_value_get_fraction_denominator (value);
329 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
332 if (!subparse->state.have_internal_fps) {
333 subparse->state.fps_n = subparse->fps_n;
334 subparse->state.fps_d = subparse->fps_d;
339 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
342 GST_OBJECT_UNLOCK (subparse);
346 gst_sub_parse_get_property (GObject * object, guint prop_id,
347 GValue * value, GParamSpec * pspec)
349 GstSubParse *subparse = GST_SUBPARSE (object);
351 GST_OBJECT_LOCK (subparse);
354 g_value_set_string (value, subparse->encoding);
357 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
360 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
363 GST_OBJECT_UNLOCK (subparse);
367 gst_sub_parse_get_format_description (GstSubParseFormat format)
370 case GST_SUB_PARSE_FORMAT_MDVDSUB:
372 case GST_SUB_PARSE_FORMAT_SUBRIP:
374 case GST_SUB_PARSE_FORMAT_MPSUB:
376 case GST_SUB_PARSE_FORMAT_SAMI:
378 case GST_SUB_PARSE_FORMAT_TMPLAYER:
380 case GST_SUB_PARSE_FORMAT_MPL2:
382 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
384 case GST_SUB_PARSE_FORMAT_DKS:
386 case GST_SUB_PARSE_FORMAT_VTT:
388 case GST_SUB_PARSE_FORMAT_QTTEXT:
390 case GST_SUB_PARSE_FORMAT_LRC:
393 case GST_SUB_PARSE_FORMAT_UNKNOWN:
404 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
407 const gchar *encoding;
413 /* First try any detected encoding */
414 if (self->detected_encoding) {
416 gst_sub_parse_gst_convert_to_utf8 (str, len, self->detected_encoding,
422 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
423 self->detected_encoding, err->message);
424 g_free (self->detected_encoding);
425 self->detected_encoding = NULL;
426 g_clear_error (&err);
429 /* Otherwise check if it's UTF8 */
430 if (self->valid_utf8) {
431 if (g_utf8_validate (str, len, NULL)) {
432 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
434 return g_strndup (str, len);
436 GST_INFO_OBJECT (self, "invalid UTF-8!");
437 self->valid_utf8 = FALSE;
440 /* Else try fallback */
441 encoding = self->encoding;
442 if (encoding == NULL || *encoding == '\0') {
443 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
445 if (encoding == NULL || *encoding == '\0') {
446 /* if local encoding is UTF-8 and no encoding specified
447 * via the environment variable, assume ISO-8859-15 */
448 if (g_get_charset (&encoding)) {
449 encoding = "ISO-8859-15";
453 ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
456 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
457 encoding, err->message);
458 g_clear_error (&err);
460 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
462 gst_sub_parse_gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed,
466 GST_LOG_OBJECT (self,
467 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
468 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
474 get_next_line (GstSubParse * self)
477 const char *line_end;
479 gboolean have_r = FALSE;
481 line_end = strchr (self->textbuf->str, '\n');
484 /* end-of-line not found; return for more data */
488 /* get rid of '\r' */
489 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
494 line_len = line_end - self->textbuf->str;
495 line = g_strndup (self->textbuf->str, line_len);
496 self->textbuf = g_string_erase (self->textbuf, 0,
497 line_len + (have_r ? 2 : 1));
502 parse_mdvdsub (ParserState * state, const gchar * line)
504 const gchar *line_split;
506 guint start_frame, end_frame;
507 guint64 clip_start = 0, clip_stop = 0;
508 gboolean in_seg = FALSE;
512 /* style variables */
518 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
519 GST_WARNING ("Parsing of the following line, assumed to be in microdvd .sub"
520 " format, failed:\n%s", line);
524 /* skip the {%u}{%u} part */
525 line = strchr (line, '}') + 1;
526 line = strchr (line, '}') + 1;
528 /* see if there's a first line with a framerate */
529 if (start_frame == 1 && end_frame == 1) {
530 gchar *rest, *end = NULL;
532 rest = g_strdup (line);
533 g_strdelimit (rest, ",", '.');
534 fps = g_ascii_strtod (rest, &end);
536 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
537 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
545 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
548 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
551 /* Check our segment start/stop */
552 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
553 state->start_time, state->start_time + state->duration, &clip_start,
556 /* No need to parse that text if it's out of segment */
558 state->start_time = clip_start;
559 state->duration = clip_stop - clip_start;
564 markup = g_string_new (NULL);
569 /* parse style markup */
570 if (strncmp (line, "{y:i}", 5) == 0) {
572 line = strchr (line, '}') + 1;
574 if (strncmp (line, "{y:b}", 5) == 0) {
576 line = strchr (line, '}') + 1;
578 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
579 line = strchr (line, '}') + 1;
581 /* forward slashes at beginning/end signify italics too */
582 if (g_str_has_prefix (line, "/")) {
586 if ((line_split = strchr (line, '|')))
587 line_chunk = g_markup_escape_text (line, line_split - line);
589 line_chunk = g_markup_escape_text (line, strlen (line));
591 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
592 * always at the end of a line or can they span multiple lines?) */
593 if (g_str_has_suffix (line_chunk, "/")) {
594 line_chunk[strlen (line_chunk) - 1] = '\0';
597 markup = g_string_append (markup, "<span");
599 g_string_append (markup, " style=\"italic\"");
601 g_string_append (markup, " weight=\"bold\"");
603 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
604 g_string_append_printf (markup, ">%s</span>", line_chunk);
607 g_string_append (markup, "\n");
608 line = line_split + 1;
614 g_string_free (markup, FALSE);
615 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
616 state->start_time / (double) GST_SECOND,
617 state->duration / (double) GST_SECOND, ret);
622 strip_trailing_newlines (gchar * txt)
628 while (len > 1 && txt[len - 1] == '\n') {
635 /* we want to escape text in general, but retain basic markup like
636 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
637 * just unescape a white list of allowed markups again after
638 * escaping everything (the text between these simple markers isn't
639 * necessarily escaped, so it seems best to do it like this) */
641 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
642 gboolean allows_tag_attributes)
646 gchar *allowed_tags_pattern, *search_pattern;
647 const gchar *replace_pattern;
649 /* No processing needed if no escaped tag marker found in the string. */
650 if (strstr (txt, "<") == NULL)
653 /* Build a list of alternates for our regexp.
654 * FIXME: Could be built once and stored */
655 allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
656 /* Look for starting/ending escaped tags with optional attributes. */
657 search_pattern = g_strdup_printf ("<(/)?\\ *(%s)(%s)>",
658 allowed_tags_pattern, ATTRIBUTE_REGEX);
659 /* And unescape appropriately */
660 if (allows_tag_attributes) {
661 replace_pattern = "<\\1\\2\\3>";
663 replace_pattern = "<\\1\\2>";
666 tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
667 res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
668 replace_pattern, 0, NULL);
670 /* res will always be shorter than the input or identical, so this
675 g_free (search_pattern);
676 g_free (allowed_tags_pattern);
678 g_regex_unref (tag_regex);
683 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
687 tag = start + strlen ("<");
691 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
696 GST_LOG ("removing unhandled tag '%s'", start);
698 memmove (start, stop, strlen (stop) + 1);
702 /* remove tags we haven't explicitly allowed earlier on, like font tags
705 subrip_remove_unhandled_tags (gchar * txt)
709 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
710 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
711 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
717 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
718 * take a simple approach. This code assumes the input has been
719 * escaped and subrip_unescape_formatting() has then been run over the
720 * input! This function adds missing closing markup tags and removes
721 * broken closing tags for tags that have never been opened. */
723 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
725 gchar *cur, *next_tag;
726 GPtrArray *open_tags = NULL;
727 guint num_open_tags = 0;
728 const gchar *iter_tag;
734 GMatchInfo *match_info;
735 gchar **allowed_tags = (gchar **) allowed_tags_ptr;
737 g_assert (*p_txt != NULL);
739 open_tags = g_ptr_array_new_with_free_func (g_free);
741 while (*cur != '\0') {
742 next_tag = strchr (cur, '<');
743 if (next_tag == NULL)
747 while (index < g_strv_length (allowed_tags)) {
748 iter_tag = allowed_tags[index];
749 /* Look for a white listed tag */
750 cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
751 tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
752 (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
754 if (g_match_info_matches (match_info)) {
755 gint start_pos, end_pos;
756 gchar *word = g_match_info_fetch (match_info, 0);
757 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
758 if (start_pos == 0) {
759 offset = strlen (word);
763 g_match_info_free (match_info);
764 g_regex_unref (tag_regex);
768 /* OK we found a tag, let's keep track of it */
769 g_ptr_array_add (open_tags, g_ascii_strdown (iter_tag, -1));
781 if (*next_tag == '<' && *(next_tag + 1) == '/') {
782 end_tag = strchr (next_tag, '>');
784 const gchar *last = NULL;
785 if (num_open_tags > 0)
786 last = g_ptr_array_index (open_tags, num_open_tags - 1);
787 if (num_open_tags == 0
788 || g_ascii_strncasecmp (end_tag - 1, last, strlen (last))) {
789 GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
790 /* Move everything after the tag end, including closing \0 */
791 memmove (next_tag, end_tag + 1, strlen (end_tag));
796 g_ptr_array_remove_index (open_tags, num_open_tags);
806 if (num_open_tags > 0) {
809 s = g_string_new (*p_txt);
810 while (num_open_tags > 0) {
811 GST_LOG ("adding missing closing tag '%s'",
812 (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
813 g_string_append_c (s, '<');
814 g_string_append_c (s, '/');
815 g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
816 g_string_append_c (s, '>');
820 *p_txt = g_string_free (s, FALSE);
822 g_ptr_array_free (open_tags, TRUE);
826 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
828 gchar s[128] = { '\0', };
830 guint hour, min, sec, msec, len;
832 while (*ts_string == ' ')
835 g_strlcpy (s, ts_string, sizeof (s));
836 if ((end = strstr (s, "-->")))
840 /* ms may be in these formats:
841 * hh:mm:ss,500 = 500ms
844 * hh:mm:ss, 50 = 50ms
846 * and the same with . instead of ,.
847 * sscanf() doesn't differentiate between ' 5' and '5' so munge
848 * the white spaces within the timestamp to '0' (I'm sure there's a
849 * way to make sscanf() do this for us, but how?)
851 g_strdelimit (s, " ", '0');
852 g_strdelimit (s, ".", ',');
854 /* make sure we have exactly three digits after he comma */
857 /* If there isn't a ',' the timestamp is broken */
858 /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
859 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
869 g_strlcat (&p[len], "0", 2);
873 GST_LOG ("parsing timestamp '%s'", s);
874 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
875 /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
877 * The hours component is optional with webVTT, for example
878 * mm:ss,500 is a valid webVTT timestamp. When not present,
883 if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
884 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
889 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
893 /* cue settings are part of the WebVTT specification. They are
894 * declared after the time interval in the first line of the
895 * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
896 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
899 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
901 gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
903 gint16 text_position, text_size;
904 gint16 line_position;
905 gboolean vertical_found = FALSE;
906 gboolean alignment_found = FALSE;
908 while (i < g_strv_length (splitted_settings)) {
909 gboolean valid_tag = FALSE;
910 switch (splitted_settings[i][0]) {
912 if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
913 &text_position) > 0) {
914 state->text_position = (guint8) text_position;
919 if (strlen (splitted_settings[i]) > 2) {
920 vertical_found = TRUE;
921 g_free (state->vertical);
922 state->vertical = g_strdup (splitted_settings[i] + 2);
927 if (g_str_has_suffix (splitted_settings[i], "%")) {
928 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
929 &line_position) > 0) {
930 state->line_position = line_position;
934 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
935 &line_position) > 0) {
936 state->line_number = line_position;
942 if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
944 state->text_size = (guint8) text_size;
949 if (strlen (splitted_settings[i]) > 2) {
950 g_free (state->alignment);
951 state->alignment = g_strdup (splitted_settings[i] + 2);
952 alignment_found = TRUE;
960 GST_LOG ("Invalid or unrecognised setting found: %s",
961 splitted_settings[i]);
965 g_strfreev (splitted_settings);
966 if (!vertical_found) {
967 g_free (state->vertical);
968 state->vertical = g_strdup ("");
970 if (!alignment_found) {
971 g_free (state->alignment);
972 state->alignment = g_strdup ("");
977 parse_subrip (ParserState * state, const gchar * line)
981 switch (state->state) {
986 /* looking for a single integer as a Cue ID, but we
987 * don't actually use it */
989 id = g_ascii_strtoull (line, &endptr, 10);
990 if (id == G_MAXUINT64 && errno == ERANGE)
992 else if (id == 0 && errno == EINVAL)
994 else if (endptr != line && *endptr == '\0')
1000 GstClockTime ts_start, ts_end;
1003 /* looking for start_time --> end_time */
1004 if ((end_time = strstr (line, " --> ")) &&
1005 parse_subrip_time (line, &ts_start) &&
1006 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1007 state->start_time <= ts_end) {
1009 state->start_time = ts_start;
1010 state->duration = ts_end - ts_start;
1012 GST_DEBUG ("error parsing subrip time line '%s'", line);
1019 /* No need to parse that text if it's out of segment */
1020 guint64 clip_start = 0, clip_stop = 0;
1021 gboolean in_seg = FALSE;
1023 /* Check our segment start/stop */
1024 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1025 state->start_time, state->start_time + state->duration,
1026 &clip_start, &clip_stop);
1029 state->start_time = clip_start;
1030 state->duration = clip_stop - clip_start;
1036 /* looking for subtitle text; empty line ends this subtitle entry */
1037 if (state->buf->len)
1038 g_string_append_c (state->buf, '\n');
1039 g_string_append (state->buf, line);
1040 if (strlen (line) == 0) {
1041 ret = g_markup_escape_text (state->buf->str, state->buf->len);
1042 g_string_truncate (state->buf, 0);
1044 subrip_unescape_formatting (ret, state->allowed_tags,
1045 state->allows_tag_attributes);
1046 subrip_remove_unhandled_tags (ret);
1047 strip_trailing_newlines (ret);
1048 subrip_fix_up_markup (&ret, state->allowed_tags);
1053 g_return_val_if_reached (NULL);
1058 parse_lrc (ParserState * state, const gchar * line)
1067 if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1068 sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1071 start = strchr (line, ']');
1072 if (start - line == 9)
1077 state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1078 + gst_util_uint64_scale (s, GST_SECOND, 1)
1079 + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1080 state->duration = GST_CLOCK_TIME_NONE;
1082 return g_strdup (start + 1);
1085 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1086 * element. This format is similar to Subrip, the biggest differences
1087 * are that there can be cue settings detailing how to display the cue
1088 * text and more markup tags are allowed.
1089 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1092 parse_webvtt (ParserState * state, const gchar * line)
1094 /* Cue IDs are optional in WebVTT, but not in subrip,
1095 * so when in state 0 (cue ID), also check if we're
1096 * already at the start --> end time marker */
1097 if (state->state == 0 || state->state == 1) {
1098 GstClockTime ts_start, ts_end;
1100 gchar *cue_settings = NULL;
1102 /* looking for start_time --> end_time */
1103 if ((end_time = strstr (line, " --> ")) &&
1104 parse_subrip_time (line, &ts_start) &&
1105 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1106 state->start_time <= ts_end) {
1108 state->start_time = ts_start;
1109 state->duration = ts_end - ts_start;
1110 cue_settings = strstr (end_time + strlen (" --> "), " ");
1112 GST_DEBUG ("error parsing subrip time line '%s'", line);
1116 state->text_position = 0;
1117 state->text_size = 0;
1118 state->line_position = 0;
1119 state->line_number = 0;
1122 parse_webvtt_cue_settings (state, cue_settings + 1);
1124 g_free (state->vertical);
1125 state->vertical = g_strdup ("");
1126 g_free (state->alignment);
1127 state->alignment = g_strdup ("");
1132 return parse_subrip (state, line);
1136 unescape_newlines_br (gchar * read)
1138 gchar *write = read;
1140 /* Replace all occurrences of '[br]' with a newline as version 2
1141 * of the subviewer format uses this for newlines */
1143 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1147 if (strncmp (read, "[br]", 4) == 0) {
1161 parse_subviewer (ParserState * state, const gchar * line)
1163 guint h1, m1, s1, ms1;
1164 guint h2, m2, s2, ms2;
1167 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1168 * For examples see the unit test or
1169 * http://www.doom9.org/index.html?/sub.htm */
1171 switch (state->state) {
1173 /* looking for start_time,end_time */
1174 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1175 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1178 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1181 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1182 ms2 * GST_MSECOND - state->start_time;
1187 /* No need to parse that text if it's out of segment */
1188 guint64 clip_start = 0, clip_stop = 0;
1189 gboolean in_seg = FALSE;
1191 /* Check our segment start/stop */
1192 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1193 state->start_time, state->start_time + state->duration,
1194 &clip_start, &clip_stop);
1197 state->start_time = clip_start;
1198 state->duration = clip_stop - clip_start;
1204 /* looking for subtitle text; empty line ends this subtitle entry */
1205 if (state->buf->len)
1206 g_string_append_c (state->buf, '\n');
1207 g_string_append (state->buf, line);
1208 if (strlen (line) == 0) {
1209 ret = g_strdup (state->buf->str);
1210 unescape_newlines_br (ret);
1211 strip_trailing_newlines (ret);
1212 g_string_truncate (state->buf, 0);
1218 g_assert_not_reached ();
1224 parse_mpsub (ParserState * state, const gchar * line)
1229 switch (state->state) {
1231 /* looking for two floats (offset, duration) */
1232 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1234 state->start_time += state->duration + GST_SECOND * t1;
1235 state->duration = GST_SECOND * t2;
1239 { /* No need to parse that text if it's out of segment */
1240 guint64 clip_start = 0, clip_stop = 0;
1241 gboolean in_seg = FALSE;
1243 /* Check our segment start/stop */
1244 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1245 state->start_time, state->start_time + state->duration,
1246 &clip_start, &clip_stop);
1249 state->start_time = clip_start;
1250 state->duration = clip_stop - clip_start;
1256 /* looking for subtitle text; empty line ends this
1258 if (state->buf->len)
1259 g_string_append_c (state->buf, '\n');
1260 g_string_append (state->buf, line);
1261 if (strlen (line) == 0) {
1262 ret = g_strdup (state->buf->str);
1263 g_string_truncate (state->buf, 0);
1269 g_assert_not_reached ();
1274 static const gchar *
1275 dks_skip_timestamp (const gchar * line)
1277 while (*line && *line != ']')
1285 parse_dks (ParserState * state, const gchar * line)
1289 switch (state->state) {
1291 /* Looking for the start time and text */
1292 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1294 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1295 text = dks_skip_timestamp (line);
1298 g_string_append (state->buf, text);
1304 guint64 clip_start = 0, clip_stop = 0;
1308 /* Looking for the end time */
1309 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1311 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1314 GST_WARNING ("Failed to parse subtitle end time");
1318 /* Check if this subtitle is out of the current segment */
1319 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1320 state->start_time, state->start_time + state->duration,
1321 &clip_start, &clip_stop);
1327 state->start_time = clip_start;
1328 state->duration = clip_stop - clip_start;
1330 ret = g_strdup (state->buf->str);
1331 g_string_truncate (state->buf, 0);
1332 unescape_newlines_br (ret);
1336 g_assert_not_reached ();
1342 parser_state_init (ParserState * state)
1344 GST_DEBUG ("initialising parser");
1347 g_string_truncate (state->buf, 0);
1349 state->buf = g_string_new (NULL);
1352 state->start_time = 0;
1353 state->duration = 0;
1354 state->max_duration = 0; /* no limit */
1356 state->segment = NULL;
1360 parser_state_dispose (GstSubParse * self, ParserState * state)
1363 g_string_free (state->buf, TRUE);
1367 g_free (state->vertical);
1368 state->vertical = NULL;
1369 g_free (state->alignment);
1370 state->alignment = NULL;
1372 if (state->user_data) {
1373 switch (self->parser_type) {
1374 case GST_SUB_PARSE_FORMAT_QTTEXT:
1375 qttext_context_deinit (state);
1377 case GST_SUB_PARSE_FORMAT_SAMI:
1378 sami_context_deinit (state);
1384 state->allowed_tags = NULL;
1390 gst_sub_parse_format_autodetect (GstSubParse * self)
1393 GstSubParseFormat format;
1395 if (strlen (self->textbuf->str) < 6) {
1396 GST_DEBUG ("File too small to be a subtitles file");
1400 data = g_strndup (self->textbuf->str, 35);
1401 format = gst_sub_parse_data_format_autodetect (data);
1404 self->parser_type = format;
1405 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1406 parser_state_init (&self->state);
1407 self->state.allowed_tags = NULL;
1410 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1411 self->parse_line = parse_mdvdsub;
1412 return gst_caps_new_simple ("text/x-raw",
1413 "format", G_TYPE_STRING, "pango-markup", NULL);
1414 case GST_SUB_PARSE_FORMAT_SUBRIP:
1415 self->state.allowed_tags = (gpointer) allowed_srt_tags;
1416 self->state.allows_tag_attributes = FALSE;
1417 self->parse_line = parse_subrip;
1418 return gst_caps_new_simple ("text/x-raw",
1419 "format", G_TYPE_STRING, "pango-markup", NULL);
1420 case GST_SUB_PARSE_FORMAT_MPSUB:
1421 self->parse_line = parse_mpsub;
1422 return gst_caps_new_simple ("text/x-raw",
1423 "format", G_TYPE_STRING, "utf8", NULL);
1424 case GST_SUB_PARSE_FORMAT_SAMI:
1425 self->parse_line = parse_sami;
1426 sami_context_init (&self->state);
1427 return gst_caps_new_simple ("text/x-raw",
1428 "format", G_TYPE_STRING, "pango-markup", NULL);
1429 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1430 self->parse_line = parse_tmplayer;
1431 self->state.max_duration = 5 * GST_SECOND;
1432 return gst_caps_new_simple ("text/x-raw",
1433 "format", G_TYPE_STRING, "utf8", NULL);
1434 case GST_SUB_PARSE_FORMAT_MPL2:
1435 self->parse_line = parse_mpl2;
1436 return gst_caps_new_simple ("text/x-raw",
1437 "format", G_TYPE_STRING, "pango-markup", NULL);
1438 case GST_SUB_PARSE_FORMAT_DKS:
1439 self->parse_line = parse_dks;
1440 return gst_caps_new_simple ("text/x-raw",
1441 "format", G_TYPE_STRING, "utf8", NULL);
1442 case GST_SUB_PARSE_FORMAT_VTT:
1443 self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1444 self->state.allows_tag_attributes = TRUE;
1445 self->parse_line = parse_webvtt;
1446 return gst_caps_new_simple ("text/x-raw",
1447 "format", G_TYPE_STRING, "pango-markup", NULL);
1448 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1449 self->parse_line = parse_subviewer;
1450 return gst_caps_new_simple ("text/x-raw",
1451 "format", G_TYPE_STRING, "utf8", NULL);
1452 case GST_SUB_PARSE_FORMAT_QTTEXT:
1453 self->parse_line = parse_qttext;
1454 qttext_context_init (&self->state);
1455 return gst_caps_new_simple ("text/x-raw",
1456 "format", G_TYPE_STRING, "pango-markup", NULL);
1457 case GST_SUB_PARSE_FORMAT_LRC:
1458 self->parse_line = parse_lrc;
1459 return gst_caps_new_simple ("text/x-raw",
1460 "format", G_TYPE_STRING, "utf8", NULL);
1461 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1463 GST_DEBUG ("no subtitle format detected");
1464 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1465 ("The input is not a valid/supported subtitle file"), (NULL));
1471 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1475 gchar *input = NULL;
1479 discont = GST_BUFFER_IS_DISCONT (buf);
1481 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1482 GST_BUFFER_OFFSET (buf) != self->offset) {
1483 self->offset = GST_BUFFER_OFFSET (buf);
1488 GST_INFO ("discontinuity");
1489 /* flush the parser state */
1490 parser_state_init (&self->state);
1491 g_string_truncate (self->textbuf, 0);
1492 gst_adapter_clear (self->adapter);
1493 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1494 sami_context_reset (&self->state);
1495 /* we could set a flag to make sure that the next buffer we push out also
1496 * has the DISCONT flag set, but there's no point really given that it's
1497 * subtitles which are discontinuous by nature. */
1500 self->offset += gst_buffer_get_size (buf);
1502 gst_adapter_push (self->adapter, buf);
1504 avail = gst_adapter_available (self->adapter);
1505 data = gst_adapter_map (self->adapter, avail);
1506 input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1508 if (input && consumed > 0) {
1509 self->textbuf = g_string_append (self->textbuf, input);
1510 gst_adapter_unmap (self->adapter);
1511 gst_adapter_flush (self->adapter, consumed);
1513 gst_adapter_unmap (self->adapter);
1521 xml_text (GMarkupParseContext * context,
1522 const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1524 gchar **accum = (gchar **) user_data;
1528 concat = g_strconcat (*accum, text, NULL);
1532 *accum = g_strdup (text);
1537 strip_pango_markup (gchar * markup, GError ** error)
1539 GMarkupParser parser = { 0, };
1540 GMarkupParseContext *context;
1541 gchar *accum = NULL;
1543 parser.text = xml_text;
1544 context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1546 g_markup_parse_context_parse (context, "<root>", 6, NULL);
1547 g_markup_parse_context_parse (context, markup, strlen (markup), error);
1548 g_markup_parse_context_parse (context, "</root>", 7, NULL);
1552 g_markup_parse_context_end_parse (context, error);
1557 g_markup_parse_context_free (context);
1567 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1570 gboolean ret = FALSE;
1571 const GstStructure *s1, *s2;
1573 caps = gst_pad_get_allowed_caps (self->srcpad);
1575 s1 = gst_caps_get_structure (preferred, 0);
1577 if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1578 GstCaps *intersected = gst_caps_intersect (caps, preferred);
1579 gst_caps_unref (caps);
1583 caps = gst_caps_fixate (caps);
1585 if (gst_caps_is_empty (caps)) {
1589 s2 = gst_caps_get_structure (caps, 0);
1591 self->strip_pango_markup =
1592 !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1593 && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1595 if (self->strip_pango_markup) {
1596 GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1599 ret = gst_pad_set_caps (self->srcpad, caps);
1602 gst_caps_unref (caps);
1606 static GstFlowReturn
1607 check_initial_events (GstSubParse * self)
1609 gboolean need_tags = FALSE;
1611 /* make sure we know the format */
1612 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1615 if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1616 return GST_FLOW_NOT_NEGOTIATED;
1619 if (!gst_sub_parse_negotiate (self, preferred)) {
1620 gst_caps_unref (preferred);
1621 return GST_FLOW_NOT_NEGOTIATED;
1624 gst_caps_unref (preferred);
1629 /* Push newsegment if needed */
1630 if (self->need_segment) {
1631 GstEvent *segment_event = gst_event_new_segment (&self->segment);
1632 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1635 gst_event_set_seqnum (segment_event, self->segment_seqnum);
1636 gst_pad_push_event (self->srcpad, segment_event);
1637 self->need_segment = FALSE;
1642 if (self->subtitle_codec != NULL) {
1645 tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1647 gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1654 static GstFlowReturn
1655 handle_buffer (GstSubParse * self, GstBuffer * buf)
1657 GstFlowReturn ret = GST_FLOW_OK;
1658 gchar *line, *subtitle;
1660 GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT, buf);
1662 if (self->first_buffer) {
1665 gst_buffer_map (buf, &map, GST_MAP_READ);
1666 self->detected_encoding =
1667 gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1668 gst_buffer_unmap (buf, &map);
1669 self->first_buffer = FALSE;
1670 self->state.fps_n = self->fps_n;
1671 self->state.fps_d = self->fps_d;
1674 feed_textbuf (self, buf);
1676 ret = check_initial_events (self);
1677 if (ret != GST_FLOW_OK)
1680 while (!self->flushing && (line = get_next_line (self))) {
1683 /* Set segment on our parser state machine */
1684 self->state.segment = &self->segment;
1685 /* Now parse the line, out of segment lines will just return NULL */
1686 GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1688 subtitle = self->parse_line (&self->state, line + offset);
1694 if (self->strip_pango_markup) {
1695 GError *error = NULL;
1698 if ((stripped = strip_pango_markup (subtitle, &error))) {
1700 subtitle = stripped;
1702 GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1707 subtitle_len = strlen (subtitle);
1709 /* +1 for terminating NUL character */
1710 buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1712 /* copy terminating NUL character as well */
1713 gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1714 gst_buffer_set_size (buf, subtitle_len);
1716 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1717 GST_BUFFER_DURATION (buf) = self->state.duration;
1719 /* in some cases (e.g. tmplayer) we can only determine the duration
1720 * of a text chunk from the timestamp of the next text chunk; in those
1721 * cases, we probably want to limit the duration to something
1722 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1723 * just because nothing else is being said during that time */
1724 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1725 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1726 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1729 self->segment.position = self->state.start_time;
1731 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1732 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1733 GST_TIME_ARGS (self->state.duration));
1735 g_free (self->state.vertical);
1736 self->state.vertical = NULL;
1737 g_free (self->state.alignment);
1738 self->state.alignment = NULL;
1740 ret = gst_pad_push (self->srcpad, buf);
1742 /* move this forward (the tmplayer parser needs this) */
1743 if (self->state.duration != GST_CLOCK_TIME_NONE)
1744 self->state.start_time += self->state.duration;
1749 if (ret != GST_FLOW_OK) {
1750 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1759 static GstFlowReturn
1760 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1765 self = GST_SUBPARSE (parent);
1767 ret = handle_buffer (self, buf);
1773 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1775 GstSubParse *self = GST_SUBPARSE (parent);
1776 gboolean ret = FALSE;
1778 GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
1780 switch (GST_EVENT_TYPE (event)) {
1781 case GST_EVENT_STREAM_GROUP_DONE:
1782 case GST_EVENT_EOS:{
1783 /* Make sure the last subrip chunk is pushed out even
1784 * if the file does not have an empty line at the end */
1785 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1786 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1787 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1788 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
1789 self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
1790 gchar term_chars[] = { '\n', '\n', '\0' };
1791 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1793 GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
1794 GST_EVENT_TYPE_NAME (event));
1796 gst_buffer_fill (buf, 0, term_chars, 3);
1797 gst_buffer_set_size (buf, 2);
1799 GST_BUFFER_OFFSET (buf) = self->offset;
1800 gst_sub_parse_chain (pad, parent, buf);
1802 ret = gst_pad_event_default (pad, parent, event);
1805 case GST_EVENT_SEGMENT:
1807 const GstSegment *s;
1808 gst_event_parse_segment (event, &s);
1809 if (s->format == GST_FORMAT_TIME)
1810 gst_event_copy_segment (event, &self->segment);
1811 GST_DEBUG_OBJECT (self, "newsegment (%s)",
1812 gst_format_get_name (self->segment.format));
1813 self->segment_seqnum = gst_event_get_seqnum (event);
1815 /* if not time format, we'll either start with a 0 timestamp anyway or
1816 * it's following a seek in which case we'll have saved the requested
1817 * seek segment and don't want to overwrite it (remember that on a seek
1818 * we always just seek back to the start in BYTES format and just throw
1819 * away all text that's before the requested position; if the subtitles
1820 * come from an upstream demuxer, it won't be able to handle our BYTES
1821 * seek request and instead send us a newsegment from the seek request
1822 * it received via its video pads instead, so all is fine then too) */
1824 gst_event_unref (event);
1825 /* in either case, let's not simply discard this event;
1826 * trigger sending of the saved requested seek segment
1827 * or the one taken here from upstream */
1828 self->need_segment = TRUE;
1833 ret = check_initial_events (self);
1834 if (ret == GST_FLOW_OK) {
1835 ret = gst_pad_event_default (pad, parent, event);
1837 gst_event_unref (event);
1841 case GST_EVENT_FLUSH_START:
1843 self->flushing = TRUE;
1845 ret = gst_pad_event_default (pad, parent, event);
1848 case GST_EVENT_FLUSH_STOP:
1850 self->flushing = FALSE;
1852 ret = gst_pad_event_default (pad, parent, event);
1856 ret = gst_pad_event_default (pad, parent, event);
1864 static GstStateChangeReturn
1865 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1867 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1868 GstSubParse *self = GST_SUBPARSE (element);
1870 switch (transition) {
1871 case GST_STATE_CHANGE_READY_TO_PAUSED:
1872 /* format detection will init the parser state */
1874 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1875 self->strip_pango_markup = FALSE;
1876 self->valid_utf8 = TRUE;
1877 self->first_buffer = TRUE;
1878 g_free (self->detected_encoding);
1879 self->detected_encoding = NULL;
1880 g_string_truncate (self->textbuf, 0);
1881 gst_adapter_clear (self->adapter);
1887 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1888 if (ret == GST_STATE_CHANGE_FAILURE)
1891 switch (transition) {
1892 case GST_STATE_CHANGE_PAUSED_TO_READY:
1893 parser_state_dispose (self, &self->state);
1894 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;