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 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
44 #define SUBPARSE_SEEK_GET_LOCK(elem) (&elem->seek_lock)
45 #define SUBPARSE_SEEK_LOCK(elem) g_mutex_lock(SUBPARSE_SEEK_GET_LOCK(elem))
46 #define SUBPARSE_SEEK_TRYLOCK(elem) g_mutex_trylock(SUBPARSE_SEEK_GET_LOCK(elem))
47 #define SUBPARSE_SEEK_UNLOCK(elem) g_mutex_unlock(SUBPARSE_SEEK_GET_LOCK(elem))
49 #define DEFAULT_ENCODING NULL
50 #define ATTRIBUTE_REGEX "\\s?[a-zA-Z0-9\\. \t\\(\\)]*"
51 static const gchar *allowed_srt_tags[] = { "i", "b", "u", NULL };
52 static const gchar *allowed_vtt_tags[] =
53 { "i", "b", "c", "u", "v", "ruby", "rt", NULL };
55 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
56 #define DEFAULT_CURRENT_LANGUAGE NULL
58 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
59 #define DEFAULT_DROP_OUT_OF_SEGMENT TRUE
66 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
67 PROP_EXTSUB_CURRENT_LANGUAGE,
69 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
70 PROP_DROP_OUT_OF_SEGMENT,
73 #ifdef TIZEN_FEATURE_HLS_WEBVTT
74 #define MPEGTIME_TO_GSTTIME(t) ((t) * (guint64)100000 / 9)
78 gst_sub_parse_set_property (GObject * object, guint prop_id,
79 const GValue * value, GParamSpec * pspec);
81 gst_sub_parse_get_property (GObject * object, guint prop_id,
82 GValue * value, GParamSpec * pspec);
85 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
88 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
89 "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
90 "application/x-subtitle-dks; application/x-subtitle-qttext;"
91 "application/x-subtitle-lrc; application/x-subtitle-vtt")
94 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
97 GST_STATIC_CAPS ("text/x-raw, format= { pango-markup, utf8 }")
101 static gboolean gst_sub_parse_src_event (GstPad * pad, GstObject * parent,
103 static gboolean gst_sub_parse_src_query (GstPad * pad, GstObject * parent,
105 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstObject * parent,
108 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
109 GstStateChange transition);
111 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent,
113 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
114 static gboolean gst_sub_parse_check_byte_seekability (GstSubParse * subparse);
116 #define gst_sub_parse_parent_class parent_class
117 G_DEFINE_TYPE (GstSubParse, gst_sub_parse, GST_TYPE_ELEMENT);
119 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (subparse, "subparse",
120 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE, sub_parse_element_init (plugin))
123 static void gst_sub_parse_dispose (GObject * object)
125 GstSubParse *subparse = GST_SUBPARSE (object);
127 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
129 if (subparse->encoding) {
130 g_free (subparse->encoding);
131 subparse->encoding = NULL;
134 if (subparse->detected_encoding) {
135 g_free (subparse->detected_encoding);
136 subparse->detected_encoding = NULL;
139 if (subparse->adapter) {
140 g_object_unref (subparse->adapter);
141 subparse->adapter = NULL;
144 if (subparse->textbuf) {
145 g_string_free (subparse->textbuf, TRUE);
146 subparse->textbuf = NULL;
148 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
149 g_free (subparse->state.current_language);
150 subparse->state.current_language = NULL;
152 g_mutex_clear (&subparse->seek_lock);
154 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
158 gst_sub_parse_class_init (GstSubParseClass * klass)
160 GObjectClass *object_class = G_OBJECT_CLASS (klass);
161 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
163 object_class->dispose = gst_sub_parse_dispose;
164 object_class->set_property = gst_sub_parse_set_property;
165 object_class->get_property = gst_sub_parse_get_property;
167 gst_element_class_add_static_pad_template (element_class, &sink_templ);
168 gst_element_class_add_static_pad_template (element_class, &src_templ);
169 gst_element_class_set_static_metadata (element_class,
170 "Subtitle parser", "Codec/Parser/Subtitle",
171 "Parses subtitle (.sub) files into text streams",
172 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
173 "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
175 element_class->change_state = gst_sub_parse_change_state;
177 g_object_class_install_property (object_class, PROP_ENCODING,
178 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
179 "Encoding to assume if input subtitles are not in UTF-8 or any other "
180 "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
181 "variable will be checked for an encoding to use. If that is not set "
182 "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
183 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
185 g_object_class_install_property (object_class, PROP_VIDEOFPS,
186 gst_param_spec_fraction ("video-fps", "Video framerate",
187 "Framerate of the video stream. This is needed by some subtitle "
188 "formats to synchronize subtitles and video properly. If not set "
189 "and the subtitle format requires it subtitles may be out of sync.",
190 0, 1, G_MAXINT, 1, 24000, 1001,
191 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
193 g_object_class_install_property (object_class, PROP_EXTSUB_CURRENT_LANGUAGE,
194 g_param_spec_string ("current-language", "Current language",
195 "Current language of the subtitle in external subtitle case.",
196 DEFAULT_CURRENT_LANGUAGE,
197 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
200 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
201 g_object_class_install_property (object_class, PROP_DROP_OUT_OF_SEGMENT,
202 g_param_spec_boolean ("drop-out-of-segment",
203 "Drop out-of-segment buffers",
204 "Drop and don't send out-of-segment buffers",
205 DEFAULT_DROP_OUT_OF_SEGMENT,
206 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
211 gst_sub_parse_init (GstSubParse * subparse)
213 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
214 gst_pad_set_chain_function (subparse->sinkpad,
215 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
216 gst_pad_set_event_function (subparse->sinkpad,
217 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
218 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
220 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
221 gst_pad_set_event_function (subparse->srcpad,
222 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
223 gst_pad_set_query_function (subparse->srcpad,
224 GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
225 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
227 subparse->textbuf = g_string_new (NULL);
228 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
229 subparse->strip_pango_markup = FALSE;
230 subparse->flushing = FALSE;
231 gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
232 subparse->segment_seqnum = gst_util_seqnum_next ();
233 subparse->need_segment = TRUE;
234 subparse->encoding = g_strdup (DEFAULT_ENCODING);
235 subparse->detected_encoding = NULL;
236 subparse->adapter = gst_adapter_new ();
238 subparse->fps_n = 24000;
239 subparse->fps_d = 1001;
240 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
241 subparse->state.language_list = NULL;
242 subparse->state.current_language = NULL;
243 subparse->state.langlist_msg_posted = FALSE;
244 g_mutex_init (&subparse->seek_lock);
246 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
247 subparse->state.drop_out_of_segment = DEFAULT_DROP_OUT_OF_SEGMENT;
252 * Source pad functions.
256 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
258 GstSubParse *self = GST_SUBPARSE (parent);
259 gboolean ret = FALSE;
261 GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
263 switch (GST_QUERY_TYPE (query)) {
264 case GST_QUERY_POSITION:{
267 gst_query_parse_position (query, &fmt, NULL);
268 if (fmt != GST_FORMAT_TIME) {
269 ret = gst_pad_peer_query (self->sinkpad, query);
272 gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
276 case GST_QUERY_SEEKING:
279 gboolean seekable = FALSE;
283 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
284 if (fmt == GST_FORMAT_TIME) {
285 GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
287 seekable = gst_pad_peer_query (self->sinkpad, peerquery);
289 gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
290 gst_query_unref (peerquery);
293 gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
297 ret = gst_pad_query_default (pad, parent, query);
305 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
307 GstSubParse *self = GST_SUBPARSE (parent);
308 gboolean ret = FALSE;
310 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
312 switch (GST_EVENT_TYPE (event)) {
317 GstSeekType start_type, stop_type;
322 gst_event_parse_seek (event, &rate, &format, &flags,
323 &start_type, &start, &stop_type, &stop);
325 if (format != GST_FORMAT_TIME) {
326 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
327 gst_event_unref (event);
330 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
331 if (!gst_sub_parse_check_byte_seekability (self)) {
332 ret = gst_pad_event_default (pad, parent, event);
336 SUBPARSE_SEEK_LOCK (self);
338 /* Convert that seek to a seeking in bytes at position 0,
339 FIXME: could use an index */
340 ret = gst_pad_push_event (self->sinkpad,
341 gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
342 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
345 /* Apply the seek to our segment */
346 gst_segment_do_seek (&self->segment, rate, format, flags,
347 start_type, start, stop_type, stop, &update);
349 GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
352 /* will mark need_segment when receiving segment from upstream,
353 * after FLUSH and all that has happened,
354 * rather than racing with chain */
356 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
359 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
360 SUBPARSE_SEEK_UNLOCK (self);
363 gst_event_unref (event);
367 ret = gst_pad_event_default (pad, parent, event);
375 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
377 gst_sub_parse_check_byte_seekability (GstSubParse * subparse)
380 gboolean seekable = FALSE;
382 query = gst_query_new_seeking (GST_FORMAT_BYTES);
384 if (gst_pad_peer_query (subparse->sinkpad, query)) {
385 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
387 GST_DEBUG_OBJECT (subparse, "seeking query failed");
390 gst_query_unref (query);
392 GST_INFO_OBJECT (subparse, "byte seekable: %d", seekable);
399 gst_sub_parse_set_property (GObject * object, guint prop_id,
400 const GValue * value, GParamSpec * pspec)
402 GstSubParse *subparse = GST_SUBPARSE (object);
404 GST_OBJECT_LOCK (subparse);
407 g_free (subparse->encoding);
408 subparse->encoding = g_value_dup_string (value);
409 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
410 GST_STR_NULL (subparse->encoding));
414 subparse->fps_n = gst_value_get_fraction_numerator (value);
415 subparse->fps_d = gst_value_get_fraction_denominator (value);
416 GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
419 if (!subparse->state.have_internal_fps) {
420 subparse->state.fps_n = subparse->fps_n;
421 subparse->state.fps_d = subparse->fps_d;
425 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
426 case PROP_EXTSUB_CURRENT_LANGUAGE:
427 g_free (subparse->state.current_language);
428 subparse->state.current_language = g_value_dup_string (value);
429 GST_LOG_OBJECT (subparse, "subtitle current language set to %s",
430 GST_STR_NULL (subparse->state.current_language));
431 sami_context_change_language (&subparse->state);
434 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
435 case PROP_DROP_OUT_OF_SEGMENT:
436 subparse->state.drop_out_of_segment = g_value_get_boolean (value);
437 GST_DEBUG_OBJECT (object, "Drop out of segment set to %d",
438 subparse->state.drop_out_of_segment);
442 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
445 GST_OBJECT_UNLOCK (subparse);
449 gst_sub_parse_get_property (GObject * object, guint prop_id,
450 GValue * value, GParamSpec * pspec)
452 GstSubParse *subparse = GST_SUBPARSE (object);
454 GST_OBJECT_LOCK (subparse);
457 g_value_set_string (value, subparse->encoding);
460 gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
462 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
463 case PROP_EXTSUB_CURRENT_LANGUAGE:
464 g_value_set_string (value, subparse->state.current_language);
467 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
468 case PROP_DROP_OUT_OF_SEGMENT:
469 g_value_set_boolean (value, subparse->state.drop_out_of_segment);
473 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
476 GST_OBJECT_UNLOCK (subparse);
480 gst_sub_parse_get_format_description (GstSubParseFormat format)
483 case GST_SUB_PARSE_FORMAT_MDVDSUB:
485 case GST_SUB_PARSE_FORMAT_SUBRIP:
487 case GST_SUB_PARSE_FORMAT_MPSUB:
489 case GST_SUB_PARSE_FORMAT_SAMI:
491 case GST_SUB_PARSE_FORMAT_TMPLAYER:
493 case GST_SUB_PARSE_FORMAT_MPL2:
495 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
497 case GST_SUB_PARSE_FORMAT_DKS:
499 case GST_SUB_PARSE_FORMAT_VTT:
501 case GST_SUB_PARSE_FORMAT_QTTEXT:
503 case GST_SUB_PARSE_FORMAT_LRC:
506 case GST_SUB_PARSE_FORMAT_UNKNOWN:
517 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
520 const gchar *encoding;
526 /* First try any detected encoding */
527 if (self->detected_encoding) {
529 gst_sub_parse_gst_convert_to_utf8 (str, len, self->detected_encoding,
535 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
536 self->detected_encoding, err->message);
537 g_free (self->detected_encoding);
538 self->detected_encoding = NULL;
539 g_clear_error (&err);
542 /* Otherwise check if it's UTF8 */
543 if (self->valid_utf8) {
544 if (g_utf8_validate (str, len, NULL)) {
545 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
547 return g_strndup (str, len);
549 GST_INFO_OBJECT (self, "invalid UTF-8!");
550 self->valid_utf8 = FALSE;
553 /* Else try fallback */
554 encoding = self->encoding;
555 if (encoding == NULL || *encoding == '\0') {
556 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
558 if (encoding == NULL || *encoding == '\0') {
559 /* if local encoding is UTF-8 and no encoding specified
560 * via the environment variable, assume ISO-8859-15 */
561 if (g_get_charset (&encoding)) {
562 encoding = "ISO-8859-15";
566 ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
569 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
570 encoding, err->message);
571 g_clear_error (&err);
573 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
574 if (!g_strcmp0 (self->encoding, "EUC-KR")) {
575 GST_LOG_OBJECT (self, "use CP949 as fallback");
576 g_free (self->encoding);
577 self->encoding = g_strdup ("CP949");
578 encoding = self->encoding;
579 ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
582 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
584 gst_sub_parse_gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed,
588 GST_LOG_OBJECT (self,
589 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
590 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
596 get_next_line (GstSubParse * self)
599 const char *line_end;
601 gboolean have_r = FALSE;
603 line_end = strchr (self->textbuf->str, '\n');
606 /* end-of-line not found; return for more data */
610 /* get rid of '\r' */
611 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
616 line_len = line_end - self->textbuf->str;
617 line = g_strndup (self->textbuf->str, line_len);
618 self->textbuf = g_string_erase (self->textbuf, 0,
619 line_len + (have_r ? 2 : 1));
624 parse_mdvdsub (ParserState * state, const gchar * line)
626 const gchar *line_split;
628 guint start_frame, end_frame;
629 guint64 clip_start = 0, clip_stop = 0;
630 gboolean in_seg = FALSE;
634 /* style variables */
640 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
641 GST_WARNING ("Parsing of the following line, assumed to be in microdvd .sub"
642 " format, failed:\n%s", line);
646 /* skip the {%u}{%u} part */
647 line = strchr (line, '}') + 1;
648 line = strchr (line, '}') + 1;
650 /* see if there's a first line with a framerate */
651 if (start_frame == 1 && end_frame == 1) {
652 gchar *rest, *end = NULL;
654 rest = g_strdup (line);
655 g_strdelimit (rest, ",", '.');
656 fps = g_ascii_strtod (rest, &end);
658 gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
659 GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
667 gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
670 gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
673 /* Check our segment start/stop */
674 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
675 if (state->drop_out_of_segment) {
677 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
678 state->start_time, state->start_time + state->duration, &clip_start,
681 /* No need to parse that text if it's out of segment */
683 state->start_time = clip_start;
684 state->duration = clip_stop - clip_start;
688 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
692 markup = g_string_new (NULL);
697 /* parse style markup */
698 if (strncmp (line, "{y:i}", 5) == 0) {
700 line = strchr (line, '}') + 1;
702 if (strncmp (line, "{y:b}", 5) == 0) {
704 line = strchr (line, '}') + 1;
706 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
707 line = strchr (line, '}') + 1;
709 /* forward slashes at beginning/end signify italics too */
710 if (g_str_has_prefix (line, "/")) {
714 if ((line_split = strchr (line, '|')))
715 line_chunk = g_markup_escape_text (line, line_split - line);
717 line_chunk = g_markup_escape_text (line, strlen (line));
719 /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
720 * always at the end of a line or can they span multiple lines?) */
721 if (g_str_has_suffix (line_chunk, "/")) {
722 line_chunk[strlen (line_chunk) - 1] = '\0';
725 markup = g_string_append (markup, "<span");
727 g_string_append (markup, " style=\"italic\"");
729 g_string_append (markup, " weight=\"bold\"");
731 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
732 g_string_append_printf (markup, ">%s</span>", line_chunk);
735 g_string_append (markup, "\n");
736 line = line_split + 1;
741 ret = g_string_free (markup, FALSE);
742 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
743 state->start_time / (double) GST_SECOND,
744 state->duration / (double) GST_SECOND, ret);
749 strip_trailing_newlines (gchar * txt)
755 while (len > 1 && txt[len - 1] == '\n') {
762 /* we want to escape text in general, but retain basic markup like
763 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
764 * just unescape a white list of allowed markups again after
765 * escaping everything (the text between these simple markers isn't
766 * necessarily escaped, so it seems best to do it like this) */
768 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
769 gboolean allows_tag_attributes)
773 gchar *allowed_tags_pattern, *search_pattern;
774 const gchar *replace_pattern;
776 /* No processing needed if no escaped tag marker found in the string. */
777 if (strstr (txt, "<") == NULL)
780 /* Build a list of alternates for our regexp.
781 * FIXME: Could be built once and stored */
782 allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
783 /* Look for starting/ending escaped tags with optional attributes. */
784 search_pattern = g_strdup_printf ("<(/)?\\ *(%s)(%s)>",
785 allowed_tags_pattern, ATTRIBUTE_REGEX);
786 /* And unescape appropriately */
787 if (allows_tag_attributes) {
788 replace_pattern = "<\\1\\2\\3>";
790 replace_pattern = "<\\1\\2>";
793 tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
794 res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
795 replace_pattern, 0, NULL);
797 /* res will always be shorter than the input or identical, so this
802 g_free (search_pattern);
803 g_free (allowed_tags_pattern);
805 g_regex_unref (tag_regex);
810 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
814 tag = start + strlen ("<");
818 if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
823 GST_LOG ("removing unhandled tag '%s'", start);
825 memmove (start, stop, strlen (stop) + 1);
829 /* remove tags we haven't explicitly allowed earlier on, like font tags
832 subrip_remove_unhandled_tags (gchar * txt)
836 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
837 if (strncmp (pos, "<", 4) == 0 && (gt = strstr (pos + 4, ">"))) {
838 if (subrip_remove_unhandled_tag (pos, gt + strlen (">")))
844 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
845 * take a simple approach. This code assumes the input has been
846 * escaped and subrip_unescape_formatting() has then been run over the
847 * input! This function adds missing closing markup tags and removes
848 * broken closing tags for tags that have never been opened. */
850 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
852 gchar *cur, *next_tag;
853 GPtrArray *open_tags = NULL;
854 guint num_open_tags = 0;
855 const gchar *iter_tag;
861 GMatchInfo *match_info;
862 gchar **allowed_tags = (gchar **) allowed_tags_ptr;
864 g_assert (*p_txt != NULL);
866 open_tags = g_ptr_array_new_with_free_func (g_free);
868 while (*cur != '\0') {
869 next_tag = strchr (cur, '<');
870 if (next_tag == NULL)
874 while (index < g_strv_length (allowed_tags)) {
875 iter_tag = allowed_tags[index];
876 /* Look for a white listed tag */
877 cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
878 tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
879 (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
881 if (g_match_info_matches (match_info)) {
882 gint start_pos, end_pos;
883 gchar *word = g_match_info_fetch (match_info, 0);
884 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
885 if (start_pos == 0) {
886 offset = strlen (word);
890 g_match_info_free (match_info);
891 g_regex_unref (tag_regex);
895 /* OK we found a tag, let's keep track of it */
896 g_ptr_array_add (open_tags, g_ascii_strdown (iter_tag, -1));
908 if (*next_tag == '<' && *(next_tag + 1) == '/') {
909 end_tag = strchr (next_tag, '>');
911 const gchar *last = NULL;
912 if (num_open_tags > 0)
913 last = g_ptr_array_index (open_tags, num_open_tags - 1);
914 if (num_open_tags == 0
915 || g_ascii_strncasecmp (end_tag - 1, last, strlen (last))) {
916 GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
917 /* Move everything after the tag end, including closing \0 */
918 memmove (next_tag, end_tag + 1, strlen (end_tag));
923 g_ptr_array_remove_index (open_tags, num_open_tags);
933 if (num_open_tags > 0) {
936 s = g_string_new (*p_txt);
937 while (num_open_tags > 0) {
938 GST_LOG ("adding missing closing tag '%s'",
939 (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
940 g_string_append_c (s, '<');
941 g_string_append_c (s, '/');
942 g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
943 g_string_append_c (s, '>');
947 *p_txt = g_string_free (s, FALSE);
949 g_ptr_array_free (open_tags, TRUE);
953 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
955 gchar s[128] = { '\0', };
957 guint hour, min, sec, msec, len;
959 while (*ts_string == ' ')
962 g_strlcpy (s, ts_string, sizeof (s));
963 if ((end = strstr (s, "-->")))
967 /* ms may be in these formats:
968 * hh:mm:ss,500 = 500ms
971 * hh:mm:ss, 50 = 50ms
973 * and the same with . instead of ,.
974 * sscanf() doesn't differentiate between ' 5' and '5' so munge
975 * the white spaces within the timestamp to '0' (I'm sure there's a
976 * way to make sscanf() do this for us, but how?)
978 g_strdelimit (s, " ", '0');
979 g_strdelimit (s, ".", ',');
981 /* make sure we have exactly three digits after he comma */
984 /* If there isn't a ',' the timestamp is broken */
985 /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
986 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
996 g_strlcat (&p[len], "0", 2);
1000 GST_LOG ("parsing timestamp '%s'", s);
1001 if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
1002 /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
1004 * The hours component is optional with webVTT, for example
1005 * mm:ss,500 is a valid webVTT timestamp. When not present,
1010 if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
1011 GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
1016 *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
1020 /* cue settings are part of the WebVTT specification. They are
1021 * declared after the time interval in the first line of the
1022 * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
1023 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1026 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
1028 gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
1030 gint16 text_position, text_size;
1031 gint16 line_position;
1032 gboolean vertical_found = FALSE;
1033 gboolean alignment_found = FALSE;
1035 while (i < g_strv_length (splitted_settings)) {
1036 gboolean valid_tag = FALSE;
1037 switch (splitted_settings[i][0]) {
1039 if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
1040 &text_position) > 0) {
1041 state->text_position = (guint8) text_position;
1046 if (strlen (splitted_settings[i]) > 2) {
1047 vertical_found = TRUE;
1048 g_free (state->vertical);
1049 state->vertical = g_strdup (splitted_settings[i] + 2);
1054 if (g_str_has_suffix (splitted_settings[i], "%")) {
1055 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
1056 &line_position) > 0) {
1057 state->line_position = line_position;
1061 if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
1062 &line_position) > 0) {
1063 state->line_number = line_position;
1069 if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
1071 state->text_size = (guint8) text_size;
1076 if (strlen (splitted_settings[i]) > 2) {
1077 g_free (state->alignment);
1078 state->alignment = g_strdup (splitted_settings[i] + 2);
1079 alignment_found = TRUE;
1087 GST_LOG ("Invalid or unrecognised setting found: %s",
1088 splitted_settings[i]);
1092 g_strfreev (splitted_settings);
1093 if (!vertical_found) {
1094 g_free (state->vertical);
1095 state->vertical = g_strdup ("");
1097 if (!alignment_found) {
1098 g_free (state->alignment);
1099 state->alignment = g_strdup ("");
1103 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1105 parse_timestamp_map (ParserState * state, const gchar * timestamp_map)
1107 GstClockTime local = 0;
1109 gchar *local_start = NULL;
1110 gchar *mpegts_start = NULL;
1115 local_start = g_strrstr (timestamp_map, "LOCAL:");
1117 parse_subrip_time (local_start + strlen ("LOCAL:"), &local);
1119 mpegts_start = g_strrstr (timestamp_map, "MPEGTS:");
1121 mpegts = g_ascii_strtoull (mpegts_start + strlen ("MPEGTS:"), NULL, 10);
1123 GST_LOG ("parsed local time %" GST_TIME_FORMAT " MPEGTS: %" G_GUINT64_FORMAT,
1124 GST_TIME_ARGS (local), mpegts);
1126 state->local = local;
1127 state->mpegts = mpegts;
1131 send_fragment_timestamp_event (GstSubParse * self, GstClockTime timestamp)
1133 GstEvent *event = NULL;
1135 if (!GST_CLOCK_TIME_IS_VALID (timestamp))
1138 GST_LOG ("send fragment_timestamp %" GST_TIME_FORMAT,
1139 GST_TIME_ARGS (timestamp));
1141 event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
1142 gst_structure_new ("fragment_timestamp",
1143 "timestamp", G_TYPE_UINT64, timestamp, NULL));
1145 gst_pad_push_event (self->srcpad, event);
1150 parse_subrip (ParserState * state, const gchar * line)
1154 switch (state->state) {
1159 /* looking for a single integer as a Cue ID, but we
1160 * don't actually use it */
1162 id = g_ascii_strtoull (line, &endptr, 10);
1163 if (id == G_MAXUINT64 && errno == ERANGE)
1165 else if (id == 0 && errno == EINVAL)
1167 else if (endptr != line && *endptr == '\0')
1173 GstClockTime ts_start, ts_end;
1176 /* looking for start_time --> end_time */
1177 if ((end_time = strstr (line, " --> ")) &&
1178 parse_subrip_time (line, &ts_start) &&
1179 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1180 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1181 state->start_time <=
1182 ts_end + MPEGTIME_TO_GSTTIME (state->mpegts) - state->local) {
1184 state->start_time <= ts_end) {
1187 state->start_time = ts_start;
1188 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1189 state->start_time += MPEGTIME_TO_GSTTIME (state->mpegts) - state->local;
1191 state->duration = ts_end - ts_start;
1193 GST_DEBUG ("error parsing subrip time line '%s'", line);
1200 /* No need to parse that text if it's out of segment */
1201 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1202 if (state->drop_out_of_segment) {
1204 guint64 clip_start = 0, clip_stop = 0;
1205 gboolean in_seg = FALSE;
1207 /* Check our segment start/stop */
1208 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1209 state->start_time, state->start_time + state->duration,
1210 &clip_start, &clip_stop);
1213 state->start_time = clip_start;
1214 state->duration = clip_stop - clip_start;
1219 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1223 /* looking for subtitle text; empty line ends this subtitle entry */
1224 if (state->buf->len)
1225 g_string_append_c (state->buf, '\n');
1226 g_string_append (state->buf, line);
1227 if (strlen (line) == 0) {
1228 ret = g_markup_escape_text (state->buf->str, state->buf->len);
1229 g_string_truncate (state->buf, 0);
1231 subrip_unescape_formatting (ret, state->allowed_tags,
1232 state->allows_tag_attributes);
1233 subrip_remove_unhandled_tags (ret);
1234 strip_trailing_newlines (ret);
1235 subrip_fix_up_markup (&ret, state->allowed_tags);
1240 g_return_val_if_reached (NULL);
1245 parse_lrc (ParserState * state, const gchar * line)
1254 if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1255 sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1258 start = strchr (line, ']');
1259 if (start - line == 9)
1264 state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1265 + gst_util_uint64_scale (s, GST_SECOND, 1)
1266 + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1267 state->duration = GST_CLOCK_TIME_NONE;
1269 return g_strdup (start + 1);
1272 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1273 * element. This format is similar to Subrip, the biggest differences
1274 * are that there can be cue settings detailing how to display the cue
1275 * text and more markup tags are allowed.
1276 * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1279 parse_webvtt (ParserState * state, const gchar * line)
1281 /* Cue IDs are optional in WebVTT, but not in subrip,
1282 * so when in state 0 (cue ID), also check if we're
1283 * already at the start --> end time marker */
1284 if (state->state == 0 || state->state == 1) {
1285 GstClockTime ts_start, ts_end;
1287 gchar *cue_settings = NULL;
1289 /* looking for start_time --> end_time */
1290 if ((end_time = strstr (line, " --> ")) &&
1291 parse_subrip_time (line, &ts_start) &&
1292 parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1293 state->start_time <= ts_end) {
1295 state->start_time = ts_start;
1296 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1297 state->start_time += MPEGTIME_TO_GSTTIME (state->mpegts) - state->local;
1299 state->duration = ts_end - ts_start;
1300 cue_settings = strstr (end_time + strlen (" --> "), " ");
1301 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1302 } else if (strstr (line, "X-TIMESTAMP-MAP")) {
1303 GST_DEBUG ("got X-TIMESTAMP-MAP '%s'", line);
1304 parse_timestamp_map (state, line);
1308 GST_DEBUG ("error parsing subrip time line '%s'", line);
1312 state->text_position = 0;
1313 state->text_size = 0;
1314 state->line_position = 0;
1315 state->line_number = 0;
1318 parse_webvtt_cue_settings (state, cue_settings + 1);
1320 g_free (state->vertical);
1321 state->vertical = g_strdup ("");
1322 g_free (state->alignment);
1323 state->alignment = g_strdup ("");
1328 return parse_subrip (state, line);
1332 unescape_newlines_br (gchar * read)
1334 gchar *write = read;
1336 /* Replace all occurrences of '[br]' with a newline as version 2
1337 * of the subviewer format uses this for newlines */
1339 if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1343 if (strncmp (read, "[br]", 4) == 0) {
1357 parse_subviewer (ParserState * state, const gchar * line)
1359 guint h1, m1, s1, ms1;
1360 guint h2, m2, s2, ms2;
1363 /* TODO: Maybe also parse the fields in the header, especially DELAY.
1364 * For examples see the unit test or
1365 * http://www.doom9.org/index.html?/sub.htm */
1367 switch (state->state) {
1369 /* looking for start_time,end_time */
1370 if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1371 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1374 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1377 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1378 ms2 * GST_MSECOND - state->start_time;
1383 /* No need to parse that text if it's out of segment */
1384 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1385 if (state->drop_out_of_segment) {
1387 guint64 clip_start = 0, clip_stop = 0;
1388 gboolean in_seg = FALSE;
1390 /* Check our segment start/stop */
1391 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1392 state->start_time, state->start_time + state->duration,
1393 &clip_start, &clip_stop);
1396 state->start_time = clip_start;
1397 state->duration = clip_stop - clip_start;
1402 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1406 /* looking for subtitle text; empty line ends this subtitle entry */
1407 if (state->buf->len)
1408 g_string_append_c (state->buf, '\n');
1409 g_string_append (state->buf, line);
1410 if (strlen (line) == 0) {
1411 ret = g_strdup (state->buf->str);
1412 unescape_newlines_br (ret);
1413 strip_trailing_newlines (ret);
1414 g_string_truncate (state->buf, 0);
1420 g_assert_not_reached ();
1426 parse_mpsub (ParserState * state, const gchar * line)
1431 switch (state->state) {
1433 /* looking for two floats (offset, duration) */
1434 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1436 state->start_time += state->duration + GST_SECOND * t1;
1437 state->duration = GST_SECOND * t2;
1441 { /* No need to parse that text if it's out of segment */
1442 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1443 if (state->drop_out_of_segment) {
1445 guint64 clip_start = 0, clip_stop = 0;
1446 gboolean in_seg = FALSE;
1448 /* Check our segment start/stop */
1449 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1450 state->start_time, state->start_time + state->duration,
1451 &clip_start, &clip_stop);
1454 state->start_time = clip_start;
1455 state->duration = clip_stop - clip_start;
1460 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1464 /* looking for subtitle text; empty line ends this
1466 if (state->buf->len)
1467 g_string_append_c (state->buf, '\n');
1468 g_string_append (state->buf, line);
1469 if (strlen (line) == 0) {
1470 ret = g_strdup (state->buf->str);
1471 g_string_truncate (state->buf, 0);
1477 g_assert_not_reached ();
1482 static const gchar *
1483 dks_skip_timestamp (const gchar * line)
1485 while (*line && *line != ']')
1493 parse_dks (ParserState * state, const gchar * line)
1497 switch (state->state) {
1499 /* Looking for the start time and text */
1500 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1502 state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1503 text = dks_skip_timestamp (line);
1506 g_string_append (state->buf, text);
1512 guint64 clip_start = 0, clip_stop = 0;
1516 /* Looking for the end time */
1517 if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1519 state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1522 GST_WARNING ("Failed to parse subtitle end time");
1525 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1526 if (state->drop_out_of_segment) {
1528 /* Check if this subtitle is out of the current segment */
1529 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1530 state->start_time, state->start_time + state->duration,
1531 &clip_start, &clip_stop);
1536 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1540 state->start_time = clip_start;
1541 state->duration = clip_stop - clip_start;
1543 ret = g_strdup (state->buf->str);
1544 g_string_truncate (state->buf, 0);
1545 unescape_newlines_br (ret);
1549 g_assert_not_reached ();
1555 parser_state_init (ParserState * state)
1557 GST_DEBUG ("initialising parser");
1560 g_string_truncate (state->buf, 0);
1562 state->buf = g_string_new (NULL);
1565 state->start_time = 0;
1566 state->duration = 0;
1567 state->max_duration = 0; /* no limit */
1569 state->segment = NULL;
1570 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1577 parser_state_dispose (GstSubParse * self, ParserState * state)
1580 g_string_free (state->buf, TRUE);
1584 g_free (state->vertical);
1585 state->vertical = NULL;
1586 g_free (state->alignment);
1587 state->alignment = NULL;
1589 if (state->user_data) {
1590 switch (self->parser_type) {
1591 case GST_SUB_PARSE_FORMAT_QTTEXT:
1592 qttext_context_deinit (state);
1594 case GST_SUB_PARSE_FORMAT_SAMI:
1595 sami_context_deinit (state);
1601 state->allowed_tags = NULL;
1607 gst_sub_parse_format_autodetect (GstSubParse * self)
1610 GstSubParseFormat format;
1612 if (strlen (self->textbuf->str) < 6) {
1613 GST_DEBUG ("File too small to be a subtitles file");
1617 data = g_strndup (self->textbuf->str, 35);
1618 format = gst_sub_parse_data_format_autodetect (data);
1621 self->parser_type = format;
1622 self->subtitle_codec = gst_sub_parse_get_format_description (format);
1623 parser_state_init (&self->state);
1624 self->state.allowed_tags = NULL;
1627 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1628 self->parse_line = parse_mdvdsub;
1629 return gst_caps_new_simple ("text/x-raw",
1630 "format", G_TYPE_STRING, "pango-markup", NULL);
1631 case GST_SUB_PARSE_FORMAT_SUBRIP:
1632 self->state.allowed_tags = (gpointer) allowed_srt_tags;
1633 self->state.allows_tag_attributes = FALSE;
1634 self->parse_line = parse_subrip;
1635 return gst_caps_new_simple ("text/x-raw",
1636 "format", G_TYPE_STRING, "pango-markup", NULL);
1637 case GST_SUB_PARSE_FORMAT_MPSUB:
1638 self->parse_line = parse_mpsub;
1639 return gst_caps_new_simple ("text/x-raw",
1640 "format", G_TYPE_STRING, "utf8", NULL);
1641 case GST_SUB_PARSE_FORMAT_SAMI:
1642 self->parse_line = parse_sami;
1643 sami_context_init (&self->state);
1644 return gst_caps_new_simple ("text/x-raw",
1645 "format", G_TYPE_STRING, "pango-markup", NULL);
1646 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1647 self->parse_line = parse_tmplayer;
1648 self->state.max_duration = 5 * GST_SECOND;
1649 return gst_caps_new_simple ("text/x-raw",
1650 "format", G_TYPE_STRING, "utf8", NULL);
1651 case GST_SUB_PARSE_FORMAT_MPL2:
1652 self->parse_line = parse_mpl2;
1653 return gst_caps_new_simple ("text/x-raw",
1654 "format", G_TYPE_STRING, "pango-markup", NULL);
1655 case GST_SUB_PARSE_FORMAT_DKS:
1656 self->parse_line = parse_dks;
1657 return gst_caps_new_simple ("text/x-raw",
1658 "format", G_TYPE_STRING, "utf8", NULL);
1659 case GST_SUB_PARSE_FORMAT_VTT:
1660 self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1661 self->state.allows_tag_attributes = TRUE;
1662 self->parse_line = parse_webvtt;
1663 return gst_caps_new_simple ("text/x-raw",
1664 "format", G_TYPE_STRING, "pango-markup", NULL);
1665 case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1666 self->parse_line = parse_subviewer;
1667 return gst_caps_new_simple ("text/x-raw",
1668 "format", G_TYPE_STRING, "utf8", NULL);
1669 case GST_SUB_PARSE_FORMAT_QTTEXT:
1670 self->parse_line = parse_qttext;
1671 qttext_context_init (&self->state);
1672 return gst_caps_new_simple ("text/x-raw",
1673 "format", G_TYPE_STRING, "pango-markup", NULL);
1674 case GST_SUB_PARSE_FORMAT_LRC:
1675 self->parse_line = parse_lrc;
1676 return gst_caps_new_simple ("text/x-raw",
1677 "format", G_TYPE_STRING, "utf8", NULL);
1678 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1680 GST_DEBUG ("no subtitle format detected");
1681 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1682 ("The input is not a valid/supported subtitle file"), (NULL));
1688 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1692 gchar *input = NULL;
1696 discont = GST_BUFFER_IS_DISCONT (buf);
1698 if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1699 GST_BUFFER_OFFSET (buf) != self->offset) {
1700 self->offset = GST_BUFFER_OFFSET (buf);
1705 GST_INFO ("discontinuity");
1706 /* flush the parser state */
1707 parser_state_init (&self->state);
1708 g_string_truncate (self->textbuf, 0);
1709 gst_adapter_clear (self->adapter);
1710 if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1711 sami_context_reset (&self->state);
1712 /* we could set a flag to make sure that the next buffer we push out also
1713 * has the DISCONT flag set, but there's no point really given that it's
1714 * subtitles which are discontinuous by nature. */
1717 self->offset += gst_buffer_get_size (buf);
1719 gst_adapter_push (self->adapter, buf);
1721 avail = gst_adapter_available (self->adapter);
1722 data = gst_adapter_map (self->adapter, avail);
1723 input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1725 if (input && consumed > 0) {
1726 self->textbuf = g_string_append (self->textbuf, input);
1727 gst_adapter_unmap (self->adapter);
1728 gst_adapter_flush (self->adapter, consumed);
1730 gst_adapter_unmap (self->adapter);
1738 xml_text (GMarkupParseContext * context,
1739 const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1741 gchar **accum = (gchar **) user_data;
1745 concat = g_strconcat (*accum, text, NULL);
1749 *accum = g_strdup (text);
1754 strip_pango_markup (gchar * markup, GError ** error)
1756 GMarkupParser parser = { 0, };
1757 GMarkupParseContext *context;
1758 gchar *accum = NULL;
1760 parser.text = xml_text;
1761 context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1763 g_markup_parse_context_parse (context, "<root>", 6, NULL);
1764 g_markup_parse_context_parse (context, markup, strlen (markup), error);
1765 g_markup_parse_context_parse (context, "</root>", 7, NULL);
1769 g_markup_parse_context_end_parse (context, error);
1774 g_markup_parse_context_free (context);
1784 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1787 gboolean ret = FALSE;
1788 const GstStructure *s1, *s2;
1790 caps = gst_pad_get_allowed_caps (self->srcpad);
1792 s1 = gst_caps_get_structure (preferred, 0);
1794 if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1795 GstCaps *intersected = gst_caps_intersect (caps, preferred);
1796 gst_caps_unref (caps);
1800 caps = gst_caps_fixate (caps);
1802 if (gst_caps_is_empty (caps)) {
1806 s2 = gst_caps_get_structure (caps, 0);
1808 self->strip_pango_markup =
1809 !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1810 && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1812 if (self->strip_pango_markup) {
1813 GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1816 ret = gst_pad_set_caps (self->srcpad, caps);
1819 gst_caps_unref (caps);
1823 static GstFlowReturn
1824 check_initial_events (GstSubParse * self)
1826 gboolean need_tags = FALSE;
1828 /* make sure we know the format */
1829 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1832 if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1833 return GST_FLOW_NOT_NEGOTIATED;
1836 if (!gst_sub_parse_negotiate (self, preferred)) {
1837 gst_caps_unref (preferred);
1838 return GST_FLOW_NOT_NEGOTIATED;
1841 gst_caps_unref (preferred);
1846 /* Push newsegment if needed */
1847 if (self->need_segment) {
1848 GstEvent *segment_event = gst_event_new_segment (&self->segment);
1849 GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1852 gst_event_set_seqnum (segment_event, self->segment_seqnum);
1853 gst_pad_push_event (self->srcpad, segment_event);
1854 self->need_segment = FALSE;
1859 if (self->subtitle_codec != NULL) {
1862 tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1864 gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1871 static GstFlowReturn
1872 handle_buffer (GstSubParse * self, GstBuffer * buf)
1874 GstFlowReturn ret = GST_FLOW_OK;
1875 gchar *line, *subtitle;
1876 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
1877 GstMessage *m = NULL;
1879 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1880 GstClockTime fragment_timestamp = GST_CLOCK_TIME_NONE;
1883 GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT, buf);
1885 if (self->first_buffer) {
1888 gst_buffer_map (buf, &map, GST_MAP_READ);
1889 self->detected_encoding =
1890 gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1891 gst_buffer_unmap (buf, &map);
1892 self->first_buffer = FALSE;
1893 self->state.fps_n = self->fps_n;
1894 self->state.fps_d = self->fps_d;
1896 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1897 if (GST_BUFFER_IS_DISCONT (buf) && GST_BUFFER_PTS_IS_VALID (buf))
1898 fragment_timestamp = GST_BUFFER_PTS (buf);
1901 feed_textbuf (self, buf);
1903 ret = check_initial_events (self);
1904 if (ret != GST_FLOW_OK)
1907 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1908 if (self->parser_type == GST_SUB_PARSE_FORMAT_VTT)
1909 send_fragment_timestamp_event (self, fragment_timestamp);
1912 while (!self->flushing && (line = get_next_line (self))) {
1915 /* Set segment on our parser state machine */
1916 self->state.segment = &self->segment;
1917 /* Now parse the line, out of segment lines will just return NULL */
1918 GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1920 subtitle = self->parse_line (&self->state, line + offset);
1922 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
1923 if (!self->state.langlist_msg_posted && self->state.language_list) {
1924 m = gst_message_new_element (GST_OBJECT_CAST (self),
1925 gst_structure_new ("Ext_Sub_Language_List", "lang_list",
1926 G_TYPE_POINTER, self->state.language_list, NULL));
1928 gst_element_post_message (GST_ELEMENT_CAST (self), m);
1929 self->state.langlist_msg_posted = TRUE;
1930 GST_DEBUG_OBJECT (self, "curr lang as : %s ",
1931 GST_STR_NULL (self->state.current_language));
1937 if (self->strip_pango_markup) {
1938 GError *error = NULL;
1941 if ((stripped = strip_pango_markup (subtitle, &error))) {
1943 subtitle = stripped;
1945 GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1950 subtitle_len = strlen (subtitle);
1952 /* +1 for terminating NUL character */
1953 buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1955 /* copy terminating NUL character as well */
1956 gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1957 gst_buffer_set_size (buf, subtitle_len);
1959 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1960 GST_BUFFER_DURATION (buf) = self->state.duration;
1962 /* in some cases (e.g. tmplayer) we can only determine the duration
1963 * of a text chunk from the timestamp of the next text chunk; in those
1964 * cases, we probably want to limit the duration to something
1965 * reasonable, so we don't end up showing some text for e.g. 40 seconds
1966 * just because nothing else is being said during that time */
1967 if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1968 if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1969 GST_BUFFER_DURATION (buf) = self->state.max_duration;
1972 self->segment.position = self->state.start_time;
1974 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1975 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1976 GST_TIME_ARGS (self->state.duration));
1978 g_free (self->state.vertical);
1979 self->state.vertical = NULL;
1980 g_free (self->state.alignment);
1981 self->state.alignment = NULL;
1983 ret = gst_pad_push (self->srcpad, buf);
1985 /* move this forward (the tmplayer parser needs this) */
1986 if (self->state.duration != GST_CLOCK_TIME_NONE)
1987 self->state.start_time += self->state.duration;
1992 if (ret != GST_FLOW_OK) {
1993 GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
2002 static GstFlowReturn
2003 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
2008 self = GST_SUBPARSE (parent);
2010 ret = handle_buffer (self, buf);
2016 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2018 GstSubParse *self = GST_SUBPARSE (parent);
2019 gboolean ret = FALSE;
2021 GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
2023 switch (GST_EVENT_TYPE (event)) {
2024 case GST_EVENT_STREAM_GROUP_DONE:
2025 case GST_EVENT_EOS:{
2026 /* Make sure the last subrip chunk is pushed out even
2027 * if the file does not have an empty line at the end */
2028 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
2029 self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
2030 self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
2031 self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
2032 self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
2033 gchar term_chars[] = { '\n', '\n', '\0' };
2034 GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
2036 GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
2037 GST_EVENT_TYPE_NAME (event));
2039 gst_buffer_fill (buf, 0, term_chars, 3);
2040 gst_buffer_set_size (buf, 2);
2042 GST_BUFFER_OFFSET (buf) = self->offset;
2043 gst_sub_parse_chain (pad, parent, buf);
2045 ret = gst_pad_event_default (pad, parent, event);
2048 case GST_EVENT_SEGMENT:
2050 const GstSegment *s;
2052 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
2053 if (self->first_buffer) {
2054 if (!SUBPARSE_SEEK_TRYLOCK (self)) {
2055 /* new seeking request is in process */
2056 GST_WARNING_OBJECT (self, "ignore the old newsegment event");
2058 gst_event_unref (event);
2062 SUBPARSE_SEEK_LOCK (self);
2066 gst_event_parse_segment (event, &s);
2067 if (s->format == GST_FORMAT_TIME)
2068 gst_event_copy_segment (event, &self->segment);
2069 GST_DEBUG_OBJECT (self, "newsegment (%s)",
2070 gst_format_get_name (self->segment.format));
2071 self->segment_seqnum = gst_event_get_seqnum (event);
2073 /* if not time format, we'll either start with a 0 timestamp anyway or
2074 * it's following a seek in which case we'll have saved the requested
2075 * seek segment and don't want to overwrite it (remember that on a seek
2076 * we always just seek back to the start in BYTES format and just throw
2077 * away all text that's before the requested position; if the subtitles
2078 * come from an upstream demuxer, it won't be able to handle our BYTES
2079 * seek request and instead send us a newsegment from the seek request
2080 * it received via its video pads instead, so all is fine then too) */
2082 gst_event_unref (event);
2083 /* in either case, let's not simply discard this event;
2084 * trigger sending of the saved requested seek segment
2085 * or the one taken here from upstream */
2086 self->need_segment = TRUE;
2088 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
2089 SUBPARSE_SEEK_UNLOCK (self);
2096 ret = check_initial_events (self);
2097 if (ret == GST_FLOW_OK) {
2098 ret = gst_pad_event_default (pad, parent, event);
2100 gst_event_unref (event);
2104 case GST_EVENT_FLUSH_START:
2106 self->flushing = TRUE;
2108 ret = gst_pad_event_default (pad, parent, event);
2111 case GST_EVENT_FLUSH_STOP:
2113 self->flushing = FALSE;
2115 ret = gst_pad_event_default (pad, parent, event);
2119 ret = gst_pad_event_default (pad, parent, event);
2127 static GstStateChangeReturn
2128 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
2130 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2131 GstSubParse *self = GST_SUBPARSE (element);
2133 switch (transition) {
2134 case GST_STATE_CHANGE_READY_TO_PAUSED:
2135 /* format detection will init the parser state */
2137 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
2138 self->strip_pango_markup = FALSE;
2139 self->valid_utf8 = TRUE;
2140 self->first_buffer = TRUE;
2141 g_free (self->detected_encoding);
2142 self->detected_encoding = NULL;
2143 g_string_truncate (self->textbuf, 0);
2144 gst_adapter_clear (self->adapter);
2150 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2151 if (ret == GST_STATE_CHANGE_FAILURE)
2154 switch (transition) {
2155 case GST_STATE_CHANGE_PAUSED_TO_READY:
2156 parser_state_dispose (self, &self->state);
2157 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;