Merging gst-devtools
[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     g_warning ("Parse 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", end_tag - 1);
789           memmove (next_tag, end_tag + 1, strlen (end_tag) + 1);
790           next_tag -= strlen (end_tag);
791         } else {
792           --num_open_tags;
793           g_ptr_array_remove_index (open_tags, num_open_tags);
794         }
795       }
796     }
797     ++next_tag;
798     cur = next_tag;
799   }
800
801   if (num_open_tags > 0) {
802     GString *s;
803
804     s = g_string_new (*p_txt);
805     while (num_open_tags > 0) {
806       GST_LOG ("adding missing closing tag '%s'",
807           (char *) g_ptr_array_index (open_tags, num_open_tags - 1));
808       g_string_append_c (s, '<');
809       g_string_append_c (s, '/');
810       g_string_append (s, g_ptr_array_index (open_tags, num_open_tags - 1));
811       g_string_append_c (s, '>');
812       --num_open_tags;
813     }
814     g_free (*p_txt);
815     *p_txt = g_string_free (s, FALSE);
816   }
817   g_ptr_array_free (open_tags, TRUE);
818 }
819
820 static gboolean
821 parse_subrip_time (const gchar * ts_string, GstClockTime * t)
822 {
823   gchar s[128] = { '\0', };
824   gchar *end, *p;
825   guint hour, min, sec, msec, len;
826
827   while (*ts_string == ' ')
828     ++ts_string;
829
830   g_strlcpy (s, ts_string, sizeof (s));
831   if ((end = strstr (s, "-->")))
832     *end = '\0';
833   g_strchomp (s);
834
835   /* ms may be in these formats:
836    * hh:mm:ss,500 = 500ms
837    * hh:mm:ss,  5 =   5ms
838    * hh:mm:ss, 5  =  50ms
839    * hh:mm:ss, 50 =  50ms
840    * hh:mm:ss,5   = 500ms
841    * and the same with . instead of ,.
842    * sscanf() doesn't differentiate between '  5' and '5' so munge
843    * the white spaces within the timestamp to '0' (I'm sure there's a
844    * way to make sscanf() do this for us, but how?)
845    */
846   g_strdelimit (s, " ", '0');
847   g_strdelimit (s, ".", ',');
848
849   /* make sure we have exactly three digits after he comma */
850   p = strchr (s, ',');
851   if (p == NULL) {
852     /* If there isn't a ',' the timestamp is broken */
853     /* https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/issues/532#note_100179 */
854     GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
855     return FALSE;
856   }
857
858   ++p;
859   len = strlen (p);
860   if (len > 3) {
861     p[3] = '\0';
862   } else
863     while (len < 3) {
864       g_strlcat (&p[len], "0", 2);
865       ++len;
866     }
867
868   GST_LOG ("parsing timestamp '%s'", s);
869   if (sscanf (s, "%u:%u:%u,%u", &hour, &min, &sec, &msec) != 4) {
870     /* https://www.w3.org/TR/webvtt1/#webvtt-timestamp
871      *
872      * The hours component is optional with webVTT, for example
873      * mm:ss,500 is a valid webVTT timestamp. When not present,
874      * hours is 0.
875      */
876     hour = 0;
877
878     if (sscanf (s, "%u:%u,%u", &min, &sec, &msec) != 3) {
879       GST_WARNING ("failed to parse subrip timestamp string '%s'", s);
880       return FALSE;
881     }
882   }
883
884   *t = ((hour * 3600) + (min * 60) + sec) * GST_SECOND + msec * GST_MSECOND;
885   return TRUE;
886 }
887
888 /* cue settings are part of the WebVTT specification. They are
889  * declared after the time interval in the first line of the
890  * cue. Example: 00:00:01,000 --> 00:00:02,000 D:vertical-lr A:start
891  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
892  */
893 static void
894 parse_webvtt_cue_settings (ParserState * state, const gchar * settings)
895 {
896   gchar **splitted_settings = g_strsplit_set (settings, " \t", -1);
897   gint i = 0;
898   gint16 text_position, text_size;
899   gint16 line_position;
900   gboolean vertical_found = FALSE;
901   gboolean alignment_found = FALSE;
902
903   while (i < g_strv_length (splitted_settings)) {
904     gboolean valid_tag = FALSE;
905     switch (splitted_settings[i][0]) {
906       case 'T':
907         if (sscanf (splitted_settings[i], "T:%" G_GINT16_FORMAT "%%",
908                 &text_position) > 0) {
909           state->text_position = (guint8) text_position;
910           valid_tag = TRUE;
911         }
912         break;
913       case 'D':
914         if (strlen (splitted_settings[i]) > 2) {
915           vertical_found = TRUE;
916           g_free (state->vertical);
917           state->vertical = g_strdup (splitted_settings[i] + 2);
918           valid_tag = TRUE;
919         }
920         break;
921       case 'L':
922         if (g_str_has_suffix (splitted_settings[i], "%")) {
923           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT "%%",
924                   &line_position) > 0) {
925             state->line_position = line_position;
926             valid_tag = TRUE;
927           }
928         } else {
929           if (sscanf (splitted_settings[i], "L:%" G_GINT16_FORMAT,
930                   &line_position) > 0) {
931             state->line_number = line_position;
932             valid_tag = TRUE;
933           }
934         }
935         break;
936       case 'S':
937         if (sscanf (splitted_settings[i], "S:%" G_GINT16_FORMAT "%%",
938                 &text_size) > 0) {
939           state->text_size = (guint8) text_size;
940           valid_tag = TRUE;
941         }
942         break;
943       case 'A':
944         if (strlen (splitted_settings[i]) > 2) {
945           g_free (state->alignment);
946           state->alignment = g_strdup (splitted_settings[i] + 2);
947           alignment_found = TRUE;
948           valid_tag = TRUE;
949         }
950         break;
951       default:
952         break;
953     }
954     if (!valid_tag) {
955       GST_LOG ("Invalid or unrecognised setting found: %s",
956           splitted_settings[i]);
957     }
958     i++;
959   }
960   g_strfreev (splitted_settings);
961   if (!vertical_found) {
962     g_free (state->vertical);
963     state->vertical = g_strdup ("");
964   }
965   if (!alignment_found) {
966     g_free (state->alignment);
967     state->alignment = g_strdup ("");
968   }
969 }
970
971 static gchar *
972 parse_subrip (ParserState * state, const gchar * line)
973 {
974   gchar *ret;
975
976   switch (state->state) {
977     case 0:{
978       char *endptr;
979       guint64 id;
980
981       /* looking for a single integer as a Cue ID, but we
982        * don't actually use it */
983       errno = 0;
984       id = g_ascii_strtoull (line, &endptr, 10);
985       if (id == G_MAXUINT64 && errno == ERANGE)
986         state->state = 1;
987       else if (id == 0 && errno == EINVAL)
988         state->state = 1;
989       else if (endptr != line && *endptr == '\0')
990         state->state = 1;
991       return NULL;
992     }
993     case 1:
994     {
995       GstClockTime ts_start, ts_end;
996       gchar *end_time;
997
998       /* looking for start_time --> end_time */
999       if ((end_time = strstr (line, " --> ")) &&
1000           parse_subrip_time (line, &ts_start) &&
1001           parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1002           state->start_time <= ts_end) {
1003         state->state = 2;
1004         state->start_time = ts_start;
1005         state->duration = ts_end - ts_start;
1006       } else {
1007         GST_DEBUG ("error parsing subrip time line '%s'", line);
1008         state->state = 0;
1009       }
1010       return NULL;
1011     }
1012     case 2:
1013     {
1014       /* No need to parse that text if it's out of segment */
1015       guint64 clip_start = 0, clip_stop = 0;
1016       gboolean in_seg = FALSE;
1017
1018       /* Check our segment start/stop */
1019       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1020           state->start_time, state->start_time + state->duration,
1021           &clip_start, &clip_stop);
1022
1023       if (in_seg) {
1024         state->start_time = clip_start;
1025         state->duration = clip_stop - clip_start;
1026       } else {
1027         state->state = 0;
1028         return NULL;
1029       }
1030     }
1031       /* looking for subtitle text; empty line ends this subtitle entry */
1032       if (state->buf->len)
1033         g_string_append_c (state->buf, '\n');
1034       g_string_append (state->buf, line);
1035       if (strlen (line) == 0) {
1036         ret = g_markup_escape_text (state->buf->str, state->buf->len);
1037         g_string_truncate (state->buf, 0);
1038         state->state = 0;
1039         subrip_unescape_formatting (ret, state->allowed_tags,
1040             state->allows_tag_attributes);
1041         subrip_remove_unhandled_tags (ret);
1042         strip_trailing_newlines (ret);
1043         subrip_fix_up_markup (&ret, state->allowed_tags);
1044         return ret;
1045       }
1046       return NULL;
1047     default:
1048       g_return_val_if_reached (NULL);
1049   }
1050 }
1051
1052 static gchar *
1053 parse_lrc (ParserState * state, const gchar * line)
1054 {
1055   gint m, s, c;
1056   const gchar *start;
1057   gint milli;
1058
1059   if (line[0] != '[')
1060     return NULL;
1061
1062   if (sscanf (line, "[%u:%02u.%03u]", &m, &s, &c) != 3 &&
1063       sscanf (line, "[%u:%02u.%02u]", &m, &s, &c) != 3)
1064     return NULL;
1065
1066   start = strchr (line, ']');
1067   if (start - line == 9)
1068     milli = 10;
1069   else
1070     milli = 1;
1071
1072   state->start_time = gst_util_uint64_scale (m, 60 * GST_SECOND, 1)
1073       + gst_util_uint64_scale (s, GST_SECOND, 1)
1074       + gst_util_uint64_scale (c, milli * GST_MSECOND, 1);
1075   state->duration = GST_CLOCK_TIME_NONE;
1076
1077   return g_strdup (start + 1);
1078 }
1079
1080 /* WebVTT is a new subtitle format for the upcoming HTML5 video track
1081  * element. This format is similar to Subrip, the biggest differences
1082  * are that there can be cue settings detailing how to display the cue
1083  * text and more markup tags are allowed.
1084  * See also http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
1085  */
1086 static gchar *
1087 parse_webvtt (ParserState * state, const gchar * line)
1088 {
1089   /* Cue IDs are optional in WebVTT, but not in subrip,
1090    * so when in state 0 (cue ID), also check if we're
1091    * already at the start --> end time marker */
1092   if (state->state == 0 || state->state == 1) {
1093     GstClockTime ts_start, ts_end;
1094     gchar *end_time;
1095     gchar *cue_settings = NULL;
1096
1097     /* looking for start_time --> end_time */
1098     if ((end_time = strstr (line, " --> ")) &&
1099         parse_subrip_time (line, &ts_start) &&
1100         parse_subrip_time (end_time + strlen (" --> "), &ts_end) &&
1101         state->start_time <= ts_end) {
1102       state->state = 2;
1103       state->start_time = ts_start;
1104       state->duration = ts_end - ts_start;
1105       cue_settings = strstr (end_time + strlen (" --> "), " ");
1106     } else {
1107       GST_DEBUG ("error parsing subrip time line '%s'", line);
1108       state->state = 0;
1109     }
1110
1111     state->text_position = 0;
1112     state->text_size = 0;
1113     state->line_position = 0;
1114     state->line_number = 0;
1115
1116     if (cue_settings)
1117       parse_webvtt_cue_settings (state, cue_settings + 1);
1118     else {
1119       g_free (state->vertical);
1120       state->vertical = g_strdup ("");
1121       g_free (state->alignment);
1122       state->alignment = g_strdup ("");
1123     }
1124
1125     return NULL;
1126   } else
1127     return parse_subrip (state, line);
1128 }
1129
1130 static void
1131 unescape_newlines_br (gchar * read)
1132 {
1133   gchar *write = read;
1134
1135   /* Replace all occurrences of '[br]' with a newline as version 2
1136    * of the subviewer format uses this for newlines */
1137
1138   if (read[0] == '\0' || read[1] == '\0' || read[2] == '\0' || read[3] == '\0')
1139     return;
1140
1141   do {
1142     if (strncmp (read, "[br]", 4) == 0) {
1143       *write = '\n';
1144       read += 4;
1145     } else {
1146       *write = *read;
1147       read++;
1148     }
1149     write++;
1150   } while (*read);
1151
1152   *write = '\0';
1153 }
1154
1155 static gchar *
1156 parse_subviewer (ParserState * state, const gchar * line)
1157 {
1158   guint h1, m1, s1, ms1;
1159   guint h2, m2, s2, ms2;
1160   gchar *ret;
1161
1162   /* TODO: Maybe also parse the fields in the header, especially DELAY.
1163    * For examples see the unit test or
1164    * http://www.doom9.org/index.html?/sub.htm */
1165
1166   switch (state->state) {
1167     case 0:
1168       /* looking for start_time,end_time */
1169       if (sscanf (line, "%u:%u:%u.%u,%u:%u:%u.%u",
1170               &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
1171         state->state = 1;
1172         state->start_time =
1173             (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
1174             ms1 * GST_MSECOND;
1175         state->duration =
1176             (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
1177             ms2 * GST_MSECOND - state->start_time;
1178       }
1179       return NULL;
1180     case 1:
1181     {
1182       /* No need to parse that text if it's out of segment */
1183       guint64 clip_start = 0, clip_stop = 0;
1184       gboolean in_seg = FALSE;
1185
1186       /* Check our segment start/stop */
1187       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1188           state->start_time, state->start_time + state->duration,
1189           &clip_start, &clip_stop);
1190
1191       if (in_seg) {
1192         state->start_time = clip_start;
1193         state->duration = clip_stop - clip_start;
1194       } else {
1195         state->state = 0;
1196         return NULL;
1197       }
1198     }
1199       /* looking for subtitle text; empty line ends this subtitle entry */
1200       if (state->buf->len)
1201         g_string_append_c (state->buf, '\n');
1202       g_string_append (state->buf, line);
1203       if (strlen (line) == 0) {
1204         ret = g_strdup (state->buf->str);
1205         unescape_newlines_br (ret);
1206         strip_trailing_newlines (ret);
1207         g_string_truncate (state->buf, 0);
1208         state->state = 0;
1209         return ret;
1210       }
1211       return NULL;
1212     default:
1213       g_assert_not_reached ();
1214       return NULL;
1215   }
1216 }
1217
1218 static gchar *
1219 parse_mpsub (ParserState * state, const gchar * line)
1220 {
1221   gchar *ret;
1222   float t1, t2;
1223
1224   switch (state->state) {
1225     case 0:
1226       /* looking for two floats (offset, duration) */
1227       if (sscanf (line, "%f %f", &t1, &t2) == 2) {
1228         state->state = 1;
1229         state->start_time += state->duration + GST_SECOND * t1;
1230         state->duration = GST_SECOND * t2;
1231       }
1232       return NULL;
1233     case 1:
1234     {                           /* No need to parse that text if it's out of segment */
1235       guint64 clip_start = 0, clip_stop = 0;
1236       gboolean in_seg = FALSE;
1237
1238       /* Check our segment start/stop */
1239       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1240           state->start_time, state->start_time + state->duration,
1241           &clip_start, &clip_stop);
1242
1243       if (in_seg) {
1244         state->start_time = clip_start;
1245         state->duration = clip_stop - clip_start;
1246       } else {
1247         state->state = 0;
1248         return NULL;
1249       }
1250     }
1251       /* looking for subtitle text; empty line ends this
1252        * subtitle entry */
1253       if (state->buf->len)
1254         g_string_append_c (state->buf, '\n');
1255       g_string_append (state->buf, line);
1256       if (strlen (line) == 0) {
1257         ret = g_strdup (state->buf->str);
1258         g_string_truncate (state->buf, 0);
1259         state->state = 0;
1260         return ret;
1261       }
1262       return NULL;
1263     default:
1264       g_assert_not_reached ();
1265       return NULL;
1266   }
1267 }
1268
1269 static const gchar *
1270 dks_skip_timestamp (const gchar * line)
1271 {
1272   while (*line && *line != ']')
1273     line++;
1274   if (*line == ']')
1275     line++;
1276   return line;
1277 }
1278
1279 static gchar *
1280 parse_dks (ParserState * state, const gchar * line)
1281 {
1282   guint h, m, s;
1283
1284   switch (state->state) {
1285     case 0:
1286       /* Looking for the start time and text */
1287       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1288         const gchar *text;
1289         state->start_time = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND;
1290         text = dks_skip_timestamp (line);
1291         if (*text) {
1292           state->state = 1;
1293           g_string_append (state->buf, text);
1294         }
1295       }
1296       return NULL;
1297     case 1:
1298     {
1299       guint64 clip_start = 0, clip_stop = 0;
1300       gboolean in_seg;
1301       gchar *ret;
1302
1303       /* Looking for the end time */
1304       if (sscanf (line, "[%u:%u:%u]", &h, &m, &s) == 3) {
1305         state->state = 0;
1306         state->duration = (((guint64) h) * 3600 + m * 60 + s) * GST_SECOND -
1307             state->start_time;
1308       } else {
1309         GST_WARNING ("Failed to parse subtitle end time");
1310         return NULL;
1311       }
1312
1313       /* Check if this subtitle is out of the current segment */
1314       in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
1315           state->start_time, state->start_time + state->duration,
1316           &clip_start, &clip_stop);
1317
1318       if (!in_seg) {
1319         return NULL;
1320       }
1321
1322       state->start_time = clip_start;
1323       state->duration = clip_stop - clip_start;
1324
1325       ret = g_strdup (state->buf->str);
1326       g_string_truncate (state->buf, 0);
1327       unescape_newlines_br (ret);
1328       return ret;
1329     }
1330     default:
1331       g_assert_not_reached ();
1332       return NULL;
1333   }
1334 }
1335
1336 static void
1337 parser_state_init (ParserState * state)
1338 {
1339   GST_DEBUG ("initialising parser");
1340
1341   if (state->buf) {
1342     g_string_truncate (state->buf, 0);
1343   } else {
1344     state->buf = g_string_new (NULL);
1345   }
1346
1347   state->start_time = 0;
1348   state->duration = 0;
1349   state->max_duration = 0;      /* no limit */
1350   state->state = 0;
1351   state->segment = NULL;
1352 }
1353
1354 static void
1355 parser_state_dispose (GstSubParse * self, ParserState * state)
1356 {
1357   if (state->buf) {
1358     g_string_free (state->buf, TRUE);
1359     state->buf = NULL;
1360   }
1361
1362   g_free (state->vertical);
1363   state->vertical = NULL;
1364   g_free (state->alignment);
1365   state->alignment = NULL;
1366
1367   if (state->user_data) {
1368     switch (self->parser_type) {
1369       case GST_SUB_PARSE_FORMAT_QTTEXT:
1370         qttext_context_deinit (state);
1371         break;
1372       case GST_SUB_PARSE_FORMAT_SAMI:
1373         sami_context_deinit (state);
1374         break;
1375       default:
1376         break;
1377     }
1378   }
1379   state->allowed_tags = NULL;
1380 }
1381
1382
1383
1384 static GstCaps *
1385 gst_sub_parse_format_autodetect (GstSubParse * self)
1386 {
1387   gchar *data;
1388   GstSubParseFormat format;
1389
1390   if (strlen (self->textbuf->str) < 6) {
1391     GST_DEBUG ("File too small to be a subtitles file");
1392     return NULL;
1393   }
1394
1395   data = g_strndup (self->textbuf->str, 35);
1396   format = gst_sub_parse_data_format_autodetect (data);
1397   g_free (data);
1398
1399   self->parser_type = format;
1400   self->subtitle_codec = gst_sub_parse_get_format_description (format);
1401   parser_state_init (&self->state);
1402   self->state.allowed_tags = NULL;
1403
1404   switch (format) {
1405     case GST_SUB_PARSE_FORMAT_MDVDSUB:
1406       self->parse_line = parse_mdvdsub;
1407       return gst_caps_new_simple ("text/x-raw",
1408           "format", G_TYPE_STRING, "pango-markup", NULL);
1409     case GST_SUB_PARSE_FORMAT_SUBRIP:
1410       self->state.allowed_tags = (gpointer) allowed_srt_tags;
1411       self->state.allows_tag_attributes = FALSE;
1412       self->parse_line = parse_subrip;
1413       return gst_caps_new_simple ("text/x-raw",
1414           "format", G_TYPE_STRING, "pango-markup", NULL);
1415     case GST_SUB_PARSE_FORMAT_MPSUB:
1416       self->parse_line = parse_mpsub;
1417       return gst_caps_new_simple ("text/x-raw",
1418           "format", G_TYPE_STRING, "utf8", NULL);
1419     case GST_SUB_PARSE_FORMAT_SAMI:
1420       self->parse_line = parse_sami;
1421       sami_context_init (&self->state);
1422       return gst_caps_new_simple ("text/x-raw",
1423           "format", G_TYPE_STRING, "pango-markup", NULL);
1424     case GST_SUB_PARSE_FORMAT_TMPLAYER:
1425       self->parse_line = parse_tmplayer;
1426       self->state.max_duration = 5 * GST_SECOND;
1427       return gst_caps_new_simple ("text/x-raw",
1428           "format", G_TYPE_STRING, "utf8", NULL);
1429     case GST_SUB_PARSE_FORMAT_MPL2:
1430       self->parse_line = parse_mpl2;
1431       return gst_caps_new_simple ("text/x-raw",
1432           "format", G_TYPE_STRING, "pango-markup", NULL);
1433     case GST_SUB_PARSE_FORMAT_DKS:
1434       self->parse_line = parse_dks;
1435       return gst_caps_new_simple ("text/x-raw",
1436           "format", G_TYPE_STRING, "utf8", NULL);
1437     case GST_SUB_PARSE_FORMAT_VTT:
1438       self->state.allowed_tags = (gpointer) allowed_vtt_tags;
1439       self->state.allows_tag_attributes = TRUE;
1440       self->parse_line = parse_webvtt;
1441       return gst_caps_new_simple ("text/x-raw",
1442           "format", G_TYPE_STRING, "pango-markup", NULL);
1443     case GST_SUB_PARSE_FORMAT_SUBVIEWER:
1444       self->parse_line = parse_subviewer;
1445       return gst_caps_new_simple ("text/x-raw",
1446           "format", G_TYPE_STRING, "utf8", NULL);
1447     case GST_SUB_PARSE_FORMAT_QTTEXT:
1448       self->parse_line = parse_qttext;
1449       qttext_context_init (&self->state);
1450       return gst_caps_new_simple ("text/x-raw",
1451           "format", G_TYPE_STRING, "pango-markup", NULL);
1452     case GST_SUB_PARSE_FORMAT_LRC:
1453       self->parse_line = parse_lrc;
1454       return gst_caps_new_simple ("text/x-raw",
1455           "format", G_TYPE_STRING, "utf8", NULL);
1456     case GST_SUB_PARSE_FORMAT_UNKNOWN:
1457     default:
1458       GST_DEBUG ("no subtitle format detected");
1459       GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
1460           ("The input is not a valid/supported subtitle file"), (NULL));
1461       return NULL;
1462   }
1463 }
1464
1465 static void
1466 feed_textbuf (GstSubParse * self, GstBuffer * buf)
1467 {
1468   gboolean discont;
1469   gsize consumed;
1470   gchar *input = NULL;
1471   const guint8 *data;
1472   gsize avail;
1473
1474   discont = GST_BUFFER_IS_DISCONT (buf);
1475
1476   if (GST_BUFFER_OFFSET_IS_VALID (buf) &&
1477       GST_BUFFER_OFFSET (buf) != self->offset) {
1478     self->offset = GST_BUFFER_OFFSET (buf);
1479     discont = TRUE;
1480   }
1481
1482   if (discont) {
1483     GST_INFO ("discontinuity");
1484     /* flush the parser state */
1485     parser_state_init (&self->state);
1486     g_string_truncate (self->textbuf, 0);
1487     gst_adapter_clear (self->adapter);
1488     if (self->parser_type == GST_SUB_PARSE_FORMAT_SAMI)
1489       sami_context_reset (&self->state);
1490     /* we could set a flag to make sure that the next buffer we push out also
1491      * has the DISCONT flag set, but there's no point really given that it's
1492      * subtitles which are discontinuous by nature. */
1493   }
1494
1495   self->offset += gst_buffer_get_size (buf);
1496
1497   gst_adapter_push (self->adapter, buf);
1498
1499   avail = gst_adapter_available (self->adapter);
1500   data = gst_adapter_map (self->adapter, avail);
1501   input = convert_encoding (self, (const gchar *) data, avail, &consumed);
1502
1503   if (input && consumed > 0) {
1504     self->textbuf = g_string_append (self->textbuf, input);
1505     gst_adapter_unmap (self->adapter);
1506     gst_adapter_flush (self->adapter, consumed);
1507   } else {
1508     gst_adapter_unmap (self->adapter);
1509   }
1510
1511   g_free (input);
1512 }
1513
1514
1515 static void
1516 xml_text (GMarkupParseContext * context,
1517     const gchar * text, gsize text_len, gpointer user_data, GError ** error)
1518 {
1519   gchar **accum = (gchar **) user_data;
1520   gchar *concat;
1521
1522   if (*accum) {
1523     concat = g_strconcat (*accum, text, NULL);
1524     g_free (*accum);
1525     *accum = concat;
1526   } else {
1527     *accum = g_strdup (text);
1528   }
1529 }
1530
1531 static gchar *
1532 strip_pango_markup (gchar * markup, GError ** error)
1533 {
1534   GMarkupParser parser = { 0, };
1535   GMarkupParseContext *context;
1536   gchar *accum = NULL;
1537
1538   parser.text = xml_text;
1539   context = g_markup_parse_context_new (&parser, 0, &accum, NULL);
1540
1541   g_markup_parse_context_parse (context, "<root>", 6, NULL);
1542   g_markup_parse_context_parse (context, markup, strlen (markup), error);
1543   g_markup_parse_context_parse (context, "</root>", 7, NULL);
1544   if (*error)
1545     goto error;
1546
1547   g_markup_parse_context_end_parse (context, error);
1548   if (*error)
1549     goto error;
1550
1551 done:
1552   g_markup_parse_context_free (context);
1553   return accum;
1554
1555 error:
1556   g_free (accum);
1557   accum = NULL;
1558   goto done;
1559 }
1560
1561 static gboolean
1562 gst_sub_parse_negotiate (GstSubParse * self, GstCaps * preferred)
1563 {
1564   GstCaps *caps;
1565   gboolean ret = FALSE;
1566   const GstStructure *s1, *s2;
1567
1568   caps = gst_pad_get_allowed_caps (self->srcpad);
1569
1570   s1 = gst_caps_get_structure (preferred, 0);
1571
1572   if (!g_strcmp0 (gst_structure_get_string (s1, "format"), "utf8")) {
1573     GstCaps *intersected = gst_caps_intersect (caps, preferred);
1574     gst_caps_unref (caps);
1575     caps = intersected;
1576   }
1577
1578   caps = gst_caps_fixate (caps);
1579
1580   if (gst_caps_is_empty (caps)) {
1581     goto done;
1582   }
1583
1584   s2 = gst_caps_get_structure (caps, 0);
1585
1586   self->strip_pango_markup =
1587       !g_strcmp0 (gst_structure_get_string (s2, "format"), "utf8")
1588       && !g_strcmp0 (gst_structure_get_string (s1, "format"), "pango-markup");
1589
1590   if (self->strip_pango_markup) {
1591     GST_INFO_OBJECT (self, "We will convert from pango-markup to utf8");
1592   }
1593
1594   ret = gst_pad_set_caps (self->srcpad, caps);
1595
1596 done:
1597   gst_caps_unref (caps);
1598   return ret;
1599 }
1600
1601 static GstFlowReturn
1602 handle_buffer (GstSubParse * self, GstBuffer * buf)
1603 {
1604   GstFlowReturn ret = GST_FLOW_OK;
1605   gchar *line, *subtitle;
1606   gboolean need_tags = FALSE;
1607
1608   if (self->first_buffer) {
1609     GstMapInfo map;
1610
1611     gst_buffer_map (buf, &map, GST_MAP_READ);
1612     self->detected_encoding =
1613         gst_sub_parse_detect_encoding ((gchar *) map.data, map.size);
1614     gst_buffer_unmap (buf, &map);
1615     self->first_buffer = FALSE;
1616     self->state.fps_n = self->fps_n;
1617     self->state.fps_d = self->fps_d;
1618   }
1619
1620   feed_textbuf (self, buf);
1621
1622   /* make sure we know the format */
1623   if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
1624     GstCaps *preferred;
1625
1626     if (!(preferred = gst_sub_parse_format_autodetect (self))) {
1627       return GST_FLOW_NOT_NEGOTIATED;
1628     }
1629
1630     if (!gst_sub_parse_negotiate (self, preferred)) {
1631       gst_caps_unref (preferred);
1632       return GST_FLOW_NOT_NEGOTIATED;
1633     }
1634
1635     gst_caps_unref (preferred);
1636
1637     need_tags = TRUE;
1638   }
1639
1640   /* Push newsegment if needed */
1641   if (self->need_segment) {
1642     GST_LOG_OBJECT (self, "pushing newsegment event with %" GST_SEGMENT_FORMAT,
1643         &self->segment);
1644
1645     gst_pad_push_event (self->srcpad, gst_event_new_segment (&self->segment));
1646     self->need_segment = FALSE;
1647   }
1648
1649   if (need_tags) {
1650     /* push tags */
1651     if (self->subtitle_codec != NULL) {
1652       GstTagList *tags;
1653
1654       tags = gst_tag_list_new (GST_TAG_SUBTITLE_CODEC, self->subtitle_codec,
1655           NULL);
1656       gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
1657     }
1658   }
1659
1660   while (!self->flushing && (line = get_next_line (self))) {
1661     guint offset = 0;
1662
1663     /* Set segment on our parser state machine */
1664     self->state.segment = &self->segment;
1665     /* Now parse the line, out of segment lines will just return NULL */
1666     GST_LOG_OBJECT (self, "State %d. Parsing line '%s'", self->state.state,
1667         line + offset);
1668     subtitle = self->parse_line (&self->state, line + offset);
1669     g_free (line);
1670
1671     if (subtitle) {
1672       guint subtitle_len;
1673
1674       if (self->strip_pango_markup) {
1675         GError *error = NULL;
1676         gchar *stripped;
1677
1678         if ((stripped = strip_pango_markup (subtitle, &error))) {
1679           g_free (subtitle);
1680           subtitle = stripped;
1681         } else {
1682           GST_WARNING_OBJECT (self, "Failed to strip pango markup: %s",
1683               error->message);
1684         }
1685       }
1686
1687       subtitle_len = strlen (subtitle);
1688
1689       /* +1 for terminating NUL character */
1690       buf = gst_buffer_new_and_alloc (subtitle_len + 1);
1691
1692       /* copy terminating NUL character as well */
1693       gst_buffer_fill (buf, 0, subtitle, subtitle_len + 1);
1694       gst_buffer_set_size (buf, subtitle_len);
1695
1696       GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
1697       GST_BUFFER_DURATION (buf) = self->state.duration;
1698
1699       /* in some cases (e.g. tmplayer) we can only determine the duration
1700        * of a text chunk from the timestamp of the next text chunk; in those
1701        * cases, we probably want to limit the duration to something
1702        * reasonable, so we don't end up showing some text for e.g. 40 seconds
1703        * just because nothing else is being said during that time */
1704       if (self->state.max_duration > 0 && GST_BUFFER_DURATION_IS_VALID (buf)) {
1705         if (GST_BUFFER_DURATION (buf) > self->state.max_duration)
1706           GST_BUFFER_DURATION (buf) = self->state.max_duration;
1707       }
1708
1709       self->segment.position = self->state.start_time;
1710
1711       GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
1712           GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
1713           GST_TIME_ARGS (self->state.duration));
1714
1715       g_free (self->state.vertical);
1716       self->state.vertical = NULL;
1717       g_free (self->state.alignment);
1718       self->state.alignment = NULL;
1719
1720       ret = gst_pad_push (self->srcpad, buf);
1721
1722       /* move this forward (the tmplayer parser needs this) */
1723       if (self->state.duration != GST_CLOCK_TIME_NONE)
1724         self->state.start_time += self->state.duration;
1725
1726       g_free (subtitle);
1727       subtitle = NULL;
1728
1729       if (ret != GST_FLOW_OK) {
1730         GST_DEBUG_OBJECT (self, "flow: %s", gst_flow_get_name (ret));
1731         break;
1732       }
1733     }
1734   }
1735
1736   return ret;
1737 }
1738
1739 static GstFlowReturn
1740 gst_sub_parse_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buf)
1741 {
1742   GstFlowReturn ret;
1743   GstSubParse *self;
1744
1745   self = GST_SUBPARSE (parent);
1746
1747   ret = handle_buffer (self, buf);
1748
1749   return ret;
1750 }
1751
1752 static gboolean
1753 gst_sub_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
1754 {
1755   GstSubParse *self = GST_SUBPARSE (parent);
1756   gboolean ret = FALSE;
1757
1758   GST_LOG_OBJECT (self, "%s event", GST_EVENT_TYPE_NAME (event));
1759
1760   switch (GST_EVENT_TYPE (event)) {
1761     case GST_EVENT_STREAM_GROUP_DONE:
1762     case GST_EVENT_EOS:{
1763       /* Make sure the last subrip chunk is pushed out even
1764        * if the file does not have an empty line at the end */
1765       if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP ||
1766           self->parser_type == GST_SUB_PARSE_FORMAT_TMPLAYER ||
1767           self->parser_type == GST_SUB_PARSE_FORMAT_MPL2 ||
1768           self->parser_type == GST_SUB_PARSE_FORMAT_QTTEXT ||
1769           self->parser_type == GST_SUB_PARSE_FORMAT_VTT) {
1770         gchar term_chars[] = { '\n', '\n', '\0' };
1771         GstBuffer *buf = gst_buffer_new_and_alloc (2 + 1);
1772
1773         GST_DEBUG_OBJECT (self, "%s: force pushing of any remaining text",
1774             GST_EVENT_TYPE_NAME (event));
1775
1776         gst_buffer_fill (buf, 0, term_chars, 3);
1777         gst_buffer_set_size (buf, 2);
1778
1779         GST_BUFFER_OFFSET (buf) = self->offset;
1780         gst_sub_parse_chain (pad, parent, buf);
1781       }
1782       ret = gst_pad_event_default (pad, parent, event);
1783       break;
1784     }
1785     case GST_EVENT_SEGMENT:
1786     {
1787       const GstSegment *s;
1788       gst_event_parse_segment (event, &s);
1789       if (s->format == GST_FORMAT_TIME)
1790         gst_event_copy_segment (event, &self->segment);
1791       GST_DEBUG_OBJECT (self, "newsegment (%s)",
1792           gst_format_get_name (self->segment.format));
1793
1794       /* if not time format, we'll either start with a 0 timestamp anyway or
1795        * it's following a seek in which case we'll have saved the requested
1796        * seek segment and don't want to overwrite it (remember that on a seek
1797        * we always just seek back to the start in BYTES format and just throw
1798        * away all text that's before the requested position; if the subtitles
1799        * come from an upstream demuxer, it won't be able to handle our BYTES
1800        * seek request and instead send us a newsegment from the seek request
1801        * it received via its video pads instead, so all is fine then too) */
1802       ret = TRUE;
1803       gst_event_unref (event);
1804       /* in either case, let's not simply discard this event;
1805        * trigger sending of the saved requested seek segment
1806        * or the one taken here from upstream */
1807       self->need_segment = TRUE;
1808       break;
1809     }
1810     case GST_EVENT_FLUSH_START:
1811     {
1812       self->flushing = TRUE;
1813
1814       ret = gst_pad_event_default (pad, parent, event);
1815       break;
1816     }
1817     case GST_EVENT_FLUSH_STOP:
1818     {
1819       self->flushing = FALSE;
1820
1821       ret = gst_pad_event_default (pad, parent, event);
1822       break;
1823     }
1824     default:
1825       ret = gst_pad_event_default (pad, parent, event);
1826       break;
1827   }
1828
1829   return ret;
1830 }
1831
1832
1833 static GstStateChangeReturn
1834 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1835 {
1836   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1837   GstSubParse *self = GST_SUBPARSE (element);
1838
1839   switch (transition) {
1840     case GST_STATE_CHANGE_READY_TO_PAUSED:
1841       /* format detection will init the parser state */
1842       self->offset = 0;
1843       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1844       self->strip_pango_markup = FALSE;
1845       self->valid_utf8 = TRUE;
1846       self->first_buffer = TRUE;
1847       g_free (self->detected_encoding);
1848       self->detected_encoding = NULL;
1849       g_string_truncate (self->textbuf, 0);
1850       gst_adapter_clear (self->adapter);
1851       break;
1852     default:
1853       break;
1854   }
1855
1856   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1857   if (ret == GST_STATE_CHANGE_FAILURE)
1858     return ret;
1859
1860   switch (transition) {
1861     case GST_STATE_CHANGE_PAUSED_TO_READY:
1862       parser_state_dispose (self, &self->state);
1863       self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1864       break;
1865     default:
1866       break;
1867   }
1868
1869   return ret;
1870 }