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