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