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