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->need_segment = TRUE;
189 subparse->encoding = g_strdup (DEFAULT_ENCODING);
190 subparse->detected_encoding = NULL;
191 subparse->adapter = gst_adapter_new ();
193 subparse->fps_n = 24000;
194 subparse->fps_d = 1001;
198 * Source pad functions.
202 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
204 GstSubParse *self = GST_SUBPARSE (parent);
205 gboolean ret = FALSE;
207 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
209 switch (GST_QUERY_TYPE (query)) {
210 case GST_QUERY_POSITION:{
213 gst_query_parse_position (query, &fmt, NULL);
214 if (fmt != GST_FORMAT_TIME) {
215 ret = gst_pad_peer_query (self->sinkpad, query);
218 gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
222 case GST_QUERY_SEEKING:
225 gboolean seekable = FALSE;
229 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
230 if (fmt == GST_FORMAT_TIME) {
231 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
233 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
235 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
236 gst_query_unref (peerquery);
239 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
243 ret = gst_pad_query_default (pad, parent, query);
251 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
253 GstSubParse *self = GST_SUBPARSE (parent);
254 gboolean ret = FALSE;
256 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
258 switch (GST_EVENT_TYPE (event)) {
263 GstSeekType start_type, stop_type;
268 gst_event_parse_seek (event, &rate, &format, &flags,
269 &start_type, &start, &stop_type, &stop);
271 if (format != GST_FORMAT_TIME) {
272 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
273 gst_event_unref (event);
277 /* Convert that seek to a seeking in bytes at position 0,
278 FIXME: could use an index */
279 ret = gst_pad_push_event (self->sinkpad,
280 gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
281 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
284 /* Apply the seek to our segment */
285 gst_segment_do_seek (&self->segment, rate, format, flags,
286 start_type, start, stop_type, stop, &update);
288 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
291 /* will mark need_segment when receiving segment from upstream,
292 * after FLUSH and all that has happened,
293 * rather than racing with chain */
295 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
298 gst_event_unref (event);
302 ret = gst_pad_event_default (pad, parent, event);
311 gst_sub_parse_set_property (GObject * object, guint prop_id,
312 const GValue * value, GParamSpec * pspec)
314 GstSubParse *subparse = GST_SUBPARSE (object);
316 GST_OBJECT_LOCK (subparse);
319 g_free (subparse->encoding);
320 subparse->encoding = g_value_dup_string (value);
321 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
322 GST_STR_NULL (subparse->encoding));
326 subparse->fps_n = gst_value_get_fraction_numerator (value);
327 subparse->fps_d = gst_value_get_fraction_denominator (value);
328 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
331 if (!subparse->state.have_internal_fps) {
332 subparse->state.fps_n = subparse->fps_n;
333 subparse->state.fps_d = subparse->fps_d;
338 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
341 GST_OBJECT_UNLOCK (subparse);
345 gst_sub_parse_get_property (GObject * object, guint prop_id,
346 GValue * value, GParamSpec * pspec)
348 GstSubParse *subparse = GST_SUBPARSE (object);
350 GST_OBJECT_LOCK (subparse);
353 g_value_set_string (value, subparse->encoding);
356 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
359 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
362 GST_OBJECT_UNLOCK (subparse);
366 gst_sub_parse_get_format_description (GstSubParseFormat format)
369 case GST_SUB_PARSE_FORMAT_MDVDSUB:
371 case GST_SUB_PARSE_FORMAT_SUBRIP:
373 case GST_SUB_PARSE_FORMAT_MPSUB:
375 case GST_SUB_PARSE_FORMAT_SAMI:
377 case GST_SUB_PARSE_FORMAT_TMPLAYER:
379 case GST_SUB_PARSE_FORMAT_MPL2:
381 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
383 case GST_SUB_PARSE_FORMAT_DKS:
385 case GST_SUB_PARSE_FORMAT_VTT:
387 case GST_SUB_PARSE_FORMAT_QTTEXT:
389 case GST_SUB_PARSE_FORMAT_LRC:
392 case GST_SUB_PARSE_FORMAT_UNKNOWN:
403 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
406 const gchar *encoding;
412 /* First try any detected encoding */
413 if (self->detected_encoding) {
415 gst_sub_parse_gst_convert_to_utf8 (str, len, self->detected_encoding,
421 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
422 self->detected_encoding, err->message);
423 g_free (self->detected_encoding);
424 self->detected_encoding = NULL;
425 g_clear_error (&err);
428 /* Otherwise check if it's UTF8 */
429 if (self->valid_utf8) {
430 if (g_utf8_validate (str, len, NULL)) {
431 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
433 return g_strndup (str, len);
435 GST_INFO_OBJECT (self, "invalid UTF-8!");
436 self->valid_utf8 = FALSE;
439 /* Else try fallback */
440 encoding = self->encoding;
441 if (encoding == NULL || *encoding == '\0') {
442 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
444 if (encoding == NULL || *encoding == '\0') {
445 /* if local encoding is UTF-8 and no encoding specified
446 * via the environment variable, assume ISO-8859-15 */
447 if (g_get_charset (&encoding)) {
448 encoding = "ISO-8859-15";
452 ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
455 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
456 encoding, err->message);
457 g_clear_error (&err);
459 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
461 gst_sub_parse_gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed,
465 GST_LOG_OBJECT (self,
466 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
467 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
473 get_next_line (GstSubParse * self)
476 const char *line_end;
478 gboolean have_r = FALSE;
480 line_end = strchr (self->textbuf->str, '\n');
483 /* end-of-line not found; return for more data */
487 /* get rid of '\r' */
488 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
493 line_len = line_end - self->textbuf->str;
494 line = g_strndup (self->textbuf->str, line_len);
495 self->textbuf = g_string_erase (self->textbuf, 0,
496 line_len + (have_r ? 2 : 1));
501 parse_mdvdsub (ParserState * state, const gchar * line)
503 const gchar *line_split;
505 guint start_frame, end_frame;
506 guint64 clip_start = 0, clip_stop = 0;
507 gboolean in_seg = FALSE;
511 /* style variables */
517 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
518 GST_WARNING ("Parsing of the following line, assumed to be in microdvd .sub"
519 " format, failed:\n%s", line);
523 /* skip the {%u}{%u} part */
524 line = strchr (line, '}') + 1;
525 line = strchr (line, '}') + 1;
527 /* see if there's a first line with a framerate */
528 if (start_frame == 1 && end_frame == 1) {
529 gchar *rest, *end = NULL;
531 rest = g_strdup (line);
532 g_strdelimit (rest, ",", '.');
533 fps = g_ascii_strtod (rest, &end);
535 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
536 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
544 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
547 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
550 /* Check our segment start/stop */
551 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
552 state->start_time, state->start_time + state->duration, &clip_start,
555 /* No need to parse that text if it's out of segment */
557 state->start_time = clip_start;
558 state->duration = clip_stop - clip_start;
563 markup = g_string_new (NULL);
568 /* parse style markup */
569 if (strncmp (line, "{y:i}", 5) == 0) {
571 line = strchr (line, '}') + 1;
573 if (strncmp (line, "{y:b}", 5) == 0) {
575 line = strchr (line, '}') + 1;
577 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
578 line = strchr (line, '}') + 1;
580 /* forward slashes at beginning/end signify italics too */
581 if (g_str_has_prefix (line, "/")) {
585 if ((line_split = strchr (line, '|')))
586 line_chunk = g_markup_escape_text (line, line_split - line);
588 line_chunk = g_markup_escape_text (line, strlen (line));
590 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
591 * always at the end of a line or can they span multiple lines?) */
592 if (g_str_has_suffix (line_chunk, "/")) {
593 line_chunk[strlen (line_chunk) - 1] = '\0';
596 markup = g_string_append (markup, "<span");
598 g_string_append (markup, " style=\"italic\"");
600 g_string_append (markup, " weight=\"bold\"");
602 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
603 g_string_append_printf (markup, ">%s</span>", line_chunk);
606 g_string_append (markup, "\n");
607 line = line_split + 1;
613 g_string_free (markup, FALSE);
614 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
615 state->start_time / (double) GST_SECOND,
616 state->duration / (double) GST_SECOND, ret);
621 strip_trailing_newlines (gchar * txt)
627 while (len > 1 && txt[len - 1] == '\n') {
634 /* we want to escape text in general, but retain basic markup like
635 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
636 * just unescape a white list of allowed markups again after
637 * escaping everything (the text between these simple markers isn't
638 * necessarily escaped, so it seems best to do it like this) */
640 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
641 gboolean allows_tag_attributes)
645 gchar *allowed_tags_pattern, *search_pattern;
646 const gchar *replace_pattern;
648 /* No processing needed if no escaped tag marker found in the string. */
649 if (strstr (txt, "<") == NULL)
652 /* Build a list of alternates for our regexp.
653 * FIXME: Could be built once and stored */
654 allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
655 /* Look for starting/ending escaped tags with optional attributes. */
656 search_pattern = g_strdup_printf ("<(/)?\\ *(%s)(%s)>",
657 allowed_tags_pattern, ATTRIBUTE_REGEX);
658 /* And unescape appropriately */
659 if (allows_tag_attributes) {
660 replace_pattern = "<\\1\\2\\3>";
662 replace_pattern = "<\\1\\2>";
665 tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
666 res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
667 replace_pattern, 0, NULL);
669 /* res will always be shorter than the input or identical, so this
674 g_free (search_pattern);
675 g_free (allowed_tags_pattern);
677 g_regex_unref (tag_regex);
682 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
686 tag = start + strlen ("<");
690 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
695 GST_LOG ("removing unhandled tag '%s'", start);
697 memmove (start, stop, strlen (stop) + 1);
701 /* remove tags we haven't explicitly allowed earlier on, like font tags
704 subrip_remove_unhandled_tags (gchar * txt)
708 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
709 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
710 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
716 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
717 * take a simple approach. This code assumes the input has been
718 * escaped and subrip_unescape_formatting() has then been run over the
719 * input! This function adds missing closing markup tags and removes
720 * broken closing tags for tags that have never been opened. */
722 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
724 gchar *cur, *next_tag;
725 GPtrArray *open_tags = NULL;
726 guint num_open_tags = 0;
727 const gchar *iter_tag;
733 GMatchInfo *match_info;
734 gchar **allowed_tags = (gchar **) allowed_tags_ptr;
736 g_assert (*p_txt != NULL);
738 open_tags = g_ptr_array_new_with_free_func (g_free);
740 while (*cur != '\0') {
741 next_tag = strchr (cur, '<');
742 if (next_tag == NULL)
746 while (index < g_strv_length (allowed_tags)) {
747 iter_tag = allowed_tags[index];
748 /* Look for a white listed tag */
749 cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
750 tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
751 (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
753 if (g_match_info_matches (match_info)) {
754 gint start_pos, end_pos;
755 gchar *word = g_match_info_fetch (match_info, 0);
756 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
757 if (start_pos == 0) {
758 offset = strlen (word);
762 g_match_info_free (match_info);
763 g_regex_unref (tag_regex);
767 /* OK we found a tag, let's keep track of it */
768 g_ptr_array_add (open_tags, g_ascii_strdown (iter_tag, -1));
780 if (*next_tag == '<' && *(next_tag + 1) == '/') {
781 end_tag = strchr (cur, '>');
783 const gchar *last = NULL;
784 if (num_open_tags > 0)
785 last = g_ptr_array_index (open_tags, num_open_tags - 1);
786 if (num_open_tags == 0
787 || g_ascii_strncasecmp (end_tag - 1, last, strlen (last))) {
788 GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
789 /* Move everything after the tag end, including closing \0 */
790 memmove (next_tag, end_tag + 1, strlen (end_tag));
795 g_ptr_array_remove_index (open_tags, num_open_tags);
803 if (num_open_tags > 0) {
806 s = g_string_new (*p_txt);
807 while (num_open_tags > 0) {
808 GST_LOG ("adding missing closing tag '%s'",
809 (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
810 g_string_append_c (s, '<');
811 g_string_append_c (s, '/');
812 g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
813 g_string_append_c (s, '>');
817 *p_txt = g_string_free (s, FALSE);
819 g_ptr_array_free (open_tags, TRUE);
823 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
825 gchar s[128] = { '\0', };
827 guint hour, min, sec, msec, len;
829 while (*ts_string == ' ')
832 g_strlcpy (s, ts_string, sizeof (s));
833 if ((end = strstr (s, "-->")))
837 /* ms may be in these formats:
838 * hh:mm:ss,500 = 500ms
841 * hh:mm:ss, 50 = 50ms
843 * and the same with . instead of ,.
844 * sscanf() doesn't differentiate between ' 5' and '5' so munge
845 * the white spaces within the timestamp to '0' (I'm sure there's a
846 * way to make sscanf() do this for us, but how?)
848 g_strdelimit (s, " ", '0');
849 g_strdelimit (s, ".", ',');
851 /* make sure we have exactly three digits after he comma */
854 /* If there isn't a ',' the timestamp is broken */
855 /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
856 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
866 g_strlcat (&p[len], "0", 2);
870 GST_LOG ("parsing timestamp '%s'", s);
871 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
872 /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
874 * The hours component is optional with webVTT, for example
875 * mm:ss,500 is a valid webVTT timestamp. When not present,
880 if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
881 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
886 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
890 /* cue settings are part of the WebVTT specification. They are
891 * declared after the time interval in the first line of the
892 * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
893 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
896 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
898 gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
900 gint16 text_position, text_size;
901 gint16 line_position;
902 gboolean vertical_found = FALSE;
903 gboolean alignment_found = FALSE;
905 while (i < g_strv_length (splitted_settings)) {
906 gboolean valid_tag = FALSE;
907 switch (splitted_settings[i][0]) {
909 if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
910 &text_position) > 0) {
911 state->text_position = (guint8) text_position;
916 if (strlen (splitted_settings[i]) > 2) {
917 vertical_found = TRUE;
918 g_free (state->vertical);
919 state->vertical = g_strdup (splitted_settings[i] + 2);
924 if (g_str_has_suffix (splitted_settings[i], "%")) {
925 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
926 &line_position) > 0) {
927 state->line_position = line_position;
931 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
932 &line_position) > 0) {
933 state->line_number = line_position;
939 if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
941 state->text_size = (guint8) text_size;
946 if (strlen (splitted_settings[i]) > 2) {
947 g_free (state->alignment);
948 state->alignment = g_strdup (splitted_settings[i] + 2);
949 alignment_found = TRUE;
957 GST_LOG ("Invalid or unrecognised setting found: %s",
958 splitted_settings[i]);
962 g_strfreev (splitted_settings);
963 if (!vertical_found) {
964 g_free (state->vertical);
965 state->vertical = g_strdup ("");
967 if (!alignment_found) {
968 g_free (state->alignment);
969 state->alignment = g_strdup ("");
974 parse_subrip (ParserState * state, const gchar * line)
978 switch (state->state) {
983 /* looking for a single integer as a Cue ID, but we
984 * don't actually use it */
986 id = g_ascii_strtoull (line, &endptr, 10);
987 if (id == G_MAXUINT64 && errno == ERANGE)
989 else if (id == 0 && errno == EINVAL)
991 else if (endptr != line && *endptr == '\0')
997 GstClockTime ts_start, ts_end;
1000 /* looking for start_time --> end_time */
1001 if ((end_time = strstr (line, " --> ")) &&
1002 parse_subrip_time (line, &ts_start) &&
1003 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1004 state->start_time <= ts_end) {
1006 state->start_time = ts_start;
1007 state->duration = ts_end - ts_start;
1009 GST_DEBUG ("error parsing subrip time line '%s'", line);
1016 /* No need to parse that text if it's out of segment */
1017 guint64 clip_start = 0, clip_stop = 0;
1018 gboolean in_seg = FALSE;
1020 /* Check our segment start/stop */
1021 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1022 state->start_time, state->start_time + state->duration,
1023 &clip_start, &clip_stop);
1026 state->start_time = clip_start;
1027 state->duration = clip_stop - clip_start;
1033 /* looking for subtitle text; empty line ends this subtitle entry */
1034 if (state->buf->len)
1035 g_string_append_c (state->buf, '\n');
1036 g_string_append (state->buf, line);
1037 if (strlen (line) == 0) {
1038 ret = g_markup_escape_text (state->buf->str, state->buf->len);
1039 g_string_truncate (state->buf, 0);
1041 subrip_unescape_formatting (ret, state->allowed_tags,
1042 state->allows_tag_attributes);
1043 subrip_remove_unhandled_tags (ret);
1044 strip_trailing_newlines (ret);
1045 subrip_fix_up_markup (&ret, state->allowed_tags);
1050 g_return_val_if_reached (NULL);
1055 parse_lrc (ParserState * state, const gchar * line)
1064 if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1065 sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1068 start = strchr (line, ']');
1069 if (start - line == 9)
1074 state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1075 + gst_util_uint64_scale (s, GST_SECOND, 1)
1076 + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1077 state->duration = GST_CLOCK_TIME_NONE;
1079 return g_strdup (start + 1);
1082 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1083 * element. This format is similar to Subrip, the biggest differences
1084 * are that there can be cue settings detailing how to display the cue
1085 * text and more markup tags are allowed.
1086 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1089 parse_webvtt (ParserState * state, const gchar * line)
1091 /* Cue IDs are optional in WebVTT, but not in subrip,
1092 * so when in state 0 (cue ID), also check if we're
1093 * already at the start --> end time marker */
1094 if (state->state == 0 || state->state == 1) {
1095 GstClockTime ts_start, ts_end;
1097 gchar *cue_settings = NULL;
1099 /* looking for start_time --> end_time */
1100 if ((end_time = strstr (line, " --> ")) &&
1101 parse_subrip_time (line, &ts_start) &&
1102 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1103 state->start_time <= ts_end) {
1105 state->start_time = ts_start;
1106 state->duration = ts_end - ts_start;
1107 cue_settings = strstr (end_time + strlen (" --> "), " ");
1109 GST_DEBUG ("error parsing subrip time line '%s'", line);
1113 state->text_position = 0;
1114 state->text_size = 0;
1115 state->line_position = 0;
1116 state->line_number = 0;
1119 parse_webvtt_cue_settings (state, cue_settings + 1);
1121 g_free (state->vertical);
1122 state->vertical = g_strdup ("");
1123 g_free (state->alignment);
1124 state->alignment = g_strdup ("");
1129 return parse_subrip (state, line);
1133 unescape_newlines_br (gchar * read)
1135 gchar *write = read;
1137 /* Replace all occurrences of '[br]' with a newline as version 2
1138 * of the subviewer format uses this for newlines */
1140 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1144 if (strncmp (read, "[br]", 4) == 0) {
1158 parse_subviewer (ParserState * state, const gchar * line)
1160 guint h1, m1, s1, ms1;
1161 guint h2, m2, s2, ms2;
1164 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1165 * For examples see the unit test or
1166 * http://www.doom9.org/index.html?/sub.htm */
1168 switch (state->state) {
1170 /* looking for start_time,end_time */
1171 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1172 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1175 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1178 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1179 ms2 * GST_MSECOND - state->start_time;
1184 /* No need to parse that text if it's out of segment */
1185 guint64 clip_start = 0, clip_stop = 0;
1186 gboolean in_seg = FALSE;
1188 /* Check our segment start/stop */
1189 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1190 state->start_time, state->start_time + state->duration,
1191 &clip_start, &clip_stop);
1194 state->start_time = clip_start;
1195 state->duration = clip_stop - clip_start;
1201 /* looking for subtitle text; empty line ends this subtitle entry */
1202 if (state->buf->len)
1203 g_string_append_c (state->buf, '\n');
1204 g_string_append (state->buf, line);
1205 if (strlen (line) == 0) {
1206 ret = g_strdup (state->buf->str);
1207 unescape_newlines_br (ret);
1208 strip_trailing_newlines (ret);
1209 g_string_truncate (state->buf, 0);
1215 g_assert_not_reached ();
1221 parse_mpsub (ParserState * state, const gchar * line)
1226 switch (state->state) {
1228 /* looking for two floats (offset, duration) */
1229 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1231 state->start_time += state->duration + GST_SECOND * t1;
1232 state->duration = GST_SECOND * t2;
1236 { /* No need to parse that text if it's out of segment */
1237 guint64 clip_start = 0, clip_stop = 0;
1238 gboolean in_seg = FALSE;
1240 /* Check our segment start/stop */
1241 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1242 state->start_time, state->start_time + state->duration,
1243 &clip_start, &clip_stop);
1246 state->start_time = clip_start;
1247 state->duration = clip_stop - clip_start;
1253 /* looking for subtitle text; empty line ends this
1255 if (state->buf->len)
1256 g_string_append_c (state->buf, '\n');
1257 g_string_append (state->buf, line);
1258 if (strlen (line) == 0) {
1259 ret = g_strdup (state->buf->str);
1260 g_string_truncate (state->buf, 0);
1266 g_assert_not_reached ();
1271 static const gchar *
1272 dks_skip_timestamp (const gchar * line)
1274 while (*line && *line != ']')
1282 parse_dks (ParserState * state, const gchar * line)
1286 switch (state->state) {
1288 /* Looking for the start time and text */
1289 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1291 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1292 text = dks_skip_timestamp (line);
1295 g_string_append (state->buf, text);
1301 guint64 clip_start = 0, clip_stop = 0;
1305 /* Looking for the end time */
1306 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1308 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1311 GST_WARNING ("Failed to parse subtitle end time");
1315 /* Check if this subtitle is out of the current segment */
1316 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1317 state->start_time, state->start_time + state->duration,
1318 &clip_start, &clip_stop);
1324 state->start_time = clip_start;
1325 state->duration = clip_stop - clip_start;
1327 ret = g_strdup (state->buf->str);
1328 g_string_truncate (state->buf, 0);
1329 unescape_newlines_br (ret);
1333 g_assert_not_reached ();
1339 parser_state_init (ParserState * state)
1341 GST_DEBUG ("initialising parser");
1344 g_string_truncate (state->buf, 0);
1346 state->buf = g_string_new (NULL);
1349 state->start_time = 0;
1350 state->duration = 0;
1351 state->max_duration = 0; /* no limit */
1353 state->segment = NULL;
1357 parser_state_dispose (GstSubParse * self, ParserState * state)
1360 g_string_free (state->buf, TRUE);
1364 g_free (state->vertical);
1365 state->vertical = NULL;
1366 g_free (state->alignment);
1367 state->alignment = NULL;
1369 if (state->user_data) {
1370 switch (self->parser_type) {
1371 case GST_SUB_PARSE_FORMAT_QTTEXT:
1372 qttext_context_deinit (state);
1374 case GST_SUB_PARSE_FORMAT_SAMI:
1375 sami_context_deinit (state);
1381 state->allowed_tags = NULL;
1387 gst_sub_parse_format_autodetect (GstSubParse * self)
1390 GstSubParseFormat format;
1392 if (strlen (self->textbuf->str) < 6) {
1393 GST_DEBUG ("File too small to be a subtitles file");
1397 data = g_strndup (self->textbuf->str, 35);
1398 format = gst_sub_parse_data_format_autodetect (data);
1401 self->parser_type = format;
1402 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1403 parser_state_init (&self->state);
1404 self->state.allowed_tags = NULL;
1407 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1408 self->parse_line = parse_mdvdsub;
1409 return gst_caps_new_simple ("text/x-raw",
1410 "format", G_TYPE_STRING, "pango-markup", NULL);
1411 case GST_SUB_PARSE_FORMAT_SUBRIP:
1412 self->state.allowed_tags = (gpointer) allowed_srt_tags;
1413 self->state.allows_tag_attributes = FALSE;
1414 self->parse_line = parse_subrip;
1415 return gst_caps_new_simple ("text/x-raw",
1416 "format", G_TYPE_STRING, "pango-markup", NULL);
1417 case GST_SUB_PARSE_FORMAT_MPSUB:
1418 self->parse_line = parse_mpsub;
1419 return gst_caps_new_simple ("text/x-raw",
1420 "format", G_TYPE_STRING, "utf8", NULL);
1421 case GST_SUB_PARSE_FORMAT_SAMI:
1422 self->parse_line = parse_sami;
1423 sami_context_init (&self->state);
1424 return gst_caps_new_simple ("text/x-raw",
1425 "format", G_TYPE_STRING, "pango-markup", NULL);
1426 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1427 self->parse_line = parse_tmplayer;
1428 self->state.max_duration = 5 * GST_SECOND;
1429 return gst_caps_new_simple ("text/x-raw",
1430 "format", G_TYPE_STRING, "utf8", NULL);
1431 case GST_SUB_PARSE_FORMAT_MPL2:
1432 self->parse_line = parse_mpl2;
1433 return gst_caps_new_simple ("text/x-raw",
1434 "format", G_TYPE_STRING, "pango-markup", NULL);
1435 case GST_SUB_PARSE_FORMAT_DKS:
1436 self->parse_line = parse_dks;
1437 return gst_caps_new_simple ("text/x-raw",
1438 "format", G_TYPE_STRING, "utf8", NULL);
1439 case GST_SUB_PARSE_FORMAT_VTT:
1440 self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1441 self->state.allows_tag_attributes = TRUE;
1442 self->parse_line = parse_webvtt;
1443 return gst_caps_new_simple ("text/x-raw",
1444 "format", G_TYPE_STRING, "pango-markup", NULL);
1445 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1446 self->parse_line = parse_subviewer;
1447 return gst_caps_new_simple ("text/x-raw",
1448 "format", G_TYPE_STRING, "utf8", NULL);
1449 case GST_SUB_PARSE_FORMAT_QTTEXT:
1450 self->parse_line = parse_qttext;
1451 qttext_context_init (&self->state);
1452 return gst_caps_new_simple ("text/x-raw",
1453 "format", G_TYPE_STRING, "pango-markup", NULL);
1454 case GST_SUB_PARSE_FORMAT_LRC:
1455 self->parse_line = parse_lrc;
1456 return gst_caps_new_simple ("text/x-raw",
1457 "format", G_TYPE_STRING, "utf8", NULL);
1458 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1460 GST_DEBUG ("no subtitle format detected");
1461 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1462 ("The input is not a valid/supported subtitle file"), (NULL));
1468 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1472 gchar *input = NULL;
1476 discont = GST_BUFFER_IS_DISCONT (buf);
1478 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1479 GST_BUFFER_OFFSET (buf) != self->offset) {
1480 self->offset = GST_BUFFER_OFFSET (buf);
1485 GST_INFO ("discontinuity");
1486 /* flush the parser state */
1487 parser_state_init (&self->state);
1488 g_string_truncate (self->textbuf, 0);
1489 gst_adapter_clear (self->adapter);
1490 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1491 sami_context_reset (&self->state);
1492 /* we could set a flag to make sure that the next buffer we push out also
1493 * has the DISCONT flag set, but there's no point really given that it's
1494 * subtitles which are discontinuous by nature. */
1497 self->offset += gst_buffer_get_size (buf);
1499 gst_adapter_push (self->adapter, buf);
1501 avail = gst_adapter_available (self->adapter);
1502 data = gst_adapter_map (self->adapter, avail);
1503 input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1505 if (input && consumed > 0) {
1506 self->textbuf = g_string_append (self->textbuf, input);
1507 gst_adapter_unmap (self->adapter);
1508 gst_adapter_flush (self->adapter, consumed);
1510 gst_adapter_unmap (self->adapter);
1518 xml_text (GMarkupParseContext * context,
1519 const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1521 gchar **accum = (gchar **) user_data;
1525 concat = g_strconcat (*accum, text, NULL);
1529 *accum = g_strdup (text);
1534 strip_pango_markup (gchar * markup, GError ** error)
1536 GMarkupParser parser = { 0, };
1537 GMarkupParseContext *context;
1538 gchar *accum = NULL;
1540 parser.text = xml_text;
1541 context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1543 g_markup_parse_context_parse (context, "<root>", 6, NULL);
1544 g_markup_parse_context_parse (context, markup, strlen (markup), error);
1545 g_markup_parse_context_parse (context, "</root>", 7, NULL);
1549 g_markup_parse_context_end_parse (context, error);
1554 g_markup_parse_context_free (context);
1564 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1567 gboolean ret = FALSE;
1568 const GstStructure *s1, *s2;
1570 caps = gst_pad_get_allowed_caps (self->srcpad);
1572 s1 = gst_caps_get_structure (preferred, 0);
1574 if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1575 GstCaps *intersected = gst_caps_intersect (caps, preferred);
1576 gst_caps_unref (caps);
1580 caps = gst_caps_fixate (caps);
1582 if (gst_caps_is_empty (caps)) {
1586 s2 = gst_caps_get_structure (caps, 0);
1588 self->strip_pango_markup =
1589 !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1590 && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1592 if (self->strip_pango_markup) {
1593 GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1596 ret = gst_pad_set_caps (self->srcpad, caps);
1599 gst_caps_unref (caps);
1603 static GstFlowReturn
1604 check_initial_events (GstSubParse * self)
1606 gboolean need_tags = FALSE;
1608 /* make sure we know the format */
1609 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1612 if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1613 return GST_FLOW_NOT_NEGOTIATED;
1616 if (!gst_sub_parse_negotiate (self, preferred)) {
1617 gst_caps_unref (preferred);
1618 return GST_FLOW_NOT_NEGOTIATED;
1621 gst_caps_unref (preferred);
1626 /* Push newsegment if needed */
1627 if (self->need_segment) {
1628 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1631 gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1632 self->need_segment = FALSE;
1637 if (self->subtitle_codec != NULL) {
1640 tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1642 gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1649 static GstFlowReturn
1650 handle_buffer (GstSubParse * self, GstBuffer * buf)
1652 GstFlowReturn ret = GST_FLOW_OK;
1653 gchar *line, *subtitle;
1655 GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT, buf);
1657 if (self->first_buffer) {
1660 gst_buffer_map (buf, &map, GST_MAP_READ);
1661 self->detected_encoding =
1662 gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1663 gst_buffer_unmap (buf, &map);
1664 self->first_buffer = FALSE;
1665 self->state.fps_n = self->fps_n;
1666 self->state.fps_d = self->fps_d;
1669 feed_textbuf (self, buf);
1671 ret = check_initial_events (self);
1672 if (ret != GST_FLOW_OK)
1675 while (!self->flushing && (line = get_next_line (self))) {
1678 /* Set segment on our parser state machine */
1679 self->state.segment = &self->segment;
1680 /* Now parse the line, out of segment lines will just return NULL */
1681 GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1683 subtitle = self->parse_line (&self->state, line + offset);
1689 if (self->strip_pango_markup) {
1690 GError *error = NULL;
1693 if ((stripped = strip_pango_markup (subtitle, &error))) {
1695 subtitle = stripped;
1697 GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1702 subtitle_len = strlen (subtitle);
1704 /* +1 for terminating NUL character */
1705 buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1707 /* copy terminating NUL character as well */
1708 gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1709 gst_buffer_set_size (buf, subtitle_len);
1711 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1712 GST_BUFFER_DURATION (buf) = self->state.duration;
1714 /* in some cases (e.g. tmplayer) we can only determine the duration
1715 * of a text chunk from the timestamp of the next text chunk; in those
1716 * cases, we probably want to limit the duration to something
1717 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1718 * just because nothing else is being said during that time */
1719 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1720 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1721 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1724 self->segment.position = self->state.start_time;
1726 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1727 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1728 GST_TIME_ARGS (self->state.duration));
1730 g_free (self->state.vertical);
1731 self->state.vertical = NULL;
1732 g_free (self->state.alignment);
1733 self->state.alignment = NULL;
1735 ret = gst_pad_push (self->srcpad, buf);
1737 /* move this forward (the tmplayer parser needs this) */
1738 if (self->state.duration != GST_CLOCK_TIME_NONE)
1739 self->state.start_time += self->state.duration;
1744 if (ret != GST_FLOW_OK) {
1745 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1754 static GstFlowReturn
1755 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1760 self = GST_SUBPARSE (parent);
1762 ret = handle_buffer (self, buf);
1768 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1770 GstSubParse *self = GST_SUBPARSE (parent);
1771 gboolean ret = FALSE;
1773 GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
1775 switch (GST_EVENT_TYPE (event)) {
1776 case GST_EVENT_STREAM_GROUP_DONE:
1777 case GST_EVENT_EOS:{
1778 /* Make sure the last subrip chunk is pushed out even
1779 * if the file does not have an empty line at the end */
1780 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1781 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1782 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1783 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
1784 self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
1785 gchar term_chars[] = { '\n', '\n', '\0' };
1786 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1788 GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
1789 GST_EVENT_TYPE_NAME (event));
1791 gst_buffer_fill (buf, 0, term_chars, 3);
1792 gst_buffer_set_size (buf, 2);
1794 GST_BUFFER_OFFSET (buf) = self->offset;
1795 gst_sub_parse_chain (pad, parent, buf);
1797 ret = gst_pad_event_default (pad, parent, event);
1800 case GST_EVENT_SEGMENT:
1802 const GstSegment *s;
1803 gst_event_parse_segment (event, &s);
1804 if (s->format == GST_FORMAT_TIME)
1805 gst_event_copy_segment (event, &self->segment);
1806 GST_DEBUG_OBJECT (self, "newsegment (%s)",
1807 gst_format_get_name (self->segment.format));
1809 /* if not time format, we'll either start with a 0 timestamp anyway or
1810 * it's following a seek in which case we'll have saved the requested
1811 * seek segment and don't want to overwrite it (remember that on a seek
1812 * we always just seek back to the start in BYTES format and just throw
1813 * away all text that's before the requested position; if the subtitles
1814 * come from an upstream demuxer, it won't be able to handle our BYTES
1815 * seek request and instead send us a newsegment from the seek request
1816 * it received via its video pads instead, so all is fine then too) */
1818 gst_event_unref (event);
1819 /* in either case, let's not simply discard this event;
1820 * trigger sending of the saved requested seek segment
1821 * or the one taken here from upstream */
1822 self->need_segment = TRUE;
1827 ret = check_initial_events (self);
1828 if (ret == GST_FLOW_OK) {
1829 ret = gst_pad_event_default (pad, parent, event);
1831 gst_event_unref (event);
1835 case GST_EVENT_FLUSH_START:
1837 self->flushing = TRUE;
1839 ret = gst_pad_event_default (pad, parent, event);
1842 case GST_EVENT_FLUSH_STOP:
1844 self->flushing = FALSE;
1846 ret = gst_pad_event_default (pad, parent, event);
1850 ret = gst_pad_event_default (pad, parent, event);
1858 static GstStateChangeReturn
1859 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1861 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1862 GstSubParse *self = GST_SUBPARSE (element);
1864 switch (transition) {
1865 case GST_STATE_CHANGE_READY_TO_PAUSED:
1866 /* format detection will init the parser state */
1868 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1869 self->strip_pango_markup = FALSE;
1870 self->valid_utf8 = TRUE;
1871 self->first_buffer = TRUE;
1872 g_free (self->detected_encoding);
1873 self->detected_encoding = NULL;
1874 g_string_truncate (self->textbuf, 0);
1875 gst_adapter_clear (self->adapter);
1881 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1882 if (ret == GST_STATE_CHANGE_FAILURE)
1885 switch (transition) {
1886 case GST_STATE_CHANGE_PAUSED_TO_READY:
1887 parser_state_dispose (self, &self->state);
1888 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;