webrtc/nice: Support domain name as connection-address of ICE candidate
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / gst / subparse / gstsubparse.c
1 /* GStreamer
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>
7  *
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.
12  *
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.
17  *
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.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <glib.h>
33
34 #include "gstsubparse.h"
35
36 #include "gstssaparse.h"
37 #include "samiparse.h"
38 #include "tmplayerparse.h"
39 #include "mpl2parse.h"
40 #include "qttextparse.h"
41 #include "gstsubparseelements.h"
42
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))
48 #endif
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 };
54
55 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
56 #define DEFAULT_CURRENT_LANGUAGE   NULL
57 #endif
58 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
59 #define DEFAULT_DROP_OUT_OF_SEGMENT TRUE
60 #endif
61 enum
62 {
63   PROP_0,
64   PROP_ENCODING,
65   PROP_VIDEOFPS,
66 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
67   PROP_EXTSUB_CURRENT_LANGUAGE,
68 #endif
69 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
70   PROP_DROP_OUT_OF_SEGMENT,
71 #endif
72 };
73 #ifdef TIZEN_FEATURE_HLS_WEBVTT
74 #define MPEGTIME_TO_GSTTIME(t) ((t) * (guint64)100000 / 9)
75 #endif
76
77 static void
78 gst_sub_parse_set_property (GObject * object, guint prop_id,
79     const GValue * value, GParamSpec * pspec);
80 static void
81 gst_sub_parse_get_property (GObject * object, guint prop_id,
82     GValue * value, GParamSpec * pspec);
83
84
85 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
86     GST_PAD_SINK,
87     GST_PAD_ALWAYS,
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")
92     );
93
94 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
95     GST_PAD_SRC,
96     GST_PAD_ALWAYS,
97     GST_STATIC_CAPS ("text/x-raw, format= { pango-markup, utf8 }")
98     );
99
100
101 static gboolean gst_sub_parse_src_event (GstPad * pad, GstObject * parent,
102     GstEvent * event);
103 static gboolean gst_sub_parse_src_query (GstPad * pad, GstObject * parent,
104     GstQuery * query);
105 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstObject * parent,
106     GstEvent * event);
107
108 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
109     GstStateChange transition);
110
111 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent,
112     GstBuffer * buf);
113 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
114 static gboolean gst_sub_parse_check_byte_seekability (GstSubParse * subparse);
115 #endif
116 #define gst_sub_parse_parent_class parent_class
117 G_DEFINE_TYPE (GstSubParse, gst_sub_parse, GST_TYPE_ELEMENT);
118
119 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (subparse, "subparse",
120     GST_RANK_PRIMARY, GST_TYPE_SUBPARSE, sub_parse_element_init (plugin))
121
122
123      static void gst_sub_parse_dispose (GObject * object)
124 {
125   GstSubParse *subparse = GST_SUBPARSE (object);
126
127   GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
128
129   if (subparse->encoding) {
130     g_free (subparse->encoding);
131     subparse->encoding = NULL;
132   }
133
134   if (subparse->detected_encoding) {
135     g_free (subparse->detected_encoding);
136     subparse->detected_encoding = NULL;
137   }
138
139   if (subparse->adapter) {
140     g_object_unref (subparse->adapter);
141     subparse->adapter = NULL;
142   }
143
144   if (subparse->textbuf) {
145     g_string_free (subparse->textbuf, TRUE);
146     subparse->textbuf = NULL;
147   }
148 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
149   g_free (subparse->state.current_language);
150   subparse->state.current_language = NULL;
151
152   g_mutex_clear (&subparse->seek_lock);
153 #endif
154   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
155 }
156
157 static void
158 gst_sub_parse_class_init (GstSubParseClass * klass)
159 {
160   GObjectClass *object_class = G_OBJECT_CLASS (klass);
161   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
162
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;
166
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>");
174
175   element_class->change_state = gst_sub_parse_change_state;
176
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));
184
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));
198 #endif
199
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));
207 #endif
208 }
209
210 static void
211 gst_sub_parse_init (GstSubParse * subparse)
212 {
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);
219
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);
226
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 ();
237
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);
245 #endif
246 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
247   subparse->state.drop_out_of_segment = DEFAULT_DROP_OUT_OF_SEGMENT;
248 #endif
249 }
250
251 /*
252  * Source pad functions.
253  */
254
255 static gboolean
256 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
257 {
258   GstSubParse *self = GST_SUBPARSE (parent);
259   gboolean ret = FALSE;
260
261   GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
262
263   switch (GST_QUERY_TYPE (query)) {
264     case GST_QUERY_POSITION:{
265       GstFormat fmt;
266
267       gst_query_parse_position (query, &fmt, NULL);
268       if (fmt != GST_FORMAT_TIME) {
269         ret = gst_pad_peer_query (self->sinkpad, query);
270       } else {
271         ret = TRUE;
272         gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
273       }
274       break;
275     }
276     case GST_QUERY_SEEKING:
277     {
278       GstFormat fmt;
279       gboolean seekable = FALSE;
280
281       ret = TRUE;
282
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);
286
287         seekable = gst_pad_peer_query (self->sinkpad, peerquery);
288         if (seekable)
289           gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
290         gst_query_unref (peerquery);
291       }
292
293       gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
294       break;
295     }
296     default:
297       ret = gst_pad_query_default (pad, parent, query);
298       break;
299   }
300
301   return ret;
302 }
303
304 static gboolean
305 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
306 {
307   GstSubParse *self = GST_SUBPARSE (parent);
308   gboolean ret = FALSE;
309
310   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
311
312   switch (GST_EVENT_TYPE (event)) {
313     case GST_EVENT_SEEK:
314     {
315       GstFormat format;
316       GstSeekFlags flags;
317       GstSeekType start_type, stop_type;
318       gint64 start, stop;
319       gdouble rate;
320       gboolean update;
321
322       gst_event_parse_seek (event, &rate, &format, &flags,
323           &start_type, &start, &stop_type, &stop);
324
325       if (format != GST_FORMAT_TIME) {
326         GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
327         gst_event_unref (event);
328         goto beach;
329       }
330 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
331       if (!gst_sub_parse_check_byte_seekability (self)) {
332         ret = gst_pad_event_default (pad, parent, event);
333         break;
334       }
335
336       SUBPARSE_SEEK_LOCK (self);
337 #endif
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));
343
344       if (ret) {
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);
348
349         GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
350             &self->segment);
351
352         /* will mark need_segment when receiving segment from upstream,
353          * after FLUSH and all that has happened,
354          * rather than racing with chain */
355       } else {
356         GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
357       }
358
359 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
360       SUBPARSE_SEEK_UNLOCK (self);
361 #endif
362
363       gst_event_unref (event);
364       break;
365     }
366     default:
367       ret = gst_pad_event_default (pad, parent, event);
368       break;
369   }
370
371 beach:
372   return ret;
373 }
374
375 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
376 static gboolean
377 gst_sub_parse_check_byte_seekability (GstSubParse * subparse)
378 {
379   GstQuery *query;
380   gboolean seekable = FALSE;
381
382   query = gst_query_new_seeking (GST_FORMAT_BYTES);
383
384   if (gst_pad_peer_query (subparse->sinkpad, query)) {
385     gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
386   } else {
387     GST_DEBUG_OBJECT (subparse, "seeking query failed");
388   }
389
390   gst_query_unref (query);
391
392   GST_INFO_OBJECT (subparse, "byte seekable: %d", seekable);
393
394   return seekable;
395 }
396 #endif
397
398 static void
399 gst_sub_parse_set_property (GObject * object, guint prop_id,
400     const GValue * value, GParamSpec * pspec)
401 {
402   GstSubParse *subparse = GST_SUBPARSE (object);
403
404   GST_OBJECT_LOCK (subparse);
405   switch (prop_id) {
406     case PROP_ENCODING:
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));
411       break;
412     case PROP_VIDEOFPS:
413     {
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,
417           subparse->fps_d);
418
419       if (!subparse->state.have_internal_fps) {
420         subparse->state.fps_n = subparse->fps_n;
421         subparse->state.fps_d = subparse->fps_d;
422       }
423       break;
424     }
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);
432       break;
433 #endif
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);
439       break;
440 #endif
441     default:
442       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
443       break;
444   }
445   GST_OBJECT_UNLOCK (subparse);
446 }
447
448 static void
449 gst_sub_parse_get_property (GObject * object, guint prop_id,
450     GValue * value, GParamSpec * pspec)
451 {
452   GstSubParse *subparse = GST_SUBPARSE (object);
453
454   GST_OBJECT_LOCK (subparse);
455   switch (prop_id) {
456     case PROP_ENCODING:
457       g_value_set_string (value, subparse->encoding);
458       break;
459     case PROP_VIDEOFPS:
460       gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
461       break;
462 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
463     case PROP_EXTSUB_CURRENT_LANGUAGE:
464       g_value_set_string (value, subparse->state.current_language);
465       break;
466 #endif
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);
470       break;
471 #endif
472     default:
473       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
474       break;
475   }
476   GST_OBJECT_UNLOCK (subparse);
477 }
478
479 static const gchar *
480 gst_sub_parse_get_format_description (GstSubParseFormat format)
481 {
482   switch (format) {
483     case GST_SUB_PARSE_FORMAT_MDVDSUB:
484       return "MicroDVD";
485     case GST_SUB_PARSE_FORMAT_SUBRIP:
486       return "SubRip";
487     case GST_SUB_PARSE_FORMAT_MPSUB:
488       return "MPSub";
489     case GST_SUB_PARSE_FORMAT_SAMI:
490       return "SAMI";
491     case GST_SUB_PARSE_FORMAT_TMPLAYER:
492       return "TMPlayer";
493     case GST_SUB_PARSE_FORMAT_MPL2:
494       return "MPL2";
495     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
496       return "SubViewer";
497     case GST_SUB_PARSE_FORMAT_DKS:
498       return "DKS";
499     case GST_SUB_PARSE_FORMAT_VTT:
500       return "WebVTT";
501     case GST_SUB_PARSE_FORMAT_QTTEXT:
502       return "QTtext";
503     case GST_SUB_PARSE_FORMAT_LRC:
504       return "LRC";
505     default:
506     case GST_SUB_PARSE_FORMAT_UNKNOWN:
507       break;
508   }
509   return NULL;
510 }
511
512
513
514
515
516 static gchar *
517 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
518     gsize * consumed)
519 {
520   const gchar *encoding;
521   GError *err = NULL;
522   gchar *ret = NULL;
523
524   *consumed = 0;
525
526   /* First try any detected encoding */
527   if (self->detected_encoding) {
528     ret =
529         gst_sub_parse_gst_convert_to_utf8 (str, len, self->detected_encoding,
530         consumed, &err);
531
532     if (!err)
533       return ret;
534
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);
540   }
541
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");
546       *consumed = len;
547       return g_strndup (str, len);
548     }
549     GST_INFO_OBJECT (self, "invalid UTF-8!");
550     self->valid_utf8 = FALSE;
551   }
552
553   /* Else try fallback */
554   encoding = self->encoding;
555   if (encoding == NULL || *encoding == '\0') {
556     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
557   }
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";
563     }
564   }
565
566   ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
567
568   if (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);
572
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);
580     } else
581 #endif
582     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
583     ret =
584         gst_sub_parse_gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed,
585         NULL);
586   }
587
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" : "");
591
592   return ret;
593 }
594
595 static gchar *
596 get_next_line (GstSubParse * self)
597 {
598   char *line = NULL;
599   const char *line_end;
600   int line_len;
601   gboolean have_r = FALSE;
602
603   line_end = strchr (self->textbuf->str, '\n');
604
605   if (!line_end) {
606     /* end-of-line not found; return for more data */
607     return NULL;
608   }
609
610   /* get rid of '\r' */
611   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
612     line_end--;
613     have_r = TRUE;
614   }
615
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));
620   return line;
621 }
622
623 static gchar *
624 parse_mdvdsub (ParserState * state, const gchar * line)
625 {
626   const gchar *line_split;
627   gchar *line_chunk;
628   guint start_frame, end_frame;
629   guint64 clip_start = 0, clip_stop = 0;
630   gboolean in_seg = FALSE;
631   GString *markup;
632   gchar *ret;
633
634   /* style variables */
635   gboolean italic;
636   gboolean bold;
637   guint fontsize;
638   gdouble fps = 0.0;
639
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);
643     return NULL;
644   }
645
646   /* skip the {%u}{%u} part */
647   line = strchr (line, '}') + 1;
648   line = strchr (line, '}') + 1;
649
650   /* see if there's a first line with a framerate */
651   if (start_frame == 1 && end_frame == 1) {
652     gchar *rest, *end = NULL;
653
654     rest = g_strdup (line);
655     g_strdelimit (rest, ",", '.');
656     fps = g_ascii_strtod (rest, &end);
657     if (end != rest) {
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,
660           state->fps_d, rest);
661     }
662     g_free (rest);
663     return NULL;
664   }
665
666   state->start_time =
667       gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
668       state->fps_n);
669   state->duration =
670       gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
671       state->fps_n);
672
673   /* Check our segment start/stop */
674 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
675   if (state->drop_out_of_segment) {
676 #endif
677   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
678       state->start_time, state->start_time + state->duration, &clip_start,
679       &clip_stop);
680
681   /* No need to parse that text if it's out of segment */
682   if (in_seg) {
683     state->start_time = clip_start;
684     state->duration = clip_stop - clip_start;
685   } else {
686     return NULL;
687   }
688 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
689   }
690 #endif
691
692   markup = g_string_new (NULL);
693   while (1) {
694     italic = FALSE;
695     bold = FALSE;
696     fontsize = 0;
697     /* parse style markup */
698     if (strncmp (line, "{y:i}", 5) == 0) {
699       italic = TRUE;
700       line = strchr (line, '}') + 1;
701     }
702     if (strncmp (line, "{y:b}", 5) == 0) {
703       bold = TRUE;
704       line = strchr (line, '}') + 1;
705     }
706     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
707       line = strchr (line, '}') + 1;
708     }
709     /* forward slashes at beginning/end signify italics too */
710     if (g_str_has_prefix (line, "/")) {
711       italic = TRUE;
712       ++line;
713     }
714     if ((line_split = strchr (line, '|')))
715       line_chunk = g_markup_escape_text (line, line_split - line);
716     else
717       line_chunk = g_markup_escape_text (line, strlen (line));
718
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';
723     }
724
725     markup = g_string_append (markup, "<span");
726     if (italic)
727       g_string_append (markup, " style=\"italic\"");
728     if (bold)
729       g_string_append (markup, " weight=\"bold\"");
730     if (fontsize)
731       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
732     g_string_append_printf (markup, ">%s</span>", line_chunk);
733     g_free (line_chunk);
734     if (line_split) {
735       g_string_append (markup, "\n");
736       line = line_split + 1;
737     } else {
738       break;
739     }
740   }
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);
745   return ret;
746 }
747
748 static void
749 strip_trailing_newlines (gchar * txt)
750 {
751   if (txt) {
752     guint len;
753
754     len = strlen (txt);
755     while (len > 1 && txt[len - 1] == '\n') {
756       txt[len - 1] = '\0';
757       --len;
758     }
759   }
760 }
761
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) */
767 static void
768 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
769     gboolean allows_tag_attributes)
770 {
771   gchar *res;
772   GRegex *tag_regex;
773   gchar *allowed_tags_pattern, *search_pattern;
774   const gchar *replace_pattern;
775
776   /* No processing needed if no escaped tag marker found in the string. */
777   if (strstr (txt, "&lt;") == NULL)
778     return;
779
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 ("&lt;(/)?\\ *(%s)(%s)&gt;",
785       allowed_tags_pattern, ATTRIBUTE_REGEX);
786   /* And unescape appropriately */
787   if (allows_tag_attributes) {
788     replace_pattern = "<\\1\\2\\3>";
789   } else {
790     replace_pattern = "<\\1\\2>";
791   }
792
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);
796
797   /* res will always be shorter than the input or identical, so this
798    * copy is OK */
799   strcpy (txt, res);
800
801   g_free (res);
802   g_free (search_pattern);
803   g_free (allowed_tags_pattern);
804
805   g_regex_unref (tag_regex);
806 }
807
808
809 static gboolean
810 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
811 {
812   gchar *tag, saved;
813
814   tag = start + strlen ("&lt;");
815   if (*tag == '/')
816     ++tag;
817
818   if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
819     return FALSE;
820
821   saved = *stop;
822   *stop = '\0';
823   GST_LOG ("removing unhandled tag '%s'", start);
824   *stop = saved;
825   memmove (start, stop, strlen (stop) + 1);
826   return TRUE;
827 }
828
829 /* remove tags we haven't explicitly allowed earlier on, like font tags
830  * for example */
831 static void
832 subrip_remove_unhandled_tags (gchar * txt)
833 {
834   gchar *pos, *gt;
835
836   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
837     if (strncmp (pos, "&lt;", 4) == 0 && (gt = strstr (pos + 4, "&gt;"))) {
838       if (subrip_remove_unhandled_tag (pos, gt + strlen ("&gt;")))
839         --pos;
840     }
841   }
842 }
843
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. */
849 static void
850 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
851 {
852   gchar *cur, *next_tag;
853   GPtrArray *open_tags = NULL;
854   guint num_open_tags = 0;
855   const gchar *iter_tag;
856   guint offset = 0;
857   guint index;
858   gchar *cur_tag;
859   gchar *end_tag;
860   GRegex *tag_regex;
861   GMatchInfo *match_info;
862   gchar **allowed_tags = (gchar **) allowed_tags_ptr;
863
864   g_assert (*p_txt != NULL);
865
866   open_tags = g_ptr_array_new_with_free_func (g_free);
867   cur = *p_txt;
868   while (*cur != '\0') {
869     next_tag = strchr (cur, '<');
870     if (next_tag == NULL)
871       break;
872     offset = 0;
873     index = 0;
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);
880
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);
887         }
888         g_free (word);
889       }
890       g_match_info_free (match_info);
891       g_regex_unref (tag_regex);
892       g_free (cur_tag);
893       index++;
894       if (offset) {
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));
897         ++num_open_tags;
898         break;
899       }
900     }
901
902     if (offset) {
903       next_tag += offset;
904       cur = next_tag;
905       continue;
906     }
907
908     if (*next_tag == '<' && *(next_tag + 1) == '/') {
909       end_tag = strchr (next_tag, '>');
910       if (end_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));
919           cur = next_tag;
920           continue;
921         } else {
922           --num_open_tags;
923           g_ptr_array_remove_index (open_tags, num_open_tags);
924           cur = end_tag + 1;
925           continue;
926         }
927       }
928     }
929     ++next_tag;
930     cur = next_tag;
931   }
932
933   if (num_open_tags > 0) {
934     GString *s;
935
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, '>');
944       --num_open_tags;
945     }
946     g_free (*p_txt);
947     *p_txt = g_string_free (s, FALSE);
948   }
949   g_ptr_array_free (open_tags, TRUE);
950 }
951
952 static gboolean
953 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
954 {
955   gchar s[128] = { '\0', };
956   gchar *end, *p;
957   guint hour, min, sec, msec, len;
958
959   while (*ts_string == ' ')
960     ++ts_string;
961
962   g_strlcpy (s, ts_string, sizeof (s));
963   if ((end = strstr (s, "-->")))
964     *end = '\0';
965   g_strchomp (s);
966
967   /* ms may be in these formats:
968    * hh:mm:ss,500 = 500ms
969    * hh:mm:ss,  5 =   5ms
970    * hh:mm:ss, 5  =  50ms
971    * hh:mm:ss, 50 =  50ms
972    * hh:mm:ss,5   = 500ms
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?)
977    */
978   g_strdelimit (s, " ", '0');
979   g_strdelimit (s, ".", ',');
980
981   /* make sure we have exactly three digits after he comma */
982   p = strchr (s, ',');
983   if (p == NULL) {
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);
987     return FALSE;
988   }
989
990   ++p;
991   len = strlen (p);
992   if (len > 3) {
993     p[3] = '\0';
994   } else
995     while (len < 3) {
996       g_strlcat (&p[len], "0", 2);
997       ++len;
998     }
999
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
1003      *
1004      * The hours component is optional with webVTT, for example
1005      * mm:ss,500 is a valid webVTT timestamp. When not present,
1006      * hours is 0.
1007      */
1008     hour = 0;
1009
1010     if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
1011       GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
1012       return FALSE;
1013     }
1014   }
1015
1016   *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
1017   return TRUE;
1018 }
1019
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
1024  */
1025 static void
1026 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
1027 {
1028   gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
1029   gint i = 0;
1030   gint16 text_position, text_size;
1031   gint16 line_position;
1032   gboolean vertical_found = FALSE;
1033   gboolean alignment_found = FALSE;
1034
1035   while (i < g_strv_length (splitted_settings)) {
1036     gboolean valid_tag = FALSE;
1037     switch (splitted_settings[i][0]) {
1038       case 'T':
1039         if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
1040                 &text_position) > 0) {
1041           state->text_position = (guint8) text_position;
1042           valid_tag = TRUE;
1043         }
1044         break;
1045       case 'D':
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);
1050           valid_tag = TRUE;
1051         }
1052         break;
1053       case 'L':
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;
1058             valid_tag = TRUE;
1059           }
1060         } else {
1061           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
1062                   &line_position) > 0) {
1063             state->line_number = line_position;
1064             valid_tag = TRUE;
1065           }
1066         }
1067         break;
1068       case 'S':
1069         if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
1070                 &text_size) > 0) {
1071           state->text_size = (guint8) text_size;
1072           valid_tag = TRUE;
1073         }
1074         break;
1075       case 'A':
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;
1080           valid_tag = TRUE;
1081         }
1082         break;
1083       default:
1084         break;
1085     }
1086     if (!valid_tag) {
1087       GST_LOG ("Invalid or unrecognised setting found: %s",
1088           splitted_settings[i]);
1089     }
1090     i++;
1091   }
1092   g_strfreev (splitted_settings);
1093   if (!vertical_found) {
1094     g_free (state->vertical);
1095     state->vertical = g_strdup ("");
1096   }
1097   if (!alignment_found) {
1098     g_free (state->alignment);
1099     state->alignment = g_strdup ("");
1100   }
1101 }
1102
1103 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1104 static void
1105 parse_timestamp_map (ParserState * state, const gchar * timestamp_map)
1106 {
1107   GstClockTime local = 0;
1108   guint64 mpegts = 0;
1109   gchar *local_start = NULL;
1110   gchar *mpegts_start = NULL;
1111
1112   if (!timestamp_map)
1113     return;
1114
1115   local_start = g_strrstr (timestamp_map, "LOCAL:");
1116   if (local_start)
1117     parse_subrip_time (local_start + strlen ("LOCAL:"), &local);
1118
1119   mpegts_start = g_strrstr (timestamp_map, "MPEGTS:");
1120   if (mpegts_start)
1121     mpegts = g_ascii_strtoull (mpegts_start + strlen ("MPEGTS:"), NULL, 10);
1122
1123   GST_LOG ("parsed local time %" GST_TIME_FORMAT " MPEGTS: %" G_GUINT64_FORMAT,
1124       GST_TIME_ARGS (local), mpegts);
1125
1126   state->local = local;
1127   state->mpegts = mpegts;
1128 }
1129
1130 static void
1131 send_fragment_timestamp_event (GstSubParse * self, GstClockTime timestamp)
1132 {
1133   GstEvent *event = NULL;
1134
1135   if (!GST_CLOCK_TIME_IS_VALID (timestamp))
1136     return;
1137
1138   GST_LOG ("send fragment_timestamp %" GST_TIME_FORMAT,
1139       GST_TIME_ARGS (timestamp));
1140
1141   event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
1142       gst_structure_new ("fragment_timestamp",
1143           "timestamp", G_TYPE_UINT64, timestamp, NULL));
1144
1145   gst_pad_push_event (self->srcpad, event);
1146 }
1147 #endif
1148
1149 static gchar *
1150 parse_subrip (ParserState * state, const gchar * line)
1151 {
1152   gchar *ret;
1153
1154   switch (state->state) {
1155     case 0:{
1156       char *endptr;
1157       guint64 id;
1158
1159       /* looking for a single integer as a Cue ID, but we
1160        * don't actually use it */
1161       errno = 0;
1162       id = g_ascii_strtoull (line, &endptr, 10);
1163       if (id == G_MAXUINT64 && errno == ERANGE)
1164         state->state = 1;
1165       else if (id == 0 && errno == EINVAL)
1166         state->state = 1;
1167       else if (endptr != line && *endptr == '\0')
1168         state->state = 1;
1169       return NULL;
1170     }
1171     case 1:
1172     {
1173       GstClockTime ts_start, ts_end;
1174       gchar *end_time;
1175
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) {
1183 #else
1184           state->start_time <= ts_end) {
1185 #endif
1186         state->state = 2;
1187         state->start_time = ts_start;
1188 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1189         state->start_time += MPEGTIME_TO_GSTTIME (state->mpegts) - state->local;
1190 #endif
1191         state->duration = ts_end - ts_start;
1192       } else {
1193         GST_DEBUG ("error parsing subrip time line '%s'", line);
1194         state->state = 0;
1195       }
1196       return NULL;
1197     }
1198     case 2:
1199     {
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) {
1203 #endif
1204       guint64 clip_start = 0, clip_stop = 0;
1205       gboolean in_seg = FALSE;
1206
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);
1211
1212       if (in_seg) {
1213         state->start_time = clip_start;
1214         state->duration = clip_stop - clip_start;
1215       } else {
1216         state->state = 0;
1217         return NULL;
1218       }
1219 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1220       }
1221 #endif
1222     }
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);
1230         state->state = 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);
1236         return ret;
1237       }
1238       return NULL;
1239     default:
1240       g_return_val_if_reached (NULL);
1241   }
1242 }
1243
1244 static gchar *
1245 parse_lrc (ParserState * state, const gchar * line)
1246 {
1247   gint m, s, c;
1248   const gchar *start;
1249   gint milli;
1250
1251   if (line[0] != '[')
1252     return NULL;
1253
1254   if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1255       sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1256     return NULL;
1257
1258   start = strchr (line, ']');
1259   if (start - line == 9)
1260     milli = 10;
1261   else
1262     milli = 1;
1263
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;
1268
1269   return g_strdup (start + 1);
1270 }
1271
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
1277  */
1278 static gchar *
1279 parse_webvtt (ParserState * state, const gchar * line)
1280 {
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;
1286     gchar *end_time;
1287     gchar *cue_settings = NULL;
1288
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) {
1294       state->state = 2;
1295       state->start_time = ts_start;
1296 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1297       state->start_time += MPEGTIME_TO_GSTTIME (state->mpegts) - state->local;
1298 #endif
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);
1305       state->state = 0;
1306 #endif
1307     } else {
1308       GST_DEBUG ("error parsing subrip time line '%s'", line);
1309       state->state = 0;
1310     }
1311
1312     state->text_position = 0;
1313     state->text_size = 0;
1314     state->line_position = 0;
1315     state->line_number = 0;
1316
1317     if (cue_settings)
1318       parse_webvtt_cue_settings (state, cue_settings + 1);
1319     else {
1320       g_free (state->vertical);
1321       state->vertical = g_strdup ("");
1322       g_free (state->alignment);
1323       state->alignment = g_strdup ("");
1324     }
1325
1326     return NULL;
1327   } else
1328     return parse_subrip (state, line);
1329 }
1330
1331 static void
1332 unescape_newlines_br (gchar * read)
1333 {
1334   gchar *write = read;
1335
1336   /* Replace all occurrences of '[br]' with a newline as version 2
1337    * of the subviewer format uses this for newlines */
1338
1339   if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1340     return;
1341
1342   do {
1343     if (strncmp (read, "[br]", 4) == 0) {
1344       *write = '\n';
1345       read += 4;
1346     } else {
1347       *write = *read;
1348       read++;
1349     }
1350     write++;
1351   } while (*read);
1352
1353   *write = '\0';
1354 }
1355
1356 static gchar *
1357 parse_subviewer (ParserState * state, const gchar * line)
1358 {
1359   guint h1, m1, s1, ms1;
1360   guint h2, m2, s2, ms2;
1361   gchar *ret;
1362
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 */
1366
1367   switch (state->state) {
1368     case 0:
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) {
1372         state->state = 1;
1373         state->start_time =
1374             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1375             ms1 * GST_MSECOND;
1376         state->duration =
1377             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1378             ms2 * GST_MSECOND - state->start_time;
1379       }
1380       return NULL;
1381     case 1:
1382     {
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) {
1386 #endif
1387       guint64 clip_start = 0, clip_stop = 0;
1388       gboolean in_seg = FALSE;
1389
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);
1394
1395       if (in_seg) {
1396         state->start_time = clip_start;
1397         state->duration = clip_stop - clip_start;
1398       } else {
1399         state->state = 0;
1400         return NULL;
1401       }
1402 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1403       }
1404 #endif
1405     }
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);
1415         state->state = 0;
1416         return ret;
1417       }
1418       return NULL;
1419     default:
1420       g_assert_not_reached ();
1421       return NULL;
1422   }
1423 }
1424
1425 static gchar *
1426 parse_mpsub (ParserState * state, const gchar * line)
1427 {
1428   gchar *ret;
1429   float t1, t2;
1430
1431   switch (state->state) {
1432     case 0:
1433       /* looking for two floats (offset, duration) */
1434       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1435         state->state = 1;
1436         state->start_time += state->duration + GST_SECOND * t1;
1437         state->duration = GST_SECOND * t2;
1438       }
1439       return NULL;
1440     case 1:
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) {
1444 #endif
1445       guint64 clip_start = 0, clip_stop = 0;
1446       gboolean in_seg = FALSE;
1447
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);
1452
1453       if (in_seg) {
1454         state->start_time = clip_start;
1455         state->duration = clip_stop - clip_start;
1456       } else {
1457         state->state = 0;
1458         return NULL;
1459       }
1460 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1461       }
1462 #endif
1463     }
1464       /* looking for subtitle text; empty line ends this
1465        * subtitle entry */
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);
1472         state->state = 0;
1473         return ret;
1474       }
1475       return NULL;
1476     default:
1477       g_assert_not_reached ();
1478       return NULL;
1479   }
1480 }
1481
1482 static const gchar *
1483 dks_skip_timestamp (const gchar * line)
1484 {
1485   while (*line && *line != ']')
1486     line++;
1487   if (*line == ']')
1488     line++;
1489   return line;
1490 }
1491
1492 static gchar *
1493 parse_dks (ParserState * state, const gchar * line)
1494 {
1495   guint h, m, s;
1496
1497   switch (state->state) {
1498     case 0:
1499       /* Looking for the start time and text */
1500       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1501         const gchar *text;
1502         state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1503         text = dks_skip_timestamp (line);
1504         if (*text) {
1505           state->state = 1;
1506           g_string_append (state->buf, text);
1507         }
1508       }
1509       return NULL;
1510     case 1:
1511     {
1512       guint64 clip_start = 0, clip_stop = 0;
1513       gboolean in_seg;
1514       gchar *ret;
1515
1516       /* Looking for the end time */
1517       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1518         state->state = 0;
1519         state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1520             state->start_time;
1521       } else {
1522         GST_WARNING ("Failed to parse subtitle end time");
1523         return NULL;
1524       }
1525 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1526       if (state->drop_out_of_segment) {
1527 #endif
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);
1532
1533       if (!in_seg) {
1534         return NULL;
1535       }
1536 #ifdef TIZEN_FEATURE_SUBPARSE_DROP_OUT_OF_SEGMENT
1537       }
1538 #endif
1539
1540       state->start_time = clip_start;
1541       state->duration = clip_stop - clip_start;
1542
1543       ret = g_strdup (state->buf->str);
1544       g_string_truncate (state->buf, 0);
1545       unescape_newlines_br (ret);
1546       return ret;
1547     }
1548     default:
1549       g_assert_not_reached ();
1550       return NULL;
1551   }
1552 }
1553
1554 static void
1555 parser_state_init (ParserState * state)
1556 {
1557   GST_DEBUG ("initialising parser");
1558
1559   if (state->buf) {
1560     g_string_truncate (state->buf, 0);
1561   } else {
1562     state->buf = g_string_new (NULL);
1563   }
1564
1565   state->start_time = 0;
1566   state->duration = 0;
1567   state->max_duration = 0;      /* no limit */
1568   state->state = 0;
1569   state->segment = NULL;
1570 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1571   state->local = 0;
1572   state->mpegts = 0;
1573 #endif
1574 }
1575
1576 static void
1577 parser_state_dispose (GstSubParse * self, ParserState * state)
1578 {
1579   if (state->buf) {
1580     g_string_free (state->buf, TRUE);
1581     state->buf = NULL;
1582   }
1583
1584   g_free (state->vertical);
1585   state->vertical = NULL;
1586   g_free (state->alignment);
1587   state->alignment = NULL;
1588
1589   if (state->user_data) {
1590     switch (self->parser_type) {
1591       case GST_SUB_PARSE_FORMAT_QTTEXT:
1592         qttext_context_deinit (state);
1593         break;
1594       case GST_SUB_PARSE_FORMAT_SAMI:
1595         sami_context_deinit (state);
1596         break;
1597       default:
1598         break;
1599     }
1600   }
1601   state->allowed_tags = NULL;
1602 }
1603
1604
1605
1606 static GstCaps *
1607 gst_sub_parse_format_autodetect (GstSubParse * self)
1608 {
1609   gchar *data;
1610   GstSubParseFormat format;
1611
1612   if (strlen (self->textbuf->str) < 6) {
1613     GST_DEBUG ("File too small to be a subtitles file");
1614     return NULL;
1615   }
1616
1617   data = g_strndup (self->textbuf->str, 35);
1618   format = gst_sub_parse_data_format_autodetect (data);
1619   g_free (data);
1620
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;
1625
1626   switch (format) {
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:
1679     default:
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));
1683       return NULL;
1684   }
1685 }
1686
1687 static void
1688 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1689 {
1690   gboolean discont;
1691   gsize consumed;
1692   gchar *input = NULL;
1693   const guint8 *data;
1694   gsize avail;
1695
1696   discont = GST_BUFFER_IS_DISCONT (buf);
1697
1698   if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1699       GST_BUFFER_OFFSET (buf) != self->offset) {
1700     self->offset = GST_BUFFER_OFFSET (buf);
1701     discont = TRUE;
1702   }
1703
1704   if (discont) {
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. */
1715   }
1716
1717   self->offset += gst_buffer_get_size (buf);
1718
1719   gst_adapter_push (self->adapter, buf);
1720
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);
1724
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);
1729   } else {
1730     gst_adapter_unmap (self->adapter);
1731   }
1732
1733   g_free (input);
1734 }
1735
1736
1737 static void
1738 xml_text (GMarkupParseContext * context,
1739     const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1740 {
1741   gchar **accum = (gchar **) user_data;
1742   gchar *concat;
1743
1744   if (*accum) {
1745     concat = g_strconcat (*accum, text, NULL);
1746     g_free (*accum);
1747     *accum = concat;
1748   } else {
1749     *accum = g_strdup (text);
1750   }
1751 }
1752
1753 static gchar *
1754 strip_pango_markup (gchar * markup, GError ** error)
1755 {
1756   GMarkupParser parser = { 0, };
1757   GMarkupParseContext *context;
1758   gchar *accum = NULL;
1759
1760   parser.text = xml_text;
1761   context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1762
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);
1766   if (*error)
1767     goto error;
1768
1769   g_markup_parse_context_end_parse (context, error);
1770   if (*error)
1771     goto error;
1772
1773 done:
1774   g_markup_parse_context_free (context);
1775   return accum;
1776
1777 error:
1778   g_free (accum);
1779   accum = NULL;
1780   goto done;
1781 }
1782
1783 static gboolean
1784 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1785 {
1786   GstCaps *caps;
1787   gboolean ret = FALSE;
1788   const GstStructure *s1, *s2;
1789
1790   caps = gst_pad_get_allowed_caps (self->srcpad);
1791
1792   s1 = gst_caps_get_structure (preferred, 0);
1793
1794   if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1795     GstCaps *intersected = gst_caps_intersect (caps, preferred);
1796     gst_caps_unref (caps);
1797     caps = intersected;
1798   }
1799
1800   caps = gst_caps_fixate (caps);
1801
1802   if (gst_caps_is_empty (caps)) {
1803     goto done;
1804   }
1805
1806   s2 = gst_caps_get_structure (caps, 0);
1807
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");
1811
1812   if (self->strip_pango_markup) {
1813     GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1814   }
1815
1816   ret = gst_pad_set_caps (self->srcpad, caps);
1817
1818 done:
1819   gst_caps_unref (caps);
1820   return ret;
1821 }
1822
1823 static GstFlowReturn
1824 check_initial_events (GstSubParse * self)
1825 {
1826   gboolean need_tags = FALSE;
1827
1828   /* make sure we know the format */
1829   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1830     GstCaps *preferred;
1831
1832     if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1833       return GST_FLOW_NOT_NEGOTIATED;
1834     }
1835
1836     if (!gst_sub_parse_negotiate (self, preferred)) {
1837       gst_caps_unref (preferred);
1838       return GST_FLOW_NOT_NEGOTIATED;
1839     }
1840
1841     gst_caps_unref (preferred);
1842
1843     need_tags = TRUE;
1844   }
1845
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,
1850         &self->segment);
1851
1852     gst_event_set_seqnum (segment_event, self->segment_seqnum);
1853     gst_pad_push_event (self->srcpad, segment_event);
1854     self->need_segment = FALSE;
1855   }
1856
1857   if (need_tags) {
1858     /* push tags */
1859     if (self->subtitle_codec != NULL) {
1860       GstTagList *tags;
1861
1862       tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1863           NULL);
1864       gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1865     }
1866   }
1867
1868   return GST_FLOW_OK;
1869 }
1870
1871 static GstFlowReturn
1872 handle_buffer (GstSubParse * self, GstBuffer * buf)
1873 {
1874   GstFlowReturn ret = GST_FLOW_OK;
1875   gchar *line, *subtitle;
1876 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
1877   GstMessage *m = NULL;
1878 #endif
1879 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1880   GstClockTime fragment_timestamp = GST_CLOCK_TIME_NONE;
1881 #endif
1882
1883   GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT, buf);
1884
1885   if (self->first_buffer) {
1886     GstMapInfo map;
1887
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;
1895   }
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);
1899 #endif
1900
1901   feed_textbuf (self, buf);
1902
1903   ret = check_initial_events (self);
1904   if (ret != GST_FLOW_OK)
1905     return ret;
1906
1907 #ifdef TIZEN_FEATURE_HLS_WEBVTT
1908   if (self->parser_type == GST_SUB_PARSE_FORMAT_VTT)
1909     send_fragment_timestamp_event (self, fragment_timestamp);
1910 #endif
1911
1912   while (!self->flushing && (line = get_next_line (self))) {
1913     guint offset = 0;
1914
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,
1919         line + offset);
1920     subtitle = self->parse_line (&self->state, line + offset);
1921     g_free (line);
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));
1927
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));
1932     }
1933 #endif
1934     if (subtitle) {
1935       guint subtitle_len;
1936
1937       if (self->strip_pango_markup) {
1938         GError *error = NULL;
1939         gchar *stripped;
1940
1941         if ((stripped = strip_pango_markup (subtitle, &error))) {
1942           g_free (subtitle);
1943           subtitle = stripped;
1944         } else {
1945           GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1946               error->message);
1947         }
1948       }
1949
1950       subtitle_len = strlen (subtitle);
1951
1952       /* +1 for terminating NUL character */
1953       buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1954
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);
1958
1959       GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1960       GST_BUFFER_DURATION (buf) = self->state.duration;
1961
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;
1970       }
1971
1972       self->segment.position = self->state.start_time;
1973
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));
1977
1978       g_free (self->state.vertical);
1979       self->state.vertical = NULL;
1980       g_free (self->state.alignment);
1981       self->state.alignment = NULL;
1982
1983       ret = gst_pad_push (self->srcpad, buf);
1984
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;
1988
1989       g_free (subtitle);
1990       subtitle = NULL;
1991
1992       if (ret != GST_FLOW_OK) {
1993         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1994         break;
1995       }
1996     }
1997   }
1998
1999   return ret;
2000 }
2001
2002 static GstFlowReturn
2003 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
2004 {
2005   GstFlowReturn ret;
2006   GstSubParse *self;
2007
2008   self = GST_SUBPARSE (parent);
2009
2010   ret = handle_buffer (self, buf);
2011
2012   return ret;
2013 }
2014
2015 static gboolean
2016 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2017 {
2018   GstSubParse *self = GST_SUBPARSE (parent);
2019   gboolean ret = FALSE;
2020
2021   GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
2022
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);
2035
2036         GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
2037             GST_EVENT_TYPE_NAME (event));
2038
2039         gst_buffer_fill (buf, 0, term_chars, 3);
2040         gst_buffer_set_size (buf, 2);
2041
2042         GST_BUFFER_OFFSET (buf) = self->offset;
2043         gst_sub_parse_chain (pad, parent, buf);
2044       }
2045       ret = gst_pad_event_default (pad, parent, event);
2046       break;
2047     }
2048     case GST_EVENT_SEGMENT:
2049     {
2050       const GstSegment *s;
2051
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");
2057           ret = TRUE;
2058           gst_event_unref (event);
2059           break;
2060         }
2061       } else {
2062         SUBPARSE_SEEK_LOCK (self);
2063       }
2064 #endif
2065
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);
2072
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) */
2081       ret = TRUE;
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;
2087
2088 #ifdef TIZEN_FEATURE_SUBPARSE_MODIFICATION
2089       SUBPARSE_SEEK_UNLOCK (self);
2090 #endif
2091
2092       break;
2093     }
2094     case GST_EVENT_GAP:
2095     {
2096       ret = check_initial_events (self);
2097       if (ret == GST_FLOW_OK) {
2098         ret = gst_pad_event_default (pad, parent, event);
2099       } else {
2100         gst_event_unref (event);
2101       }
2102       break;
2103     }
2104     case GST_EVENT_FLUSH_START:
2105     {
2106       self->flushing = TRUE;
2107
2108       ret = gst_pad_event_default (pad, parent, event);
2109       break;
2110     }
2111     case GST_EVENT_FLUSH_STOP:
2112     {
2113       self->flushing = FALSE;
2114
2115       ret = gst_pad_event_default (pad, parent, event);
2116       break;
2117     }
2118     default:
2119       ret = gst_pad_event_default (pad, parent, event);
2120       break;
2121   }
2122
2123   return ret;
2124 }
2125
2126
2127 static GstStateChangeReturn
2128 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
2129 {
2130   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2131   GstSubParse *self = GST_SUBPARSE (element);
2132
2133   switch (transition) {
2134     case GST_STATE_CHANGE_READY_TO_PAUSED:
2135       /* format detection will init the parser state */
2136       self->offset = 0;
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);
2145       break;
2146     default:
2147       break;
2148   }
2149
2150   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2151   if (ret == GST_STATE_CHANGE_FAILURE)
2152     return ret;
2153
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;
2158       break;
2159     default:
2160       break;
2161   }
2162
2163   return ret;
2164 }