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 g_warning ("Parse 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", end_tag - 1);
789 memmove (next_tag, end_tag + 1, strlen (end_tag) + 1);
790 next_tag -= strlen (end_tag);
793 g_ptr_array_remove_index (open_tags, num_open_tags);
801 if (num_open_tags > 0) {
804 s = g_string_new (*p_txt);
805 while (num_open_tags > 0) {
806 GST_LOG ("adding missing closing tag '%s'",
807 (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
808 g_string_append_c (s, '<');
809 g_string_append_c (s, '/');
810 g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
811 g_string_append_c (s, '>');
815 *p_txt = g_string_free (s, FALSE);
817 g_ptr_array_free (open_tags, TRUE);
821 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
823 gchar s[128] = { '\0', };
825 guint hour, min, sec, msec, len;
827 while (*ts_string == ' ')
830 g_strlcpy (s, ts_string, sizeof (s));
831 if ((end = strstr (s, "-->")))
835 /* ms may be in these formats:
836 * hh:mm:ss,500 = 500ms
839 * hh:mm:ss, 50 = 50ms
841 * and the same with . instead of ,.
842 * sscanf() doesn't differentiate between ' 5' and '5' so munge
843 * the white spaces within the timestamp to '0' (I'm sure there's a
844 * way to make sscanf() do this for us, but how?)
846 g_strdelimit (s, " ", '0');
847 g_strdelimit (s, ".", ',');
849 /* make sure we have exactly three digits after he comma */
852 /* If there isn't a ',' the timestamp is broken */
853 /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
854 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
864 g_strlcat (&p[len], "0", 2);
868 GST_LOG ("parsing timestamp '%s'", s);
869 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
870 /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
872 * The hours component is optional with webVTT, for example
873 * mm:ss,500 is a valid webVTT timestamp. When not present,
878 if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
879 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
884 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
888 /* cue settings are part of the WebVTT specification. They are
889 * declared after the time interval in the first line of the
890 * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
891 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
894 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
896 gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
898 gint16 text_position, text_size;
899 gint16 line_position;
900 gboolean vertical_found = FALSE;
901 gboolean alignment_found = FALSE;
903 while (i < g_strv_length (splitted_settings)) {
904 gboolean valid_tag = FALSE;
905 switch (splitted_settings[i][0]) {
907 if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
908 &text_position) > 0) {
909 state->text_position = (guint8) text_position;
914 if (strlen (splitted_settings[i]) > 2) {
915 vertical_found = TRUE;
916 g_free (state->vertical);
917 state->vertical = g_strdup (splitted_settings[i] + 2);
922 if (g_str_has_suffix (splitted_settings[i], "%")) {
923 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
924 &line_position) > 0) {
925 state->line_position = line_position;
929 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
930 &line_position) > 0) {
931 state->line_number = line_position;
937 if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
939 state->text_size = (guint8) text_size;
944 if (strlen (splitted_settings[i]) > 2) {
945 g_free (state->alignment);
946 state->alignment = g_strdup (splitted_settings[i] + 2);
947 alignment_found = TRUE;
955 GST_LOG ("Invalid or unrecognised setting found: %s",
956 splitted_settings[i]);
960 g_strfreev (splitted_settings);
961 if (!vertical_found) {
962 g_free (state->vertical);
963 state->vertical = g_strdup ("");
965 if (!alignment_found) {
966 g_free (state->alignment);
967 state->alignment = g_strdup ("");
972 parse_subrip (ParserState * state, const gchar * line)
976 switch (state->state) {
981 /* looking for a single integer as a Cue ID, but we
982 * don't actually use it */
984 id = g_ascii_strtoull (line, &endptr, 10);
985 if (id == G_MAXUINT64 && errno == ERANGE)
987 else if (id == 0 && errno == EINVAL)
989 else if (endptr != line && *endptr == '\0')
995 GstClockTime ts_start, ts_end;
998 /* looking for start_time --> end_time */
999 if ((end_time = strstr (line, " --> ")) &&
1000 parse_subrip_time (line, &ts_start) &&
1001 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1002 state->start_time <= ts_end) {
1004 state->start_time = ts_start;
1005 state->duration = ts_end - ts_start;
1007 GST_DEBUG ("error parsing subrip time line '%s'", line);
1014 /* No need to parse that text if it's out of segment */
1015 guint64 clip_start = 0, clip_stop = 0;
1016 gboolean in_seg = FALSE;
1018 /* Check our segment start/stop */
1019 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1020 state->start_time, state->start_time + state->duration,
1021 &clip_start, &clip_stop);
1024 state->start_time = clip_start;
1025 state->duration = clip_stop - clip_start;
1031 /* looking for subtitle text; empty line ends this subtitle entry */
1032 if (state->buf->len)
1033 g_string_append_c (state->buf, '\n');
1034 g_string_append (state->buf, line);
1035 if (strlen (line) == 0) {
1036 ret = g_markup_escape_text (state->buf->str, state->buf->len);
1037 g_string_truncate (state->buf, 0);
1039 subrip_unescape_formatting (ret, state->allowed_tags,
1040 state->allows_tag_attributes);
1041 subrip_remove_unhandled_tags (ret);
1042 strip_trailing_newlines (ret);
1043 subrip_fix_up_markup (&ret, state->allowed_tags);
1048 g_return_val_if_reached (NULL);
1053 parse_lrc (ParserState * state, const gchar * line)
1062 if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1063 sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1066 start = strchr (line, ']');
1067 if (start - line == 9)
1072 state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1073 + gst_util_uint64_scale (s, GST_SECOND, 1)
1074 + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1075 state->duration = GST_CLOCK_TIME_NONE;
1077 return g_strdup (start + 1);
1080 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1081 * element. This format is similar to Subrip, the biggest differences
1082 * are that there can be cue settings detailing how to display the cue
1083 * text and more markup tags are allowed.
1084 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1087 parse_webvtt (ParserState * state, const gchar * line)
1089 /* Cue IDs are optional in WebVTT, but not in subrip,
1090 * so when in state 0 (cue ID), also check if we're
1091 * already at the start --> end time marker */
1092 if (state->state == 0 || state->state == 1) {
1093 GstClockTime ts_start, ts_end;
1095 gchar *cue_settings = NULL;
1097 /* looking for start_time --> end_time */
1098 if ((end_time = strstr (line, " --> ")) &&
1099 parse_subrip_time (line, &ts_start) &&
1100 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1101 state->start_time <= ts_end) {
1103 state->start_time = ts_start;
1104 state->duration = ts_end - ts_start;
1105 cue_settings = strstr (end_time + strlen (" --> "), " ");
1107 GST_DEBUG ("error parsing subrip time line '%s'", line);
1111 state->text_position = 0;
1112 state->text_size = 0;
1113 state->line_position = 0;
1114 state->line_number = 0;
1117 parse_webvtt_cue_settings (state, cue_settings + 1);
1119 g_free (state->vertical);
1120 state->vertical = g_strdup ("");
1121 g_free (state->alignment);
1122 state->alignment = g_strdup ("");
1127 return parse_subrip (state, line);
1131 unescape_newlines_br (gchar * read)
1133 gchar *write = read;
1135 /* Replace all occurrences of '[br]' with a newline as version 2
1136 * of the subviewer format uses this for newlines */
1138 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1142 if (strncmp (read, "[br]", 4) == 0) {
1156 parse_subviewer (ParserState * state, const gchar * line)
1158 guint h1, m1, s1, ms1;
1159 guint h2, m2, s2, ms2;
1162 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1163 * For examples see the unit test or
1164 * http://www.doom9.org/index.html?/sub.htm */
1166 switch (state->state) {
1168 /* looking for start_time,end_time */
1169 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1170 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1173 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1176 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1177 ms2 * GST_MSECOND - state->start_time;
1182 /* No need to parse that text if it's out of segment */
1183 guint64 clip_start = 0, clip_stop = 0;
1184 gboolean in_seg = FALSE;
1186 /* Check our segment start/stop */
1187 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1188 state->start_time, state->start_time + state->duration,
1189 &clip_start, &clip_stop);
1192 state->start_time = clip_start;
1193 state->duration = clip_stop - clip_start;
1199 /* looking for subtitle text; empty line ends this subtitle entry */
1200 if (state->buf->len)
1201 g_string_append_c (state->buf, '\n');
1202 g_string_append (state->buf, line);
1203 if (strlen (line) == 0) {
1204 ret = g_strdup (state->buf->str);
1205 unescape_newlines_br (ret);
1206 strip_trailing_newlines (ret);
1207 g_string_truncate (state->buf, 0);
1213 g_assert_not_reached ();
1219 parse_mpsub (ParserState * state, const gchar * line)
1224 switch (state->state) {
1226 /* looking for two floats (offset, duration) */
1227 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1229 state->start_time += state->duration + GST_SECOND * t1;
1230 state->duration = GST_SECOND * t2;
1234 { /* No need to parse that text if it's out of segment */
1235 guint64 clip_start = 0, clip_stop = 0;
1236 gboolean in_seg = FALSE;
1238 /* Check our segment start/stop */
1239 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1240 state->start_time, state->start_time + state->duration,
1241 &clip_start, &clip_stop);
1244 state->start_time = clip_start;
1245 state->duration = clip_stop - clip_start;
1251 /* looking for subtitle text; empty line ends this
1253 if (state->buf->len)
1254 g_string_append_c (state->buf, '\n');
1255 g_string_append (state->buf, line);
1256 if (strlen (line) == 0) {
1257 ret = g_strdup (state->buf->str);
1258 g_string_truncate (state->buf, 0);
1264 g_assert_not_reached ();
1269 static const gchar *
1270 dks_skip_timestamp (const gchar * line)
1272 while (*line && *line != ']')
1280 parse_dks (ParserState * state, const gchar * line)
1284 switch (state->state) {
1286 /* Looking for the start time and text */
1287 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1289 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1290 text = dks_skip_timestamp (line);
1293 g_string_append (state->buf, text);
1299 guint64 clip_start = 0, clip_stop = 0;
1303 /* Looking for the end time */
1304 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1306 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1309 GST_WARNING ("Failed to parse subtitle end time");
1313 /* Check if this subtitle is out of the current segment */
1314 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1315 state->start_time, state->start_time + state->duration,
1316 &clip_start, &clip_stop);
1322 state->start_time = clip_start;
1323 state->duration = clip_stop - clip_start;
1325 ret = g_strdup (state->buf->str);
1326 g_string_truncate (state->buf, 0);
1327 unescape_newlines_br (ret);
1331 g_assert_not_reached ();
1337 parser_state_init (ParserState * state)
1339 GST_DEBUG ("initialising parser");
1342 g_string_truncate (state->buf, 0);
1344 state->buf = g_string_new (NULL);
1347 state->start_time = 0;
1348 state->duration = 0;
1349 state->max_duration = 0; /* no limit */
1351 state->segment = NULL;
1355 parser_state_dispose (GstSubParse * self, ParserState * state)
1358 g_string_free (state->buf, TRUE);
1362 g_free (state->vertical);
1363 state->vertical = NULL;
1364 g_free (state->alignment);
1365 state->alignment = NULL;
1367 if (state->user_data) {
1368 switch (self->parser_type) {
1369 case GST_SUB_PARSE_FORMAT_QTTEXT:
1370 qttext_context_deinit (state);
1372 case GST_SUB_PARSE_FORMAT_SAMI:
1373 sami_context_deinit (state);
1379 state->allowed_tags = NULL;
1385 gst_sub_parse_format_autodetect (GstSubParse * self)
1388 GstSubParseFormat format;
1390 if (strlen (self->textbuf->str) < 6) {
1391 GST_DEBUG ("File too small to be a subtitles file");
1395 data = g_strndup (self->textbuf->str, 35);
1396 format = gst_sub_parse_data_format_autodetect (data);
1399 self->parser_type = format;
1400 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1401 parser_state_init (&self->state);
1402 self->state.allowed_tags = NULL;
1405 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1406 self->parse_line = parse_mdvdsub;
1407 return gst_caps_new_simple ("text/x-raw",
1408 "format", G_TYPE_STRING, "pango-markup", NULL);
1409 case GST_SUB_PARSE_FORMAT_SUBRIP:
1410 self->state.allowed_tags = (gpointer) allowed_srt_tags;
1411 self->state.allows_tag_attributes = FALSE;
1412 self->parse_line = parse_subrip;
1413 return gst_caps_new_simple ("text/x-raw",
1414 "format", G_TYPE_STRING, "pango-markup", NULL);
1415 case GST_SUB_PARSE_FORMAT_MPSUB:
1416 self->parse_line = parse_mpsub;
1417 return gst_caps_new_simple ("text/x-raw",
1418 "format", G_TYPE_STRING, "utf8", NULL);
1419 case GST_SUB_PARSE_FORMAT_SAMI:
1420 self->parse_line = parse_sami;
1421 sami_context_init (&self->state);
1422 return gst_caps_new_simple ("text/x-raw",
1423 "format", G_TYPE_STRING, "pango-markup", NULL);
1424 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1425 self->parse_line = parse_tmplayer;
1426 self->state.max_duration = 5 * GST_SECOND;
1427 return gst_caps_new_simple ("text/x-raw",
1428 "format", G_TYPE_STRING, "utf8", NULL);
1429 case GST_SUB_PARSE_FORMAT_MPL2:
1430 self->parse_line = parse_mpl2;
1431 return gst_caps_new_simple ("text/x-raw",
1432 "format", G_TYPE_STRING, "pango-markup", NULL);
1433 case GST_SUB_PARSE_FORMAT_DKS:
1434 self->parse_line = parse_dks;
1435 return gst_caps_new_simple ("text/x-raw",
1436 "format", G_TYPE_STRING, "utf8", NULL);
1437 case GST_SUB_PARSE_FORMAT_VTT:
1438 self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1439 self->state.allows_tag_attributes = TRUE;
1440 self->parse_line = parse_webvtt;
1441 return gst_caps_new_simple ("text/x-raw",
1442 "format", G_TYPE_STRING, "pango-markup", NULL);
1443 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1444 self->parse_line = parse_subviewer;
1445 return gst_caps_new_simple ("text/x-raw",
1446 "format", G_TYPE_STRING, "utf8", NULL);
1447 case GST_SUB_PARSE_FORMAT_QTTEXT:
1448 self->parse_line = parse_qttext;
1449 qttext_context_init (&self->state);
1450 return gst_caps_new_simple ("text/x-raw",
1451 "format", G_TYPE_STRING, "pango-markup", NULL);
1452 case GST_SUB_PARSE_FORMAT_LRC:
1453 self->parse_line = parse_lrc;
1454 return gst_caps_new_simple ("text/x-raw",
1455 "format", G_TYPE_STRING, "utf8", NULL);
1456 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1458 GST_DEBUG ("no subtitle format detected");
1459 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1460 ("The input is not a valid/supported subtitle file"), (NULL));
1466 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1470 gchar *input = NULL;
1474 discont = GST_BUFFER_IS_DISCONT (buf);
1476 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1477 GST_BUFFER_OFFSET (buf) != self->offset) {
1478 self->offset = GST_BUFFER_OFFSET (buf);
1483 GST_INFO ("discontinuity");
1484 /* flush the parser state */
1485 parser_state_init (&self->state);
1486 g_string_truncate (self->textbuf, 0);
1487 gst_adapter_clear (self->adapter);
1488 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1489 sami_context_reset (&self->state);
1490 /* we could set a flag to make sure that the next buffer we push out also
1491 * has the DISCONT flag set, but there's no point really given that it's
1492 * subtitles which are discontinuous by nature. */
1495 self->offset += gst_buffer_get_size (buf);
1497 gst_adapter_push (self->adapter, buf);
1499 avail = gst_adapter_available (self->adapter);
1500 data = gst_adapter_map (self->adapter, avail);
1501 input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1503 if (input && consumed > 0) {
1504 self->textbuf = g_string_append (self->textbuf, input);
1505 gst_adapter_unmap (self->adapter);
1506 gst_adapter_flush (self->adapter, consumed);
1508 gst_adapter_unmap (self->adapter);
1516 xml_text (GMarkupParseContext * context,
1517 const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1519 gchar **accum = (gchar **) user_data;
1523 concat = g_strconcat (*accum, text, NULL);
1527 *accum = g_strdup (text);
1532 strip_pango_markup (gchar * markup, GError ** error)
1534 GMarkupParser parser = { 0, };
1535 GMarkupParseContext *context;
1536 gchar *accum = NULL;
1538 parser.text = xml_text;
1539 context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1541 g_markup_parse_context_parse (context, "<root>", 6, NULL);
1542 g_markup_parse_context_parse (context, markup, strlen (markup), error);
1543 g_markup_parse_context_parse (context, "</root>", 7, NULL);
1547 g_markup_parse_context_end_parse (context, error);
1552 g_markup_parse_context_free (context);
1562 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1565 gboolean ret = FALSE;
1566 const GstStructure *s1, *s2;
1568 caps = gst_pad_get_allowed_caps (self->srcpad);
1570 s1 = gst_caps_get_structure (preferred, 0);
1572 if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1573 GstCaps *intersected = gst_caps_intersect (caps, preferred);
1574 gst_caps_unref (caps);
1578 caps = gst_caps_fixate (caps);
1580 if (gst_caps_is_empty (caps)) {
1584 s2 = gst_caps_get_structure (caps, 0);
1586 self->strip_pango_markup =
1587 !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1588 && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1590 if (self->strip_pango_markup) {
1591 GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1594 ret = gst_pad_set_caps (self->srcpad, caps);
1597 gst_caps_unref (caps);
1601 static GstFlowReturn
1602 handle_buffer (GstSubParse * self, GstBuffer * buf)
1604 GstFlowReturn ret = GST_FLOW_OK;
1605 gchar *line, *subtitle;
1606 gboolean need_tags = FALSE;
1608 if (self->first_buffer) {
1611 gst_buffer_map (buf, &map, GST_MAP_READ);
1612 self->detected_encoding =
1613 gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1614 gst_buffer_unmap (buf, &map);
1615 self->first_buffer = FALSE;
1616 self->state.fps_n = self->fps_n;
1617 self->state.fps_d = self->fps_d;
1620 feed_textbuf (self, buf);
1622 /* make sure we know the format */
1623 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1626 if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1627 return GST_FLOW_NOT_NEGOTIATED;
1630 if (!gst_sub_parse_negotiate (self, preferred)) {
1631 gst_caps_unref (preferred);
1632 return GST_FLOW_NOT_NEGOTIATED;
1635 gst_caps_unref (preferred);
1640 /* Push newsegment if needed */
1641 if (self->need_segment) {
1642 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1645 gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1646 self->need_segment = FALSE;
1651 if (self->subtitle_codec != NULL) {
1654 tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1656 gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1660 while (!self->flushing && (line = get_next_line (self))) {
1663 /* Set segment on our parser state machine */
1664 self->state.segment = &self->segment;
1665 /* Now parse the line, out of segment lines will just return NULL */
1666 GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1668 subtitle = self->parse_line (&self->state, line + offset);
1674 if (self->strip_pango_markup) {
1675 GError *error = NULL;
1678 if ((stripped = strip_pango_markup (subtitle, &error))) {
1680 subtitle = stripped;
1682 GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1687 subtitle_len = strlen (subtitle);
1689 /* +1 for terminating NUL character */
1690 buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1692 /* copy terminating NUL character as well */
1693 gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1694 gst_buffer_set_size (buf, subtitle_len);
1696 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1697 GST_BUFFER_DURATION (buf) = self->state.duration;
1699 /* in some cases (e.g. tmplayer) we can only determine the duration
1700 * of a text chunk from the timestamp of the next text chunk; in those
1701 * cases, we probably want to limit the duration to something
1702 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1703 * just because nothing else is being said during that time */
1704 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1705 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1706 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1709 self->segment.position = self->state.start_time;
1711 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1712 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1713 GST_TIME_ARGS (self->state.duration));
1715 g_free (self->state.vertical);
1716 self->state.vertical = NULL;
1717 g_free (self->state.alignment);
1718 self->state.alignment = NULL;
1720 ret = gst_pad_push (self->srcpad, buf);
1722 /* move this forward (the tmplayer parser needs this) */
1723 if (self->state.duration != GST_CLOCK_TIME_NONE)
1724 self->state.start_time += self->state.duration;
1729 if (ret != GST_FLOW_OK) {
1730 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1739 static GstFlowReturn
1740 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1745 self = GST_SUBPARSE (parent);
1747 ret = handle_buffer (self, buf);
1753 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1755 GstSubParse *self = GST_SUBPARSE (parent);
1756 gboolean ret = FALSE;
1758 GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
1760 switch (GST_EVENT_TYPE (event)) {
1761 case GST_EVENT_STREAM_GROUP_DONE:
1762 case GST_EVENT_EOS:{
1763 /* Make sure the last subrip chunk is pushed out even
1764 * if the file does not have an empty line at the end */
1765 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1766 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1767 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1768 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
1769 self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
1770 gchar term_chars[] = { '\n', '\n', '\0' };
1771 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1773 GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
1774 GST_EVENT_TYPE_NAME (event));
1776 gst_buffer_fill (buf, 0, term_chars, 3);
1777 gst_buffer_set_size (buf, 2);
1779 GST_BUFFER_OFFSET (buf) = self->offset;
1780 gst_sub_parse_chain (pad, parent, buf);
1782 ret = gst_pad_event_default (pad, parent, event);
1785 case GST_EVENT_SEGMENT:
1787 const GstSegment *s;
1788 gst_event_parse_segment (event, &s);
1789 if (s->format == GST_FORMAT_TIME)
1790 gst_event_copy_segment (event, &self->segment);
1791 GST_DEBUG_OBJECT (self, "newsegment (%s)",
1792 gst_format_get_name (self->segment.format));
1794 /* if not time format, we'll either start with a 0 timestamp anyway or
1795 * it's following a seek in which case we'll have saved the requested
1796 * seek segment and don't want to overwrite it (remember that on a seek
1797 * we always just seek back to the start in BYTES format and just throw
1798 * away all text that's before the requested position; if the subtitles
1799 * come from an upstream demuxer, it won't be able to handle our BYTES
1800 * seek request and instead send us a newsegment from the seek request
1801 * it received via its video pads instead, so all is fine then too) */
1803 gst_event_unref (event);
1804 /* in either case, let's not simply discard this event;
1805 * trigger sending of the saved requested seek segment
1806 * or the one taken here from upstream */
1807 self->need_segment = TRUE;
1810 case GST_EVENT_FLUSH_START:
1812 self->flushing = TRUE;
1814 ret = gst_pad_event_default (pad, parent, event);
1817 case GST_EVENT_FLUSH_STOP:
1819 self->flushing = FALSE;
1821 ret = gst_pad_event_default (pad, parent, event);
1825 ret = gst_pad_event_default (pad, parent, event);
1833 static GstStateChangeReturn
1834 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1836 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1837 GstSubParse *self = GST_SUBPARSE (element);
1839 switch (transition) {
1840 case GST_STATE_CHANGE_READY_TO_PAUSED:
1841 /* format detection will init the parser state */
1843 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1844 self->strip_pango_markup = FALSE;
1845 self->valid_utf8 = TRUE;
1846 self->first_buffer = TRUE;
1847 g_free (self->detected_encoding);
1848 self->detected_encoding = NULL;
1849 g_string_truncate (self->textbuf, 0);
1850 gst_adapter_clear (self->adapter);
1856 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1857 if (ret == GST_STATE_CHANGE_FAILURE)
1860 switch (transition) {
1861 case GST_STATE_CHANGE_PAUSED_TO_READY:
1862 parser_state_dispose (self, &self->state);
1863 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;