subparse: Fix non-closed tag handling.
[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 #define DEFAULT_ENCODING   NULL
44 #define ATTRIBUTE_REGEX "\\s?[a-zA-Z0-9\\. \t\\(\\)]*"
45 static const gchar *allowed_srt_tags[] = { "i", "b", "u", NULL };
46 static const gchar *allowed_vtt_tags[] =
47     { "i", "b", "c", "u", "v", "ruby", "rt", NULL };
48
49 enum
50 {
51   PROP_0,
52   PROP_ENCODING,
53   PROP_VIDEOFPS
54 };
55
56 static void
57 gst_sub_parse_set_property (GObject * object, guint prop_id,
58     const GValue * value, GParamSpec * pspec);
59 static void
60 gst_sub_parse_get_property (GObject * object, guint prop_id,
61     GValue * value, GParamSpec * pspec);
62
63
64 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
65     GST_PAD_SINK,
66     GST_PAD_ALWAYS,
67     GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
68         "application/x-subtitle-tmplayer; application/x-subtitle-mpl2; "
69         "application/x-subtitle-dks; application/x-subtitle-qttext;"
70         "application/x-subtitle-lrc; application/x-subtitle-vtt")
71     );
72
73 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
74     GST_PAD_SRC,
75     GST_PAD_ALWAYS,
76     GST_STATIC_CAPS ("text/x-raw, format= { pango-markup, utf8 }")
77     );
78
79
80 static gboolean gst_sub_parse_src_event (GstPad * pad, GstObject * parent,
81     GstEvent * event);
82 static gboolean gst_sub_parse_src_query (GstPad * pad, GstObject * parent,
83     GstQuery * query);
84 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstObject * parent,
85     GstEvent * event);
86
87 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
88     GstStateChange transition);
89
90 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent,
91     GstBuffer * buf);
92
93 #define gst_sub_parse_parent_class parent_class
94 G_DEFINE_TYPE (GstSubParse, gst_sub_parse, GST_TYPE_ELEMENT);
95
96 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (subparse, "subparse",
97     GST_RANK_PRIMARY, GST_TYPE_SUBPARSE, sub_parse_element_init (plugin))
98
99
100      static void gst_sub_parse_dispose (GObject * object)
101 {
102   GstSubParse *subparse = GST_SUBPARSE (object);
103
104   GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
105
106   if (subparse->encoding) {
107     g_free (subparse->encoding);
108     subparse->encoding = NULL;
109   }
110
111   if (subparse->detected_encoding) {
112     g_free (subparse->detected_encoding);
113     subparse->detected_encoding = NULL;
114   }
115
116   if (subparse->adapter) {
117     g_object_unref (subparse->adapter);
118     subparse->adapter = NULL;
119   }
120
121   if (subparse->textbuf) {
122     g_string_free (subparse->textbuf, TRUE);
123     subparse->textbuf = NULL;
124   }
125
126   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
127 }
128
129 static void
130 gst_sub_parse_class_init (GstSubParseClass * klass)
131 {
132   GObjectClass *object_class = G_OBJECT_CLASS (klass);
133   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
134
135   object_class->dispose = gst_sub_parse_dispose;
136   object_class->set_property = gst_sub_parse_set_property;
137   object_class->get_property = gst_sub_parse_get_property;
138
139   gst_element_class_add_static_pad_template (element_class, &sink_templ);
140   gst_element_class_add_static_pad_template (element_class, &src_templ);
141   gst_element_class_set_static_metadata (element_class,
142       "Subtitle parser", "Codec/Parser/Subtitle",
143       "Parses subtitle (.sub) files into text streams",
144       "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>, "
145       "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
146
147   element_class->change_state = gst_sub_parse_change_state;
148
149   g_object_class_install_property (object_class, PROP_ENCODING,
150       g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
151           "Encoding to assume if input subtitles are not in UTF-8 or any other "
152           "Unicode encoding. If not set, the GST_SUBTITLE_ENCODING environment "
153           "variable will be checked for an encoding to use. If that is not set "
154           "either, ISO-8859-15 will be assumed.", DEFAULT_ENCODING,
155           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
156
157   g_object_class_install_property (object_class, PROP_VIDEOFPS,
158       gst_param_spec_fraction ("video-fps", "Video framerate",
159           "Framerate of the video stream. This is needed by some subtitle "
160           "formats to synchronize subtitles and video properly. If not set "
161           "and the subtitle format requires it subtitles may be out of sync.",
162           0, 1, G_MAXINT, 1, 24000, 1001,
163           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164 }
165
166 static void
167 gst_sub_parse_init (GstSubParse * subparse)
168 {
169   subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
170   gst_pad_set_chain_function (subparse->sinkpad,
171       GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
172   gst_pad_set_event_function (subparse->sinkpad,
173       GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
174   gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
175
176   subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
177   gst_pad_set_event_function (subparse->srcpad,
178       GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
179   gst_pad_set_query_function (subparse->srcpad,
180       GST_DEBUG_FUNCPTR (gst_sub_parse_src_query));
181   gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
182
183   subparse->textbuf = g_string_new (NULL);
184   subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
185   subparse->strip_pango_markup = FALSE;
186   subparse->flushing = FALSE;
187   gst_segment_init (&subparse->segment, GST_FORMAT_TIME);
188   subparse->need_segment = TRUE;
189   subparse->encoding = g_strdup (DEFAULT_ENCODING);
190   subparse->detected_encoding = NULL;
191   subparse->adapter = gst_adapter_new ();
192
193   subparse->fps_n = 24000;
194   subparse->fps_d = 1001;
195 }
196
197 /*
198  * Source pad functions.
199  */
200
201 static gboolean
202 gst_sub_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
203 {
204   GstSubParse *self = GST_SUBPARSE (parent);
205   gboolean ret = FALSE;
206
207   GST_DEBUG ("Handling %s query", GST_QUERY_TYPE_NAME (query));
208
209   switch (GST_QUERY_TYPE (query)) {
210     case GST_QUERY_POSITION:{
211       GstFormat fmt;
212
213       gst_query_parse_position (query, &fmt, NULL);
214       if (fmt != GST_FORMAT_TIME) {
215         ret = gst_pad_peer_query (self->sinkpad, query);
216       } else {
217         ret = TRUE;
218         gst_query_set_position (query, GST_FORMAT_TIME, self->segment.position);
219       }
220       break;
221     }
222     case GST_QUERY_SEEKING:
223     {
224       GstFormat fmt;
225       gboolean seekable = FALSE;
226
227       ret = TRUE;
228
229       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
230       if (fmt == GST_FORMAT_TIME) {
231         GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
232
233         seekable = gst_pad_peer_query (self->sinkpad, peerquery);
234         if (seekable)
235           gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
236         gst_query_unref (peerquery);
237       }
238
239       gst_query_set_seeking (query, fmt, seekable, seekable ? 0 : -1, -1);
240       break;
241     }
242     default:
243       ret = gst_pad_query_default (pad, parent, query);
244       break;
245   }
246
247   return ret;
248 }
249
250 static gboolean
251 gst_sub_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
252 {
253   GstSubParse *self = GST_SUBPARSE (parent);
254   gboolean ret = FALSE;
255
256   GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
257
258   switch (GST_EVENT_TYPE (event)) {
259     case GST_EVENT_SEEK:
260     {
261       GstFormat format;
262       GstSeekFlags flags;
263       GstSeekType start_type, stop_type;
264       gint64 start, stop;
265       gdouble rate;
266       gboolean update;
267
268       gst_event_parse_seek (event, &rate, &format, &flags,
269           &start_type, &start, &stop_type, &stop);
270
271       if (format != GST_FORMAT_TIME) {
272         GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
273         gst_event_unref (event);
274         goto beach;
275       }
276
277       /* Convert that seek to a seeking in bytes at position 0,
278          FIXME: could use an index */
279       ret = gst_pad_push_event (self->sinkpad,
280           gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
281               GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
282
283       if (ret) {
284         /* Apply the seek to our segment */
285         gst_segment_do_seek (&self->segment, rate, format, flags,
286             start_type, start, stop_type, stop, &update);
287
288         GST_DEBUG_OBJECT (self, "segment after seek: %" GST_SEGMENT_FORMAT,
289             &self->segment);
290
291         /* will mark need_segment when receiving segment from upstream,
292          * after FLUSH and all that has happened,
293          * rather than racing with chain */
294       } else {
295         GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
296       }
297
298       gst_event_unref (event);
299       break;
300     }
301     default:
302       ret = gst_pad_event_default (pad, parent, event);
303       break;
304   }
305
306 beach:
307   return ret;
308 }
309
310 static void
311 gst_sub_parse_set_property (GObject * object, guint prop_id,
312     const GValue * value, GParamSpec * pspec)
313 {
314   GstSubParse *subparse = GST_SUBPARSE (object);
315
316   GST_OBJECT_LOCK (subparse);
317   switch (prop_id) {
318     case PROP_ENCODING:
319       g_free (subparse->encoding);
320       subparse->encoding = g_value_dup_string (value);
321       GST_LOG_OBJECT (object, "subtitle encoding set to %s",
322           GST_STR_NULL (subparse->encoding));
323       break;
324     case PROP_VIDEOFPS:
325     {
326       subparse->fps_n = gst_value_get_fraction_numerator (value);
327       subparse->fps_d = gst_value_get_fraction_denominator (value);
328       GST_DEBUG_OBJECT (object, "video framerate set to %d/%d", subparse->fps_n,
329           subparse->fps_d);
330
331       if (!subparse->state.have_internal_fps) {
332         subparse->state.fps_n = subparse->fps_n;
333         subparse->state.fps_d = subparse->fps_d;
334       }
335       break;
336     }
337     default:
338       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
339       break;
340   }
341   GST_OBJECT_UNLOCK (subparse);
342 }
343
344 static void
345 gst_sub_parse_get_property (GObject * object, guint prop_id,
346     GValue * value, GParamSpec * pspec)
347 {
348   GstSubParse *subparse = GST_SUBPARSE (object);
349
350   GST_OBJECT_LOCK (subparse);
351   switch (prop_id) {
352     case PROP_ENCODING:
353       g_value_set_string (value, subparse->encoding);
354       break;
355     case PROP_VIDEOFPS:
356       gst_value_set_fraction (value, subparse->fps_n, subparse->fps_d);
357       break;
358     default:
359       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
360       break;
361   }
362   GST_OBJECT_UNLOCK (subparse);
363 }
364
365 static const gchar *
366 gst_sub_parse_get_format_description (GstSubParseFormat format)
367 {
368   switch (format) {
369     case GST_SUB_PARSE_FORMAT_MDVDSUB:
370       return "MicroDVD";
371     case GST_SUB_PARSE_FORMAT_SUBRIP:
372       return "SubRip";
373     case GST_SUB_PARSE_FORMAT_MPSUB:
374       return "MPSub";
375     case GST_SUB_PARSE_FORMAT_SAMI:
376       return "SAMI";
377     case GST_SUB_PARSE_FORMAT_TMPLAYER:
378       return "TMPlayer";
379     case GST_SUB_PARSE_FORMAT_MPL2:
380       return "MPL2";
381     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
382       return "SubViewer";
383     case GST_SUB_PARSE_FORMAT_DKS:
384       return "DKS";
385     case GST_SUB_PARSE_FORMAT_VTT:
386       return "WebVTT";
387     case GST_SUB_PARSE_FORMAT_QTTEXT:
388       return "QTtext";
389     case GST_SUB_PARSE_FORMAT_LRC:
390       return "LRC";
391     default:
392     case GST_SUB_PARSE_FORMAT_UNKNOWN:
393       break;
394   }
395   return NULL;
396 }
397
398
399
400
401
402 static gchar *
403 convert_encoding (GstSubParse * self, const gchar * str, gsize len,
404     gsize * consumed)
405 {
406   const gchar *encoding;
407   GError *err = NULL;
408   gchar *ret = NULL;
409
410   *consumed = 0;
411
412   /* First try any detected encoding */
413   if (self->detected_encoding) {
414     ret =
415         gst_sub_parse_gst_convert_to_utf8 (str, len, self->detected_encoding,
416         consumed, &err);
417
418     if (!err)
419       return ret;
420
421     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
422         self->detected_encoding, err->message);
423     g_free (self->detected_encoding);
424     self->detected_encoding = NULL;
425     g_clear_error (&err);
426   }
427
428   /* Otherwise check if it's UTF8 */
429   if (self->valid_utf8) {
430     if (g_utf8_validate (str, len, NULL)) {
431       GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
432       *consumed = len;
433       return g_strndup (str, len);
434     }
435     GST_INFO_OBJECT (self, "invalid UTF-8!");
436     self->valid_utf8 = FALSE;
437   }
438
439   /* Else try fallback */
440   encoding = self->encoding;
441   if (encoding == NULL || *encoding == '\0') {
442     encoding = g_getenv ("GST_SUBTITLE_ENCODING");
443   }
444   if (encoding == NULL || *encoding == '\0') {
445     /* if local encoding is UTF-8 and no encoding specified
446      * via the environment variable, assume ISO-8859-15 */
447     if (g_get_charset (&encoding)) {
448       encoding = "ISO-8859-15";
449     }
450   }
451
452   ret = gst_sub_parse_gst_convert_to_utf8 (str, len, encoding, consumed, &err);
453
454   if (err) {
455     GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
456         encoding, err->message);
457     g_clear_error (&err);
458
459     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
460     ret =
461         gst_sub_parse_gst_convert_to_utf8 (str, len, "ISO-8859-15", consumed,
462         NULL);
463   }
464
465   GST_LOG_OBJECT (self,
466       "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
467       "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
468
469   return ret;
470 }
471
472 static gchar *
473 get_next_line (GstSubParse * self)
474 {
475   char *line = NULL;
476   const char *line_end;
477   int line_len;
478   gboolean have_r = FALSE;
479
480   line_end = strchr (self->textbuf->str, '\n');
481
482   if (!line_end) {
483     /* end-of-line not found; return for more data */
484     return NULL;
485   }
486
487   /* get rid of '\r' */
488   if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
489     line_end--;
490     have_r = TRUE;
491   }
492
493   line_len = line_end - self->textbuf->str;
494   line = g_strndup (self->textbuf->str, line_len);
495   self->textbuf = g_string_erase (self->textbuf, 0,
496       line_len + (have_r ? 2 : 1));
497   return line;
498 }
499
500 static gchar *
501 parse_mdvdsub (ParserState * state, const gchar * line)
502 {
503   const gchar *line_split;
504   gchar *line_chunk;
505   guint start_frame, end_frame;
506   guint64 clip_start = 0, clip_stop = 0;
507   gboolean in_seg = FALSE;
508   GString *markup;
509   gchar *ret;
510
511   /* style variables */
512   gboolean italic;
513   gboolean bold;
514   guint fontsize;
515   gdouble fps = 0.0;
516
517   if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
518     GST_WARNING ("Parsing of the following line, assumed to be in microdvd .sub"
519         " format, failed:\n%s", line);
520     return NULL;
521   }
522
523   /* skip the {%u}{%u} part */
524   line = strchr (line, '}') + 1;
525   line = strchr (line, '}') + 1;
526
527   /* see if there's a first line with a framerate */
528   if (start_frame == 1 && end_frame == 1) {
529     gchar *rest, *end = NULL;
530
531     rest = g_strdup (line);
532     g_strdelimit (rest, ",", '.');
533     fps = g_ascii_strtod (rest, &end);
534     if (end != rest) {
535       gst_util_double_to_fraction (fps, &state->fps_n, &state->fps_d);
536       GST_INFO ("framerate from file: %d/%d ('%s')", state->fps_n,
537           state->fps_d, rest);
538     }
539     g_free (rest);
540     return NULL;
541   }
542
543   state->start_time =
544       gst_util_uint64_scale (start_frame, GST_SECOND * state->fps_d,
545       state->fps_n);
546   state->duration =
547       gst_util_uint64_scale (end_frame - start_frame, GST_SECOND * state->fps_d,
548       state->fps_n);
549
550   /* Check our segment start/stop */
551   in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
552       state->start_time, state->start_time + state->duration, &clip_start,
553       &clip_stop);
554
555   /* No need to parse that text if it's out of segment */
556   if (in_seg) {
557     state->start_time = clip_start;
558     state->duration = clip_stop - clip_start;
559   } else {
560     return NULL;
561   }
562
563   markup = g_string_new (NULL);
564   while (1) {
565     italic = FALSE;
566     bold = FALSE;
567     fontsize = 0;
568     /* parse style markup */
569     if (strncmp (line, "{y:i}", 5) == 0) {
570       italic = TRUE;
571       line = strchr (line, '}') + 1;
572     }
573     if (strncmp (line, "{y:b}", 5) == 0) {
574       bold = TRUE;
575       line = strchr (line, '}') + 1;
576     }
577     if (sscanf (line, "{s:%u}", &fontsize) == 1) {
578       line = strchr (line, '}') + 1;
579     }
580     /* forward slashes at beginning/end signify italics too */
581     if (g_str_has_prefix (line, "/")) {
582       italic = TRUE;
583       ++line;
584     }
585     if ((line_split = strchr (line, '|')))
586       line_chunk = g_markup_escape_text (line, line_split - line);
587     else
588       line_chunk = g_markup_escape_text (line, strlen (line));
589
590     /* Remove italics markers at end of line/stanza (CHECKME: are end slashes
591      * always at the end of a line or can they span multiple lines?) */
592     if (g_str_has_suffix (line_chunk, "/")) {
593       line_chunk[strlen (line_chunk) - 1] = '\0';
594     }
595
596     markup = g_string_append (markup, "<span");
597     if (italic)
598       g_string_append (markup, " style=\"italic\"");
599     if (bold)
600       g_string_append (markup, " weight=\"bold\"");
601     if (fontsize)
602       g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
603     g_string_append_printf (markup, ">%s</span>", line_chunk);
604     g_free (line_chunk);
605     if (line_split) {
606       g_string_append (markup, "\n");
607       line = line_split + 1;
608     } else {
609       break;
610     }
611   }
612   ret = markup->str;
613   g_string_free (markup, FALSE);
614   GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
615       state->start_time / (double) GST_SECOND,
616       state->duration / (double) GST_SECOND, ret);
617   return ret;
618 }
619
620 static void
621 strip_trailing_newlines (gchar * txt)
622 {
623   if (txt) {
624     guint len;
625
626     len = strlen (txt);
627     while (len > 1 && txt[len - 1] == '\n') {
628       txt[len - 1] = '\0';
629       --len;
630     }
631   }
632 }
633
634 /* we want to escape text in general, but retain basic markup like
635  * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
636  * just unescape a white list of allowed markups again after
637  * escaping everything (the text between these simple markers isn't
638  * necessarily escaped, so it seems best to do it like this) */
639 static void
640 subrip_unescape_formatting (gchar * txt, gconstpointer allowed_tags_ptr,
641     gboolean allows_tag_attributes)
642 {
643   gchar *res;
644   GRegex *tag_regex;
645   gchar *allowed_tags_pattern, *search_pattern;
646   const gchar *replace_pattern;
647
648   /* No processing needed if no escaped tag marker found in the string. */
649   if (strstr (txt, "&lt;") == NULL)
650     return;
651
652   /* Build a list of alternates for our regexp.
653    * FIXME: Could be built once and stored */
654   allowed_tags_pattern = g_strjoinv ("|", (gchar **) allowed_tags_ptr);
655   /* Look for starting/ending escaped tags with optional attributes. */
656   search_pattern = g_strdup_printf ("&lt;(/)?\\ *(%s)(%s)&gt;",
657       allowed_tags_pattern, ATTRIBUTE_REGEX);
658   /* And unescape appropriately */
659   if (allows_tag_attributes) {
660     replace_pattern = "<\\1\\2\\3>";
661   } else {
662     replace_pattern = "<\\1\\2>";
663   }
664
665   tag_regex = g_regex_new (search_pattern, 0, 0, NULL);
666   res = g_regex_replace (tag_regex, txt, strlen (txt), 0,
667       replace_pattern, 0, NULL);
668
669   /* res will always be shorter than the input or identical, so this
670    * copy is OK */
671   strcpy (txt, res);
672
673   g_free (res);
674   g_free (search_pattern);
675   g_free (allowed_tags_pattern);
676
677   g_regex_unref (tag_regex);
678 }
679
680
681 static gboolean
682 subrip_remove_unhandled_tag (gchar * start, gchar * stop)
683 {
684   gchar *tag, saved;
685
686   tag = start + strlen ("&lt;");
687   if (*tag == '/')
688     ++tag;
689
690   if (g_ascii_tolower (*tag) < 'a' || g_ascii_tolower (*tag) > 'z')
691     return FALSE;
692
693   saved = *stop;
694   *stop = '\0';
695   GST_LOG ("removing unhandled tag '%s'", start);
696   *stop = saved;
697   memmove (start, stop, strlen (stop) + 1);
698   return TRUE;
699 }
700
701 /* remove tags we haven't explicitly allowed earlier on, like font tags
702  * for example */
703 static void
704 subrip_remove_unhandled_tags (gchar * txt)
705 {
706   gchar *pos, *gt;
707
708   for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
709     if (strncmp (pos, "&lt;", 4) == 0 && (gt = strstr (pos + 4, "&gt;"))) {
710       if (subrip_remove_unhandled_tag (pos, gt + strlen ("&gt;")))
711         --pos;
712     }
713   }
714 }
715
716 /* we only allow a fixed set of tags like <i>, <u> and <b>, so let's
717  * take a simple approach. This code assumes the input has been
718  * escaped and subrip_unescape_formatting() has then been run over the
719  * input! This function adds missing closing markup tags and removes
720  * broken closing tags for tags that have never been opened. */
721 static void
722 subrip_fix_up_markup (gchar ** p_txt, gconstpointer allowed_tags_ptr)
723 {
724   gchar *cur, *next_tag;
725   GPtrArray *open_tags = NULL;
726   guint num_open_tags = 0;
727   const gchar *iter_tag;
728   guint offset = 0;
729   guint index;
730   gchar *cur_tag;
731   gchar *end_tag;
732   GRegex *tag_regex;
733   GMatchInfo *match_info;
734   gchar **allowed_tags = (gchar **) allowed_tags_ptr;
735
736   g_assert (*p_txt != NULL);
737
738   open_tags = g_ptr_array_new_with_free_func (g_free);
739   cur = *p_txt;
740   while (*cur != '\0') {
741     next_tag = strchr (cur, '<');
742     if (next_tag == NULL)
743       break;
744     offset = 0;
745     index = 0;
746     while (index < g_strv_length (allowed_tags)) {
747       iter_tag = allowed_tags[index];
748       /* Look for a white listed tag */
749       cur_tag = g_strconcat ("<", iter_tag, ATTRIBUTE_REGEX, ">", NULL);
750       tag_regex = g_regex_new (cur_tag, 0, 0, NULL);
751       (void) g_regex_match (tag_regex, next_tag, 0, &match_info);
752
753       if (g_match_info_matches (match_info)) {
754         gint start_pos, end_pos;
755         gchar *word = g_match_info_fetch (match_info, 0);
756         g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
757         if (start_pos == 0) {
758           offset = strlen (word);
759         }
760         g_free (word);
761       }
762       g_match_info_free (match_info);
763       g_regex_unref (tag_regex);
764       g_free (cur_tag);
765       index++;
766       if (offset) {
767         /* OK we found a tag, let's keep track of it */
768         g_ptr_array_add (open_tags, g_ascii_strdown (iter_tag, -1));
769         ++num_open_tags;
770         break;
771       }
772     }
773
774     if (offset) {
775       next_tag += offset;
776       cur = next_tag;
777       continue;
778     }
779
780     if (*next_tag == '<' && *(next_tag + 1) == '/') {
781       end_tag = strchr (cur, '>');
782       if (end_tag) {
783         const gchar *last = NULL;
784         if (num_open_tags > 0)
785           last = g_ptr_array_index (open_tags, num_open_tags - 1);
786         if (num_open_tags == 0
787             || g_ascii_strncasecmp (end_tag - 1, last, strlen (last))) {
788           GST_LOG ("broken input, closing tag '%s' is not open", next_tag);
789           /* Move everything after the tag end, including closing \0 */
790           memmove (next_tag, end_tag + 1, strlen (end_tag));
791           cur = next_tag;
792           continue;
793         } else {
794           --num_open_tags;
795           g_ptr_array_remove_index (open_tags, num_open_tags);
796         }
797       }
798     }
799     ++next_tag;
800     cur = next_tag;
801   }
802
803   if (num_open_tags > 0) {
804     GString *s;
805
806     s = g_string_new (*p_txt);
807     while (num_open_tags > 0) {
808       GST_LOG ("adding missing closing tag '%s'",
809           (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
810       g_string_append_c (s, '<');
811       g_string_append_c (s, '/');
812       g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
813       g_string_append_c (s, '>');
814       --num_open_tags;
815     }
816     g_free (*p_txt);
817     *p_txt = g_string_free (s, FALSE);
818   }
819   g_ptr_array_free (open_tags, TRUE);
820 }
821
822 static gboolean
823 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
824 {
825   gchar s[128] = { '\0', };
826   gchar *end, *p;
827   guint hour, min, sec, msec, len;
828
829   while (*ts_string == ' ')
830     ++ts_string;
831
832   g_strlcpy (s, ts_string, sizeof (s));
833   if ((end = strstr (s, "-->")))
834     *end = '\0';
835   g_strchomp (s);
836
837   /* ms may be in these formats:
838    * hh:mm:ss,500 = 500ms
839    * hh:mm:ss,  5 =   5ms
840    * hh:mm:ss, 5  =  50ms
841    * hh:mm:ss, 50 =  50ms
842    * hh:mm:ss,5   = 500ms
843    * and the same with . instead of ,.
844    * sscanf() doesn't differentiate between '  5' and '5' so munge
845    * the white spaces within the timestamp to '0' (I'm sure there's a
846    * way to make sscanf() do this for us, but how?)
847    */
848   g_strdelimit (s, " ", '0');
849   g_strdelimit (s, ".", ',');
850
851   /* make sure we have exactly three digits after he comma */
852   p = strchr (s, ',');
853   if (p == NULL) {
854     /* If there isn't a ',' the timestamp is broken */
855     /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
856     GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
857     return FALSE;
858   }
859
860   ++p;
861   len = strlen (p);
862   if (len > 3) {
863     p[3] = '\0';
864   } else
865     while (len < 3) {
866       g_strlcat (&p[len], "0", 2);
867       ++len;
868     }
869
870   GST_LOG ("parsing timestamp '%s'", s);
871   if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
872     /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
873      *
874      * The hours component is optional with webVTT, for example
875      * mm:ss,500 is a valid webVTT timestamp. When not present,
876      * hours is 0.
877      */
878     hour = 0;
879
880     if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
881       GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
882       return FALSE;
883     }
884   }
885
886   *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
887   return TRUE;
888 }
889
890 /* cue settings are part of the WebVTT specification. They are
891  * declared after the time interval in the first line of the
892  * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
893  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
894  */
895 static void
896 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
897 {
898   gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
899   gint i = 0;
900   gint16 text_position, text_size;
901   gint16 line_position;
902   gboolean vertical_found = FALSE;
903   gboolean alignment_found = FALSE;
904
905   while (i < g_strv_length (splitted_settings)) {
906     gboolean valid_tag = FALSE;
907     switch (splitted_settings[i][0]) {
908       case 'T':
909         if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
910                 &text_position) > 0) {
911           state->text_position = (guint8) text_position;
912           valid_tag = TRUE;
913         }
914         break;
915       case 'D':
916         if (strlen (splitted_settings[i]) > 2) {
917           vertical_found = TRUE;
918           g_free (state->vertical);
919           state->vertical = g_strdup (splitted_settings[i] + 2);
920           valid_tag = TRUE;
921         }
922         break;
923       case 'L':
924         if (g_str_has_suffix (splitted_settings[i], "%")) {
925           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
926                   &line_position) > 0) {
927             state->line_position = line_position;
928             valid_tag = TRUE;
929           }
930         } else {
931           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
932                   &line_position) > 0) {
933             state->line_number = line_position;
934             valid_tag = TRUE;
935           }
936         }
937         break;
938       case 'S':
939         if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
940                 &text_size) > 0) {
941           state->text_size = (guint8) text_size;
942           valid_tag = TRUE;
943         }
944         break;
945       case 'A':
946         if (strlen (splitted_settings[i]) > 2) {
947           g_free (state->alignment);
948           state->alignment = g_strdup (splitted_settings[i] + 2);
949           alignment_found = TRUE;
950           valid_tag = TRUE;
951         }
952         break;
953       default:
954         break;
955     }
956     if (!valid_tag) {
957       GST_LOG ("Invalid or unrecognised setting found: %s",
958           splitted_settings[i]);
959     }
960     i++;
961   }
962   g_strfreev (splitted_settings);
963   if (!vertical_found) {
964     g_free (state->vertical);
965     state->vertical = g_strdup ("");
966   }
967   if (!alignment_found) {
968     g_free (state->alignment);
969     state->alignment = g_strdup ("");
970   }
971 }
972
973 static gchar *
974 parse_subrip (ParserState * state, const gchar * line)
975 {
976   gchar *ret;
977
978   switch (state->state) {
979     case 0:{
980       char *endptr;
981       guint64 id;
982
983       /* looking for a single integer as a Cue ID, but we
984        * don't actually use it */
985       errno = 0;
986       id = g_ascii_strtoull (line, &endptr, 10);
987       if (id == G_MAXUINT64 && errno == ERANGE)
988         state->state = 1;
989       else if (id == 0 && errno == EINVAL)
990         state->state = 1;
991       else if (endptr != line && *endptr == '\0')
992         state->state = 1;
993       return NULL;
994     }
995     case 1:
996     {
997       GstClockTime ts_start, ts_end;
998       gchar *end_time;
999
1000       /* looking for start_time --> end_time */
1001       if ((end_time = strstr (line, " --> ")) &&
1002           parse_subrip_time (line, &ts_start) &&
1003           parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1004           state->start_time <= ts_end) {
1005         state->state = 2;
1006         state->start_time = ts_start;
1007         state->duration = ts_end - ts_start;
1008       } else {
1009         GST_DEBUG ("error parsing subrip time line '%s'", line);
1010         state->state = 0;
1011       }
1012       return NULL;
1013     }
1014     case 2:
1015     {
1016       /* No need to parse that text if it's out of segment */
1017       guint64 clip_start = 0, clip_stop = 0;
1018       gboolean in_seg = FALSE;
1019
1020       /* Check our segment start/stop */
1021       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1022           state->start_time, state->start_time + state->duration,
1023           &clip_start, &clip_stop);
1024
1025       if (in_seg) {
1026         state->start_time = clip_start;
1027         state->duration = clip_stop - clip_start;
1028       } else {
1029         state->state = 0;
1030         return NULL;
1031       }
1032     }
1033       /* looking for subtitle text; empty line ends this subtitle entry */
1034       if (state->buf->len)
1035         g_string_append_c (state->buf, '\n');
1036       g_string_append (state->buf, line);
1037       if (strlen (line) == 0) {
1038         ret = g_markup_escape_text (state->buf->str, state->buf->len);
1039         g_string_truncate (state->buf, 0);
1040         state->state = 0;
1041         subrip_unescape_formatting (ret, state->allowed_tags,
1042             state->allows_tag_attributes);
1043         subrip_remove_unhandled_tags (ret);
1044         strip_trailing_newlines (ret);
1045         subrip_fix_up_markup (&ret, state->allowed_tags);
1046         return ret;
1047       }
1048       return NULL;
1049     default:
1050       g_return_val_if_reached (NULL);
1051   }
1052 }
1053
1054 static gchar *
1055 parse_lrc (ParserState * state, const gchar * line)
1056 {
1057   gint m, s, c;
1058   const gchar *start;
1059   gint milli;
1060
1061   if (line[0] != '[')
1062     return NULL;
1063
1064   if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1065       sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1066     return NULL;
1067
1068   start = strchr (line, ']');
1069   if (start - line == 9)
1070     milli = 10;
1071   else
1072     milli = 1;
1073
1074   state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1075       + gst_util_uint64_scale (s, GST_SECOND, 1)
1076       + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1077   state->duration = GST_CLOCK_TIME_NONE;
1078
1079   return g_strdup (start + 1);
1080 }
1081
1082 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1083  * element. This format is similar to Subrip, the biggest differences
1084  * are that there can be cue settings detailing how to display the cue
1085  * text and more markup tags are allowed.
1086  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1087  */
1088 static gchar *
1089 parse_webvtt (ParserState * state, const gchar * line)
1090 {
1091   /* Cue IDs are optional in WebVTT, but not in subrip,
1092    * so when in state 0 (cue ID), also check if we're
1093    * already at the start --> end time marker */
1094   if (state->state == 0 || state->state == 1) {
1095     GstClockTime ts_start, ts_end;
1096     gchar *end_time;
1097     gchar *cue_settings = NULL;
1098
1099     /* looking for start_time --> end_time */
1100     if ((end_time = strstr (line, " --> ")) &&
1101         parse_subrip_time (line, &ts_start) &&
1102         parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1103         state->start_time <= ts_end) {
1104       state->state = 2;
1105       state->start_time = ts_start;
1106       state->duration = ts_end - ts_start;
1107       cue_settings = strstr (end_time + strlen (" --> "), " ");
1108     } else {
1109       GST_DEBUG ("error parsing subrip time line '%s'", line);
1110       state->state = 0;
1111     }
1112
1113     state->text_position = 0;
1114     state->text_size = 0;
1115     state->line_position = 0;
1116     state->line_number = 0;
1117
1118     if (cue_settings)
1119       parse_webvtt_cue_settings (state, cue_settings + 1);
1120     else {
1121       g_free (state->vertical);
1122       state->vertical = g_strdup ("");
1123       g_free (state->alignment);
1124       state->alignment = g_strdup ("");
1125     }
1126
1127     return NULL;
1128   } else
1129     return parse_subrip (state, line);
1130 }
1131
1132 static void
1133 unescape_newlines_br (gchar * read)
1134 {
1135   gchar *write = read;
1136
1137   /* Replace all occurrences of '[br]' with a newline as version 2
1138    * of the subviewer format uses this for newlines */
1139
1140   if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1141     return;
1142
1143   do {
1144     if (strncmp (read, "[br]", 4) == 0) {
1145       *write = '\n';
1146       read += 4;
1147     } else {
1148       *write = *read;
1149       read++;
1150     }
1151     write++;
1152   } while (*read);
1153
1154   *write = '\0';
1155 }
1156
1157 static gchar *
1158 parse_subviewer (ParserState * state, const gchar * line)
1159 {
1160   guint h1, m1, s1, ms1;
1161   guint h2, m2, s2, ms2;
1162   gchar *ret;
1163
1164   /* TODO: Maybe also parse the fields in the header, especially DELAY.
1165    * For examples see the unit test or
1166    * http://www.doom9.org/index.html?/sub.htm */
1167
1168   switch (state->state) {
1169     case 0:
1170       /* looking for start_time,end_time */
1171       if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1172               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1173         state->state = 1;
1174         state->start_time =
1175             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1176             ms1 * GST_MSECOND;
1177         state->duration =
1178             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1179             ms2 * GST_MSECOND - state->start_time;
1180       }
1181       return NULL;
1182     case 1:
1183     {
1184       /* No need to parse that text if it's out of segment */
1185       guint64 clip_start = 0, clip_stop = 0;
1186       gboolean in_seg = FALSE;
1187
1188       /* Check our segment start/stop */
1189       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1190           state->start_time, state->start_time + state->duration,
1191           &clip_start, &clip_stop);
1192
1193       if (in_seg) {
1194         state->start_time = clip_start;
1195         state->duration = clip_stop - clip_start;
1196       } else {
1197         state->state = 0;
1198         return NULL;
1199       }
1200     }
1201       /* looking for subtitle text; empty line ends this subtitle entry */
1202       if (state->buf->len)
1203         g_string_append_c (state->buf, '\n');
1204       g_string_append (state->buf, line);
1205       if (strlen (line) == 0) {
1206         ret = g_strdup (state->buf->str);
1207         unescape_newlines_br (ret);
1208         strip_trailing_newlines (ret);
1209         g_string_truncate (state->buf, 0);
1210         state->state = 0;
1211         return ret;
1212       }
1213       return NULL;
1214     default:
1215       g_assert_not_reached ();
1216       return NULL;
1217   }
1218 }
1219
1220 static gchar *
1221 parse_mpsub (ParserState * state, const gchar * line)
1222 {
1223   gchar *ret;
1224   float t1, t2;
1225
1226   switch (state->state) {
1227     case 0:
1228       /* looking for two floats (offset, duration) */
1229       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1230         state->state = 1;
1231         state->start_time += state->duration + GST_SECOND * t1;
1232         state->duration = GST_SECOND * t2;
1233       }
1234       return NULL;
1235     case 1:
1236     {                           /* No need to parse that text if it's out of segment */
1237       guint64 clip_start = 0, clip_stop = 0;
1238       gboolean in_seg = FALSE;
1239
1240       /* Check our segment start/stop */
1241       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1242           state->start_time, state->start_time + state->duration,
1243           &clip_start, &clip_stop);
1244
1245       if (in_seg) {
1246         state->start_time = clip_start;
1247         state->duration = clip_stop - clip_start;
1248       } else {
1249         state->state = 0;
1250         return NULL;
1251       }
1252     }
1253       /* looking for subtitle text; empty line ends this
1254        * subtitle entry */
1255       if (state->buf->len)
1256         g_string_append_c (state->buf, '\n');
1257       g_string_append (state->buf, line);
1258       if (strlen (line) == 0) {
1259         ret = g_strdup (state->buf->str);
1260         g_string_truncate (state->buf, 0);
1261         state->state = 0;
1262         return ret;
1263       }
1264       return NULL;
1265     default:
1266       g_assert_not_reached ();
1267       return NULL;
1268   }
1269 }
1270
1271 static const gchar *
1272 dks_skip_timestamp (const gchar * line)
1273 {
1274   while (*line && *line != ']')
1275     line++;
1276   if (*line == ']')
1277     line++;
1278   return line;
1279 }
1280
1281 static gchar *
1282 parse_dks (ParserState * state, const gchar * line)
1283 {
1284   guint h, m, s;
1285
1286   switch (state->state) {
1287     case 0:
1288       /* Looking for the start time and text */
1289       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1290         const gchar *text;
1291         state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1292         text = dks_skip_timestamp (line);
1293         if (*text) {
1294           state->state = 1;
1295           g_string_append (state->buf, text);
1296         }
1297       }
1298       return NULL;
1299     case 1:
1300     {
1301       guint64 clip_start = 0, clip_stop = 0;
1302       gboolean in_seg;
1303       gchar *ret;
1304
1305       /* Looking for the end time */
1306       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1307         state->state = 0;
1308         state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1309             state->start_time;
1310       } else {
1311         GST_WARNING ("Failed to parse subtitle end time");
1312         return NULL;
1313       }
1314
1315       /* Check if this subtitle is out of the current segment */
1316       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1317           state->start_time, state->start_time + state->duration,
1318           &clip_start, &clip_stop);
1319
1320       if (!in_seg) {
1321         return NULL;
1322       }
1323
1324       state->start_time = clip_start;
1325       state->duration = clip_stop - clip_start;
1326
1327       ret = g_strdup (state->buf->str);
1328       g_string_truncate (state->buf, 0);
1329       unescape_newlines_br (ret);
1330       return ret;
1331     }
1332     default:
1333       g_assert_not_reached ();
1334       return NULL;
1335   }
1336 }
1337
1338 static void
1339 parser_state_init (ParserState * state)
1340 {
1341   GST_DEBUG ("initialising parser");
1342
1343   if (state->buf) {
1344     g_string_truncate (state->buf, 0);
1345   } else {
1346     state->buf = g_string_new (NULL);
1347   }
1348
1349   state->start_time = 0;
1350   state->duration = 0;
1351   state->max_duration = 0;      /* no limit */
1352   state->state = 0;
1353   state->segment = NULL;
1354 }
1355
1356 static void
1357 parser_state_dispose (GstSubParse * self, ParserState * state)
1358 {
1359   if (state->buf) {
1360     g_string_free (state->buf, TRUE);
1361     state->buf = NULL;
1362   }
1363
1364   g_free (state->vertical);
1365   state->vertical = NULL;
1366   g_free (state->alignment);
1367   state->alignment = NULL;
1368
1369   if (state->user_data) {
1370     switch (self->parser_type) {
1371       case GST_SUB_PARSE_FORMAT_QTTEXT:
1372         qttext_context_deinit (state);
1373         break;
1374       case GST_SUB_PARSE_FORMAT_SAMI:
1375         sami_context_deinit (state);
1376         break;
1377       default:
1378         break;
1379     }
1380   }
1381   state->allowed_tags = NULL;
1382 }
1383
1384
1385
1386 static GstCaps *
1387 gst_sub_parse_format_autodetect (GstSubParse * self)
1388 {
1389   gchar *data;
1390   GstSubParseFormat format;
1391
1392   if (strlen (self->textbuf->str) < 6) {
1393     GST_DEBUG ("File too small to be a subtitles file");
1394     return NULL;
1395   }
1396
1397   data = g_strndup (self->textbuf->str, 35);
1398   format = gst_sub_parse_data_format_autodetect (data);
1399   g_free (data);
1400
1401   self->parser_type = format;
1402   self->subtitle_codec = gst_sub_parse_get_format_description (format);
1403   parser_state_init (&self->state);
1404   self->state.allowed_tags = NULL;
1405
1406   switch (format) {
1407     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1408       self->parse_line = parse_mdvdsub;
1409       return gst_caps_new_simple ("text/x-raw",
1410           "format", G_TYPE_STRING, "pango-markup", NULL);
1411     case GST_SUB_PARSE_FORMAT_SUBRIP:
1412       self->state.allowed_tags = (gpointer) allowed_srt_tags;
1413       self->state.allows_tag_attributes = FALSE;
1414       self->parse_line = parse_subrip;
1415       return gst_caps_new_simple ("text/x-raw",
1416           "format", G_TYPE_STRING, "pango-markup", NULL);
1417     case GST_SUB_PARSE_FORMAT_MPSUB:
1418       self->parse_line = parse_mpsub;
1419       return gst_caps_new_simple ("text/x-raw",
1420           "format", G_TYPE_STRING, "utf8", NULL);
1421     case GST_SUB_PARSE_FORMAT_SAMI:
1422       self->parse_line = parse_sami;
1423       sami_context_init (&self->state);
1424       return gst_caps_new_simple ("text/x-raw",
1425           "format", G_TYPE_STRING, "pango-markup", NULL);
1426     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1427       self->parse_line = parse_tmplayer;
1428       self->state.max_duration = 5 * GST_SECOND;
1429       return gst_caps_new_simple ("text/x-raw",
1430           "format", G_TYPE_STRING, "utf8", NULL);
1431     case GST_SUB_PARSE_FORMAT_MPL2:
1432       self->parse_line = parse_mpl2;
1433       return gst_caps_new_simple ("text/x-raw",
1434           "format", G_TYPE_STRING, "pango-markup", NULL);
1435     case GST_SUB_PARSE_FORMAT_DKS:
1436       self->parse_line = parse_dks;
1437       return gst_caps_new_simple ("text/x-raw",
1438           "format", G_TYPE_STRING, "utf8", NULL);
1439     case GST_SUB_PARSE_FORMAT_VTT:
1440       self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1441       self->state.allows_tag_attributes = TRUE;
1442       self->parse_line = parse_webvtt;
1443       return gst_caps_new_simple ("text/x-raw",
1444           "format", G_TYPE_STRING, "pango-markup", NULL);
1445     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1446       self->parse_line = parse_subviewer;
1447       return gst_caps_new_simple ("text/x-raw",
1448           "format", G_TYPE_STRING, "utf8", NULL);
1449     case GST_SUB_PARSE_FORMAT_QTTEXT:
1450       self->parse_line = parse_qttext;
1451       qttext_context_init (&self->state);
1452       return gst_caps_new_simple ("text/x-raw",
1453           "format", G_TYPE_STRING, "pango-markup", NULL);
1454     case GST_SUB_PARSE_FORMAT_LRC:
1455       self->parse_line = parse_lrc;
1456       return gst_caps_new_simple ("text/x-raw",
1457           "format", G_TYPE_STRING, "utf8", NULL);
1458     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1459     default:
1460       GST_DEBUG ("no subtitle format detected");
1461       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1462           ("The input is not a valid/supported subtitle file"), (NULL));
1463       return NULL;
1464   }
1465 }
1466
1467 static void
1468 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1469 {
1470   gboolean discont;
1471   gsize consumed;
1472   gchar *input = NULL;
1473   const guint8 *data;
1474   gsize avail;
1475
1476   discont = GST_BUFFER_IS_DISCONT (buf);
1477
1478   if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1479       GST_BUFFER_OFFSET (buf) != self->offset) {
1480     self->offset = GST_BUFFER_OFFSET (buf);
1481     discont = TRUE;
1482   }
1483
1484   if (discont) {
1485     GST_INFO ("discontinuity");
1486     /* flush the parser state */
1487     parser_state_init (&self->state);
1488     g_string_truncate (self->textbuf, 0);
1489     gst_adapter_clear (self->adapter);
1490     if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1491       sami_context_reset (&self->state);
1492     /* we could set a flag to make sure that the next buffer we push out also
1493      * has the DISCONT flag set, but there's no point really given that it's
1494      * subtitles which are discontinuous by nature. */
1495   }
1496
1497   self->offset += gst_buffer_get_size (buf);
1498
1499   gst_adapter_push (self->adapter, buf);
1500
1501   avail = gst_adapter_available (self->adapter);
1502   data = gst_adapter_map (self->adapter, avail);
1503   input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1504
1505   if (input && consumed > 0) {
1506     self->textbuf = g_string_append (self->textbuf, input);
1507     gst_adapter_unmap (self->adapter);
1508     gst_adapter_flush (self->adapter, consumed);
1509   } else {
1510     gst_adapter_unmap (self->adapter);
1511   }
1512
1513   g_free (input);
1514 }
1515
1516
1517 static void
1518 xml_text (GMarkupParseContext * context,
1519     const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1520 {
1521   gchar **accum = (gchar **) user_data;
1522   gchar *concat;
1523
1524   if (*accum) {
1525     concat = g_strconcat (*accum, text, NULL);
1526     g_free (*accum);
1527     *accum = concat;
1528   } else {
1529     *accum = g_strdup (text);
1530   }
1531 }
1532
1533 static gchar *
1534 strip_pango_markup (gchar * markup, GError ** error)
1535 {
1536   GMarkupParser parser = { 0, };
1537   GMarkupParseContext *context;
1538   gchar *accum = NULL;
1539
1540   parser.text = xml_text;
1541   context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1542
1543   g_markup_parse_context_parse (context, "<root>", 6, NULL);
1544   g_markup_parse_context_parse (context, markup, strlen (markup), error);
1545   g_markup_parse_context_parse (context, "</root>", 7, NULL);
1546   if (*error)
1547     goto error;
1548
1549   g_markup_parse_context_end_parse (context, error);
1550   if (*error)
1551     goto error;
1552
1553 done:
1554   g_markup_parse_context_free (context);
1555   return accum;
1556
1557 error:
1558   g_free (accum);
1559   accum = NULL;
1560   goto done;
1561 }
1562
1563 static gboolean
1564 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1565 {
1566   GstCaps *caps;
1567   gboolean ret = FALSE;
1568   const GstStructure *s1, *s2;
1569
1570   caps = gst_pad_get_allowed_caps (self->srcpad);
1571
1572   s1 = gst_caps_get_structure (preferred, 0);
1573
1574   if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1575     GstCaps *intersected = gst_caps_intersect (caps, preferred);
1576     gst_caps_unref (caps);
1577     caps = intersected;
1578   }
1579
1580   caps = gst_caps_fixate (caps);
1581
1582   if (gst_caps_is_empty (caps)) {
1583     goto done;
1584   }
1585
1586   s2 = gst_caps_get_structure (caps, 0);
1587
1588   self->strip_pango_markup =
1589       !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1590       && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1591
1592   if (self->strip_pango_markup) {
1593     GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1594   }
1595
1596   ret = gst_pad_set_caps (self->srcpad, caps);
1597
1598 done:
1599   gst_caps_unref (caps);
1600   return ret;
1601 }
1602
1603 static GstFlowReturn
1604 check_initial_events (GstSubParse * self)
1605 {
1606   gboolean need_tags = FALSE;
1607
1608   /* make sure we know the format */
1609   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1610     GstCaps *preferred;
1611
1612     if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1613       return GST_FLOW_NOT_NEGOTIATED;
1614     }
1615
1616     if (!gst_sub_parse_negotiate (self, preferred)) {
1617       gst_caps_unref (preferred);
1618       return GST_FLOW_NOT_NEGOTIATED;
1619     }
1620
1621     gst_caps_unref (preferred);
1622
1623     need_tags = TRUE;
1624   }
1625
1626   /* Push newsegment if needed */
1627   if (self->need_segment) {
1628     GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1629         &self->segment);
1630
1631     gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1632     self->need_segment = FALSE;
1633   }
1634
1635   if (need_tags) {
1636     /* push tags */
1637     if (self->subtitle_codec != NULL) {
1638       GstTagList *tags;
1639
1640       tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1641           NULL);
1642       gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1643     }
1644   }
1645
1646   return GST_FLOW_OK;
1647 }
1648
1649 static GstFlowReturn
1650 handle_buffer (GstSubParse * self, GstBuffer * buf)
1651 {
1652   GstFlowReturn ret = GST_FLOW_OK;
1653   gchar *line, *subtitle;
1654
1655   GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT, buf);
1656
1657   if (self->first_buffer) {
1658     GstMapInfo map;
1659
1660     gst_buffer_map (buf, &map, GST_MAP_READ);
1661     self->detected_encoding =
1662         gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1663     gst_buffer_unmap (buf, &map);
1664     self->first_buffer = FALSE;
1665     self->state.fps_n = self->fps_n;
1666     self->state.fps_d = self->fps_d;
1667   }
1668
1669   feed_textbuf (self, buf);
1670
1671   ret = check_initial_events (self);
1672   if (ret != GST_FLOW_OK)
1673     return ret;
1674
1675   while (!self->flushing && (line = get_next_line (self))) {
1676     guint offset = 0;
1677
1678     /* Set segment on our parser state machine */
1679     self->state.segment = &self->segment;
1680     /* Now parse the line, out of segment lines will just return NULL */
1681     GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1682         line + offset);
1683     subtitle = self->parse_line (&self->state, line + offset);
1684     g_free (line);
1685
1686     if (subtitle) {
1687       guint subtitle_len;
1688
1689       if (self->strip_pango_markup) {
1690         GError *error = NULL;
1691         gchar *stripped;
1692
1693         if ((stripped = strip_pango_markup (subtitle, &error))) {
1694           g_free (subtitle);
1695           subtitle = stripped;
1696         } else {
1697           GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1698               error->message);
1699         }
1700       }
1701
1702       subtitle_len = strlen (subtitle);
1703
1704       /* +1 for terminating NUL character */
1705       buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1706
1707       /* copy terminating NUL character as well */
1708       gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1709       gst_buffer_set_size (buf, subtitle_len);
1710
1711       GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1712       GST_BUFFER_DURATION (buf) = self->state.duration;
1713
1714       /* in some cases (e.g. tmplayer) we can only determine the duration
1715        * of a text chunk from the timestamp of the next text chunk; in those
1716        * cases, we probably want to limit the duration to something
1717        * reasonable, so we don't end up showing some text for e.g. 40 seconds
1718        * just because nothing else is being said during that time */
1719       if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1720         if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1721           GST_BUFFER_DURATION (buf) = self->state.max_duration;
1722       }
1723
1724       self->segment.position = self->state.start_time;
1725
1726       GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1727           GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1728           GST_TIME_ARGS (self->state.duration));
1729
1730       g_free (self->state.vertical);
1731       self->state.vertical = NULL;
1732       g_free (self->state.alignment);
1733       self->state.alignment = NULL;
1734
1735       ret = gst_pad_push (self->srcpad, buf);
1736
1737       /* move this forward (the tmplayer parser needs this) */
1738       if (self->state.duration != GST_CLOCK_TIME_NONE)
1739         self->state.start_time += self->state.duration;
1740
1741       g_free (subtitle);
1742       subtitle = NULL;
1743
1744       if (ret != GST_FLOW_OK) {
1745         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1746         break;
1747       }
1748     }
1749   }
1750
1751   return ret;
1752 }
1753
1754 static GstFlowReturn
1755 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1756 {
1757   GstFlowReturn ret;
1758   GstSubParse *self;
1759
1760   self = GST_SUBPARSE (parent);
1761
1762   ret = handle_buffer (self, buf);
1763
1764   return ret;
1765 }
1766
1767 static gboolean
1768 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1769 {
1770   GstSubParse *self = GST_SUBPARSE (parent);
1771   gboolean ret = FALSE;
1772
1773   GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
1774
1775   switch (GST_EVENT_TYPE (event)) {
1776     case GST_EVENT_STREAM_GROUP_DONE:
1777     case GST_EVENT_EOS:{
1778       /* Make sure the last subrip chunk is pushed out even
1779        * if the file does not have an empty line at the end */
1780       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1781           self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1782           self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1783           self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
1784           self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
1785         gchar term_chars[] = { '\n', '\n', '\0' };
1786         GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1787
1788         GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
1789             GST_EVENT_TYPE_NAME (event));
1790
1791         gst_buffer_fill (buf, 0, term_chars, 3);
1792         gst_buffer_set_size (buf, 2);
1793
1794         GST_BUFFER_OFFSET (buf) = self->offset;
1795         gst_sub_parse_chain (pad, parent, buf);
1796       }
1797       ret = gst_pad_event_default (pad, parent, event);
1798       break;
1799     }
1800     case GST_EVENT_SEGMENT:
1801     {
1802       const GstSegment *s;
1803       gst_event_parse_segment (event, &s);
1804       if (s->format == GST_FORMAT_TIME)
1805         gst_event_copy_segment (event, &self->segment);
1806       GST_DEBUG_OBJECT (self, "newsegment (%s)",
1807           gst_format_get_name (self->segment.format));
1808
1809       /* if not time format, we'll either start with a 0 timestamp anyway or
1810        * it's following a seek in which case we'll have saved the requested
1811        * seek segment and don't want to overwrite it (remember that on a seek
1812        * we always just seek back to the start in BYTES format and just throw
1813        * away all text that's before the requested position; if the subtitles
1814        * come from an upstream demuxer, it won't be able to handle our BYTES
1815        * seek request and instead send us a newsegment from the seek request
1816        * it received via its video pads instead, so all is fine then too) */
1817       ret = TRUE;
1818       gst_event_unref (event);
1819       /* in either case, let's not simply discard this event;
1820        * trigger sending of the saved requested seek segment
1821        * or the one taken here from upstream */
1822       self->need_segment = TRUE;
1823       break;
1824     }
1825     case GST_EVENT_GAP:
1826     {
1827       ret = check_initial_events (self);
1828       if (ret == GST_FLOW_OK) {
1829         ret = gst_pad_event_default (pad, parent, event);
1830       } else {
1831         gst_event_unref (event);
1832       }
1833       break;
1834     }
1835     case GST_EVENT_FLUSH_START:
1836     {
1837       self->flushing = TRUE;
1838
1839       ret = gst_pad_event_default (pad, parent, event);
1840       break;
1841     }
1842     case GST_EVENT_FLUSH_STOP:
1843     {
1844       self->flushing = FALSE;
1845
1846       ret = gst_pad_event_default (pad, parent, event);
1847       break;
1848     }
1849     default:
1850       ret = gst_pad_event_default (pad, parent, event);
1851       break;
1852   }
1853
1854   return ret;
1855 }
1856
1857
1858 static GstStateChangeReturn
1859 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1860 {
1861   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1862   GstSubParse *self = GST_SUBPARSE (element);
1863
1864   switch (transition) {
1865     case GST_STATE_CHANGE_READY_TO_PAUSED:
1866       /* format detection will init the parser state */
1867       self->offset = 0;
1868       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1869       self->strip_pango_markup = FALSE;
1870       self->valid_utf8 = TRUE;
1871       self->first_buffer = TRUE;
1872       g_free (self->detected_encoding);
1873       self->detected_encoding = NULL;
1874       g_string_truncate (self->textbuf, 0);
1875       gst_adapter_clear (self->adapter);
1876       break;
1877     default:
1878       break;
1879   }
1880
1881   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1882   if (ret == GST_STATE_CHANGE_FAILURE)
1883     return ret;
1884
1885   switch (transition) {
1886     case GST_STATE_CHANGE_PAUSED_TO_READY:
1887       parser_state_dispose (self, &self->state);
1888       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1889       break;
1890     default:
1891       break;
1892   }
1893
1894   return ret;
1895 }