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>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
28 #include <sys/types.h>
31 #include "gstsubparse.h"
32 #include "gstssaparse.h"
33 #include "samiparse.h"
34 #include "tmplayerparse.h"
36 GST_DEBUG_CATEGORY (sub_parse_debug);
38 #define DEFAULT_ENCODING NULL
47 gst_sub_parse_set_property (GObject * object, guint prop_id,
48 const GValue * value, GParamSpec * pspec);
50 gst_sub_parse_get_property (GObject * object, guint prop_id,
51 GValue * value, GParamSpec * pspec);
54 static const GstElementDetails sub_parse_details =
55 GST_ELEMENT_DETAILS ("Subtitle parser",
56 "Codec/Parser/Subtitle",
57 "Parses subtitle (.sub) files into text streams",
58 "Gustavo J. A. M. Carneiro <gjc@inescporto.pt>\n"
59 "Ronald S. Bultje <rbultje@ronald.bitfreak.net>");
61 #ifndef GST_DISABLE_LOADSAVE_REGISTRY
62 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
65 GST_STATIC_CAPS ("application/x-subtitle; application/x-subtitle-sami; "
66 "application/x-subtitle-tmplayer")
69 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
72 GST_STATIC_CAPS ("application/x-subtitle")
76 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
79 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
82 static void gst_sub_parse_base_init (GstSubParseClass * klass);
83 static void gst_sub_parse_class_init (GstSubParseClass * klass);
84 static void gst_sub_parse_init (GstSubParse * subparse);
86 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
87 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
89 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
90 GstStateChange transition);
92 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
94 static GstElementClass *parent_class = NULL;
97 gst_sub_parse_get_type (void)
99 static GType sub_parse_type = 0;
101 if (!sub_parse_type) {
102 static const GTypeInfo sub_parse_info = {
103 sizeof (GstSubParseClass),
104 (GBaseInitFunc) gst_sub_parse_base_init,
106 (GClassInitFunc) gst_sub_parse_class_init,
109 sizeof (GstSubParse),
111 (GInstanceInitFunc) gst_sub_parse_init,
114 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
115 "GstSubParse", &sub_parse_info, 0);
118 return sub_parse_type;
122 gst_sub_parse_base_init (GstSubParseClass * klass)
124 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
126 gst_element_class_add_pad_template (element_class,
127 gst_static_pad_template_get (&sink_templ));
128 gst_element_class_add_pad_template (element_class,
129 gst_static_pad_template_get (&src_templ));
130 gst_element_class_set_details (element_class, &sub_parse_details);
134 gst_sub_parse_dispose (GObject * object)
136 GstSubParse *subparse = GST_SUBPARSE (object);
138 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
140 if (subparse->segment) {
141 gst_segment_free (subparse->segment);
142 subparse->segment = NULL;
144 if (subparse->encoding) {
145 g_free (subparse->encoding);
146 subparse->encoding = NULL;
148 if (subparse->textbuf) {
149 g_string_free (subparse->textbuf, TRUE);
150 subparse->textbuf = NULL;
152 sami_context_deinit (&subparse->state);
154 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
158 gst_sub_parse_class_init (GstSubParseClass * klass)
160 GObjectClass *object_class = G_OBJECT_CLASS (klass);
161 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
163 parent_class = g_type_class_peek_parent (klass);
165 object_class->dispose = gst_sub_parse_dispose;
166 object_class->set_property = gst_sub_parse_set_property;
167 object_class->get_property = gst_sub_parse_get_property;
169 element_class->change_state = gst_sub_parse_change_state;
171 g_object_class_install_property (object_class, PROP_ENCODING,
172 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
173 "Encoding to assume if input subtitles are not in UTF-8 encoding. "
174 "If not set, the GST_SUBTITLE_ENCODING environment variable will "
175 "be checked for an encoding to use. If that is not set either, "
176 "ISO-8859-15 will be assumed.", DEFAULT_ENCODING, G_PARAM_READWRITE));
180 gst_sub_parse_init (GstSubParse * subparse)
182 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
183 gst_pad_set_chain_function (subparse->sinkpad,
184 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
185 gst_pad_set_event_function (subparse->sinkpad,
186 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
187 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
189 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
190 gst_pad_set_event_function (subparse->srcpad,
191 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
192 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
194 subparse->textbuf = g_string_new (NULL);
195 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
196 subparse->flushing = FALSE;
197 subparse->segment = gst_segment_new ();
198 if (subparse->segment) {
199 gst_segment_init (subparse->segment, GST_FORMAT_TIME);
200 subparse->need_segment = TRUE;
202 GST_WARNING_OBJECT (subparse, "segment creation failed");
203 g_assert_not_reached ();
205 subparse->encoding = g_strdup (DEFAULT_ENCODING);
209 * Source pad functions.
213 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
215 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
216 gboolean ret = FALSE;
218 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
220 switch (GST_EVENT_TYPE (event)) {
224 GstSeekType start_type, stop_type;
229 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
230 &start_type, &start, &stop_type, &stop);
232 if (format != GST_FORMAT_TIME) {
233 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
234 gst_event_unref (event);
238 /* Convert that seek to a seeking in bytes at position 0,
239 FIXME: could use an index */
240 ret = gst_pad_push_event (self->sinkpad,
241 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
242 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
245 /* Apply the seek to our segment */
246 gst_segment_set_seek (self->segment, rate, format, self->segment_flags,
247 start_type, start, stop_type, stop, &update);
249 GST_DEBUG_OBJECT (self, "segment configured from %" GST_TIME_FORMAT
250 " to %" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT,
251 GST_TIME_ARGS (self->segment->start),
252 GST_TIME_ARGS (self->segment->stop),
253 GST_TIME_ARGS (self->segment->last_stop));
255 self->next_offset = 0;
257 self->need_segment = TRUE;
259 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
262 gst_event_unref (event);
266 ret = gst_pad_event_default (pad, event);
271 gst_object_unref (self);
277 gst_sub_parse_set_property (GObject * object, guint prop_id,
278 const GValue * value, GParamSpec * pspec)
280 GstSubParse *subparse = GST_SUBPARSE (object);
282 GST_OBJECT_LOCK (subparse);
285 g_free (subparse->encoding);
286 subparse->encoding = g_value_dup_string (value);
287 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
288 GST_STR_NULL (subparse->encoding));
291 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
294 GST_OBJECT_UNLOCK (subparse);
298 gst_sub_parse_get_property (GObject * object, guint prop_id,
299 GValue * value, GParamSpec * pspec)
301 GstSubParse *subparse = GST_SUBPARSE (object);
303 GST_OBJECT_LOCK (subparse);
306 g_value_set_string (value, subparse->encoding);
309 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
312 GST_OBJECT_UNLOCK (subparse);
316 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
318 const gchar *encoding;
322 if (self->valid_utf8) {
323 if (g_utf8_validate (str, len, NULL)) {
324 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
325 return g_strndup (str, len);
327 GST_INFO_OBJECT (self, "invalid UTF-8!");
328 self->valid_utf8 = FALSE;
331 encoding = self->encoding;
332 if (encoding == NULL || *encoding == '\0') {
333 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
335 if (encoding == NULL || *encoding == '\0') {
336 /* if local encoding is UTF-8 and no encoding specified
337 * via the environment variable, assume ISO-8859-15 */
338 if (g_get_charset (&encoding)) {
339 encoding = "ISO-8859-15";
343 ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
347 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
348 encoding, err->message);
351 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
352 ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
356 GST_LOG_OBJECT (self,
357 "successfully converted %" G_GSIZE_FORMAT " characters from %s to UTF-8"
358 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
364 get_next_line (GstSubParse * self)
367 const char *line_end;
369 gboolean have_r = FALSE;
371 line_end = strchr (self->textbuf->str, '\n');
374 /* end-of-line not found; return for more data */
378 /* get rid of '\r' */
379 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
384 line_len = line_end - self->textbuf->str;
385 line = convert_encoding (self, self->textbuf->str, line_len);
386 self->textbuf = g_string_erase (self->textbuf, 0,
387 line_len + (have_r ? 2 : 1));
392 parse_mdvdsub (ParserState * state, const gchar * line)
394 const gchar *line_split;
396 guint start_frame, end_frame;
397 gint64 clip_start = 0, clip_stop = 0;
398 gboolean in_seg = FALSE;
402 /* style variables */
407 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
408 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
409 " format, failed:\n%s", line);
413 /* skip the {%u}{%u} part */
414 line = strchr (line, '}') + 1;
415 line = strchr (line, '}') + 1;
417 /* see if there's a first line with a framerate */
418 if (state->fps == 0.0 && start_frame == 1 && end_frame == 1) {
419 gchar *rest, *end = NULL;
421 rest = g_strdup (line);
422 g_strdelimit (rest, ",", '.');
423 state->fps = g_ascii_strtod (rest, &end);
426 GST_INFO ("framerate from file: %f ('%s')", state->fps, rest);
431 if (state->fps == 0.0) {
432 /* FIXME: hardcoded for now, is there a better way/assumption? */
433 state->fps = 24000.0 / 1001.0;
434 GST_INFO ("no framerate specified, assuming %f", state->fps);
437 state->start_time = start_frame / state->fps * GST_SECOND;
438 state->duration = (end_frame - start_frame) / state->fps * GST_SECOND;
440 /* Check our segment start/stop */
441 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
442 state->start_time, state->start_time + state->duration, &clip_start,
445 /* No need to parse that text if it's out of segment */
447 state->start_time = clip_start;
448 state->duration = clip_stop - clip_start;
453 markup = g_string_new (NULL);
458 /* parse style markup */
459 if (strncmp (line, "{y:i}", 5) == 0) {
461 line = strchr (line, '}') + 1;
463 if (strncmp (line, "{y:b}", 5) == 0) {
465 line = strchr (line, '}') + 1;
467 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
468 line = strchr (line, '}') + 1;
470 if ((line_split = strchr (line, '|')))
471 line_chunk = g_markup_escape_text (line, line_split - line);
473 line_chunk = g_markup_escape_text (line, strlen (line));
474 markup = g_string_append (markup, "<span");
476 g_string_append (markup, " style=\"italic\"");
478 g_string_append (markup, " weight=\"bold\"");
480 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
481 g_string_append_printf (markup, ">%s</span>", line_chunk);
484 g_string_append (markup, "\n");
485 line = line_split + 1;
491 g_string_free (markup, FALSE);
492 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
493 state->start_time / (double) GST_SECOND,
494 state->duration / (double) GST_SECOND, ret);
499 strip_trailing_newlines (gchar * txt)
505 while (len > 1 && txt[len - 1] == '\n') {
512 /* we want to escape text in general, but retain basic markup like
513 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
514 * just unescape a white list of allowed markups again after
515 * escaping everything (the text between these simple markers isn't
516 * necessarily escaped, so it seems best to do it like this) */
518 subrip_unescape_formatting (gchar * txt)
522 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
523 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
524 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
525 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
527 pos[1] = g_ascii_tolower (pos[4]);
529 /* move NUL terminator as well */
530 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
535 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
536 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
537 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
538 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
541 pos[2] = g_ascii_tolower (pos[5]);
543 /* move NUL terminator as well */
544 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
550 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
551 * assumes the input has been escaped and subrip_unescape_formatting() has then
552 * been run over the input! This function adds missing closing markup tags and
553 * removes broken closing tags for tags that have never been opened. */
555 subrip_fix_up_markup (gchar ** p_txt)
557 gchar *cur, *next_tag;
559 guint num_open_tags = 0;
561 g_assert (*p_txt != NULL);
564 while (*cur != '\0') {
565 next_tag = strchr (cur, '<');
566 if (next_tag == NULL)
572 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
573 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
574 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
577 /* it's all good, closing tag which is open */
585 if (num_open_tags == G_N_ELEMENTS (open_tags))
586 return; /* something dodgy is going on, stop parsing */
587 open_tags[num_open_tags] = *next_tag;
591 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
592 g_assert_not_reached ();
598 if (num_open_tags > 0) {
601 s = g_string_new (*p_txt);
602 while (num_open_tags > 0) {
603 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
604 g_string_append_c (s, '<');
605 g_string_append_c (s, '/');
606 g_string_append_c (s, open_tags[num_open_tags - 1]);
607 g_string_append_c (s, '>');
611 *p_txt = g_string_free (s, FALSE);
616 parse_subrip (ParserState * state, const gchar * line)
618 guint h1, m1, s1, ms1;
619 guint h2, m2, s2, ms2;
623 switch (state->state) {
625 /* looking for a single integer */
626 if (sscanf (line, "%u", &subnum) == 1)
630 /* looking for start_time --> end_time */
631 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
632 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
635 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
638 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
639 ms2 * GST_MSECOND - state->start_time;
641 GST_DEBUG ("error parsing subrip time line");
646 { /* No need to parse that text if it's out of segment */
647 gint64 clip_start = 0, clip_stop = 0;
648 gboolean in_seg = FALSE;
650 /* Check our segment start/stop */
651 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
652 state->start_time, state->start_time + state->duration,
653 &clip_start, &clip_stop);
656 state->start_time = clip_start;
657 state->duration = clip_stop - clip_start;
663 /* looking for subtitle text; empty line ends this
666 g_string_append_c (state->buf, '\n');
667 g_string_append (state->buf, line);
668 if (strlen (line) == 0) {
669 ret = g_markup_escape_text (state->buf->str, state->buf->len);
670 g_string_truncate (state->buf, 0);
672 subrip_unescape_formatting (ret);
673 strip_trailing_newlines (ret);
674 subrip_fix_up_markup (&ret);
679 g_return_val_if_reached (NULL);
684 parse_mpsub (ParserState * state, const gchar * line)
689 switch (state->state) {
691 /* looking for two floats (offset, duration) */
692 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
694 state->start_time += state->duration + GST_SECOND * t1;
695 state->duration = GST_SECOND * t2;
699 { /* No need to parse that text if it's out of segment */
700 gint64 clip_start = 0, clip_stop = 0;
701 gboolean in_seg = FALSE;
703 /* Check our segment start/stop */
704 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
705 state->start_time, state->start_time + state->duration,
706 &clip_start, &clip_stop);
709 state->start_time = clip_start;
710 state->duration = clip_stop - clip_start;
716 /* looking for subtitle text; empty line ends this
719 g_string_append_c (state->buf, '\n');
720 g_string_append (state->buf, line);
721 if (strlen (line) == 0) {
722 ret = g_strdup (state->buf->str);
723 g_string_truncate (state->buf, 0);
729 g_assert_not_reached ();
735 parser_state_init (ParserState * state)
737 GST_DEBUG ("initialising parser");
740 g_string_truncate (state->buf, 0);
742 state->buf = g_string_new (NULL);
745 state->start_time = 0;
748 state->segment = NULL;
752 parser_state_dispose (ParserState * state)
755 g_string_free (state->buf, TRUE);
758 if (state->user_data) {
759 sami_context_reset (state);
764 * FIXME: maybe we should pass along a second argument, the preceding
765 * text buffer, because that is how this originally worked, even though
766 * I don't really see the use of that.
769 static GstSubParseFormat
770 gst_sub_parse_data_format_autodetect (gchar * match_str)
772 static gboolean need_init_regexps = TRUE;
773 static regex_t mdvd_rx;
774 static regex_t subrip_rx;
777 /* initialize the regexps used the first time around */
778 if (need_init_regexps) {
782 need_init_regexps = FALSE;
783 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
784 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
785 (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
786 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
787 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
788 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
789 regerror (err, &subrip_rx, errstr, 127);
790 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
794 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
795 GST_LOG ("MicroDVD (frame based) format detected");
796 return GST_SUB_PARSE_FORMAT_MDVDSUB;
798 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
799 GST_LOG ("SubRip (time based) format detected");
800 return GST_SUB_PARSE_FORMAT_SUBRIP;
802 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
803 GST_LOG ("MPSub (time based) format detected");
804 return GST_SUB_PARSE_FORMAT_MPSUB;
806 if (strstr (match_str, "<SAMI>") != NULL ||
807 strstr (match_str, "<sami>") != NULL) {
808 GST_LOG ("SAMI (time based) format detected");
809 return GST_SUB_PARSE_FORMAT_SAMI;
811 /* we're boldly assuming the first subtitle appears within the first hour */
812 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
813 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
814 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
815 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
816 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
817 GST_LOG ("TMPlayer (time based) format detected");
818 return GST_SUB_PARSE_FORMAT_TMPLAYER;
821 GST_DEBUG ("no subtitle format detected");
822 return GST_SUB_PARSE_FORMAT_UNKNOWN;
826 gst_sub_parse_format_autodetect (GstSubParse * self)
829 GstSubParseFormat format;
831 if (strlen (self->textbuf->str) < 35) {
832 GST_DEBUG ("File too small to be a subtitles file");
836 data = g_strndup (self->textbuf->str, 35);
837 format = gst_sub_parse_data_format_autodetect (data);
840 self->parser_type = format;
841 parser_state_init (&self->state);
844 case GST_SUB_PARSE_FORMAT_MDVDSUB:
845 self->parse_line = parse_mdvdsub;
846 return gst_caps_new_simple ("text/x-pango-markup", NULL);
847 case GST_SUB_PARSE_FORMAT_SUBRIP:
848 self->parse_line = parse_subrip;
849 return gst_caps_new_simple ("text/x-pango-markup", NULL);
850 case GST_SUB_PARSE_FORMAT_MPSUB:
851 self->parse_line = parse_mpsub;
852 return gst_caps_new_simple ("text/plain", NULL);
853 case GST_SUB_PARSE_FORMAT_SAMI:
854 self->parse_line = parse_sami;
855 sami_context_init (&self->state);
856 return gst_caps_new_simple ("text/x-pango-markup", NULL);
857 case GST_SUB_PARSE_FORMAT_TMPLAYER:
858 self->parse_line = parse_tmplayer;
859 return gst_caps_new_simple ("text/plain", NULL);
860 case GST_SUB_PARSE_FORMAT_UNKNOWN:
862 GST_DEBUG ("no subtitle format detected");
863 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
864 ("The input is not a valid/supported subtitle file"), (NULL));
870 feed_textbuf (GstSubParse * self, GstBuffer * buf)
872 if (GST_BUFFER_OFFSET (buf) != self->offset) {
873 /* flush the parser state */
874 parser_state_init (&self->state);
875 g_string_truncate (self->textbuf, 0);
876 sami_context_reset (&self->state);
879 self->textbuf = g_string_append_len (self->textbuf,
880 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
881 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
882 self->next_offset = self->offset;
884 gst_buffer_unref (buf);
888 handle_buffer (GstSubParse * self, GstBuffer * buf)
890 GstFlowReturn ret = GST_FLOW_OK;
891 GstCaps *caps = NULL;
892 gchar *line, *subtitle;
894 feed_textbuf (self, buf);
896 /* make sure we know the format */
897 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
898 if (!(caps = gst_sub_parse_format_autodetect (self))) {
899 return GST_FLOW_UNEXPECTED;
901 if (!gst_pad_set_caps (self->srcpad, caps)) {
902 gst_caps_unref (caps);
903 return GST_FLOW_UNEXPECTED;
905 gst_caps_unref (caps);
908 while ((line = get_next_line (self)) && !self->flushing) {
909 /* Set segment on our parser state machine */
910 self->state.segment = self->segment;
911 /* Now parse the line, out of segment lines will just return NULL */
912 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
913 subtitle = self->parse_line (&self->state, line);
917 guint subtitle_len = strlen (subtitle);
919 /* +1 for terminating NUL character */
920 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
921 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
922 GST_PAD_CAPS (self->srcpad), &buf);
924 if (ret == GST_FLOW_OK) {
925 /* copy terminating NUL character as well */
926 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
927 GST_BUFFER_SIZE (buf) = subtitle_len;
928 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
929 GST_BUFFER_DURATION (buf) = self->state.duration;
931 gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
932 self->state.start_time);
934 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
935 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
936 GST_TIME_ARGS (self->state.duration));
938 ret = gst_pad_push (self->srcpad, buf);
944 if (GST_FLOW_IS_FATAL (ret))
953 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
958 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
960 /* Push newsegment if needed */
961 if (self->need_segment) {
962 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
963 self->segment->rate, self->segment->format,
964 self->segment->last_stop, self->segment->stop,
965 self->segment->time));
966 self->need_segment = FALSE;
969 ret = handle_buffer (self, buf);
975 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
977 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
978 gboolean ret = FALSE;
980 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
982 switch (GST_EVENT_TYPE (event)) {
984 /* Make sure the last subrip chunk is pushed out even
985 * if the file does not have an empty line at the end */
986 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
987 GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
989 GST_DEBUG ("EOS. Pushing remaining text (if any)");
990 GST_BUFFER_DATA (buf)[0] = '\n';
991 GST_BUFFER_DATA (buf)[1] = '\0'; /* play it safe */
992 GST_BUFFER_SIZE (buf) = 1;
993 GST_BUFFER_OFFSET (buf) = self->offset;
994 gst_sub_parse_chain (pad, buf);
996 ret = gst_pad_event_default (pad, event);
999 case GST_EVENT_NEWSEGMENT:
1003 gint64 start, stop, time;
1006 GST_DEBUG_OBJECT (self, "received new segment");
1008 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
1011 /* now copy over the values */
1012 gst_segment_set_newsegment (self->segment, update, rate, format,
1016 gst_event_unref (event);
1019 case GST_EVENT_FLUSH_START:
1021 self->flushing = TRUE;
1023 ret = gst_pad_event_default (pad, event);
1026 case GST_EVENT_FLUSH_STOP:
1028 self->flushing = FALSE;
1030 ret = gst_pad_event_default (pad, event);
1034 ret = gst_pad_event_default (pad, event);
1038 gst_object_unref (self);
1044 static GstStateChangeReturn
1045 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1047 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1048 GstSubParse *self = GST_SUBPARSE (element);
1050 switch (transition) {
1051 case GST_STATE_CHANGE_READY_TO_PAUSED:
1052 /* format detection will init the parser state */
1054 self->next_offset = 0;
1055 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1056 self->valid_utf8 = TRUE;
1057 g_string_truncate (self->textbuf, 0);
1063 ret = parent_class->change_state (element, transition);
1064 if (ret == GST_STATE_CHANGE_FAILURE)
1067 switch (transition) {
1068 case GST_STATE_CHANGE_PAUSED_TO_READY:
1069 parser_state_dispose (&self->state);
1070 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1083 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1084 * also, give different subtitle formats really different types */
1085 static GstStaticCaps tmp_caps =
1086 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1087 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1088 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1090 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1091 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1092 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1095 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1097 GstSubParseFormat format;
1102 if (!(data = gst_type_find_peek (tf, 0, 36)))
1105 /* make sure string passed to _autodetect() is NUL-terminated */
1106 str = g_strndup ((gchar *) data, 35);
1107 format = gst_sub_parse_data_format_autodetect (str);
1111 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1112 GST_DEBUG ("MicroDVD format detected");
1115 case GST_SUB_PARSE_FORMAT_SUBRIP:
1116 GST_DEBUG ("SubRip format detected");
1119 case GST_SUB_PARSE_FORMAT_MPSUB:
1120 GST_DEBUG ("MPSub format detected");
1123 case GST_SUB_PARSE_FORMAT_SAMI:
1124 GST_DEBUG ("SAMI (time-based) format detected");
1127 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1128 GST_DEBUG ("TMPlayer (time based) format detected");
1132 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1133 GST_DEBUG ("no subtitle format detected");
1137 /* if we're here, it's ok */
1138 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1142 plugin_init (GstPlugin * plugin)
1144 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1148 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1150 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1151 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1154 if (!gst_element_register (plugin, "subparse",
1155 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1156 !gst_element_register (plugin, "ssaparse",
1157 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1164 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1168 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)