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, "successfully converted %d characters from %s to UTF-8"
357 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
363 get_next_line (GstSubParse * self)
366 const char *line_end;
368 gboolean have_r = FALSE;
370 line_end = strchr (self->textbuf->str, '\n');
373 /* end-of-line not found; return for more data */
377 /* get rid of '\r' */
378 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
383 line_len = line_end - self->textbuf->str;
384 line = convert_encoding (self, self->textbuf->str, line_len);
385 self->textbuf = g_string_erase (self->textbuf, 0,
386 line_len + (have_r ? 2 : 1));
391 parse_mdvdsub (ParserState * state, const gchar * line)
393 const gchar *line_split;
395 guint start_frame, end_frame;
396 gint64 clip_start = 0, clip_stop = 0;
397 gboolean in_seg = FALSE;
399 /* FIXME: hardcoded for now, but detecting the correct value is
400 * not going to be easy, I suspect... */
401 const double frames_per_sec = 24000 / 1001.;
405 /* style variables */
410 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
411 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
412 " format, failed:\n%s", line);
416 state->start_time = (start_frame - 1000) / frames_per_sec * GST_SECOND;
417 state->duration = (end_frame - start_frame) / frames_per_sec * GST_SECOND;
419 /* Check our segment start/stop */
420 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
421 state->start_time, state->start_time + state->duration, &clip_start,
424 /* No need to parse that text if it's out of segment */
426 state->start_time = clip_start;
427 state->duration = clip_stop - clip_start;
432 /* skip the {%u}{%u} part */
433 line = strchr (line, '}') + 1;
434 line = strchr (line, '}') + 1;
436 markup = g_string_new (NULL);
441 /* parse style markup */
442 if (strncmp (line, "{y:i}", 5) == 0) {
444 line = strchr (line, '}') + 1;
446 if (strncmp (line, "{y:b}", 5) == 0) {
448 line = strchr (line, '}') + 1;
450 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
451 line = strchr (line, '}') + 1;
453 if ((line_split = strchr (line, '|')))
454 line_chunk = g_markup_escape_text (line, line_split - line);
456 line_chunk = g_markup_escape_text (line, strlen (line));
457 markup = g_string_append (markup, "<span");
459 g_string_append (markup, " style=\"italic\"");
461 g_string_append (markup, " weight=\"bold\"");
463 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
464 g_string_append_printf (markup, ">%s</span>", line_chunk);
467 g_string_append (markup, "\n");
468 line = line_split + 1;
474 g_string_free (markup, FALSE);
475 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
476 state->start_time / (double) GST_SECOND,
477 state->duration / (double) GST_SECOND, ret);
482 strip_trailing_newlines (gchar * txt)
488 while (len > 1 && txt[len - 1] == '\n') {
495 /* we want to escape text in general, but retain basic markup like
496 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
497 * just unescape a white list of allowed markups again after
498 * escaping everything (the text between these simple markers isn't
499 * necessarily escaped, so it seems best to do it like this) */
501 subrip_unescape_formatting (gchar * txt)
505 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
506 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
507 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
508 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
510 pos[1] = g_ascii_tolower (pos[4]);
512 /* move NUL terminator as well */
513 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
518 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
519 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
520 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
521 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
524 pos[2] = g_ascii_tolower (pos[5]);
526 /* move NUL terminator as well */
527 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
533 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
534 * assumes the input has been escaped and subrip_unescape_formatting() has then
535 * been run over the input! This function adds missing closing markup tags and
536 * removes broken closing tags for tags that have never been opened. */
538 subrip_fix_up_markup (gchar ** p_txt)
540 gchar *cur, *next_tag;
542 guint num_open_tags = 0;
544 g_assert (*p_txt != NULL);
547 while (*cur != '\0') {
548 next_tag = strchr (cur, '<');
549 if (next_tag == NULL)
555 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
556 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
557 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
560 /* it's all good, closing tag which is open */
568 if (num_open_tags == G_N_ELEMENTS (open_tags))
569 return; /* something dodgy is going on, stop parsing */
570 open_tags[num_open_tags] = *next_tag;
574 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
575 g_assert_not_reached ();
581 if (num_open_tags > 0) {
584 s = g_string_new (*p_txt);
585 while (num_open_tags > 0) {
586 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
587 g_string_append_c (s, '<');
588 g_string_append_c (s, '/');
589 g_string_append_c (s, open_tags[num_open_tags - 1]);
590 g_string_append_c (s, '>');
594 *p_txt = g_string_free (s, FALSE);
599 parse_subrip (ParserState * state, const gchar * line)
601 guint h1, m1, s1, ms1;
602 guint h2, m2, s2, ms2;
606 switch (state->state) {
608 /* looking for a single integer */
609 if (sscanf (line, "%u", &subnum) == 1)
613 /* looking for start_time --> end_time */
614 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
615 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
618 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
621 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
622 ms2 * GST_MSECOND - state->start_time;
624 GST_DEBUG ("error parsing subrip time line");
629 { /* No need to parse that text if it's out of segment */
630 gint64 clip_start = 0, clip_stop = 0;
631 gboolean in_seg = FALSE;
633 /* Check our segment start/stop */
634 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
635 state->start_time, state->start_time + state->duration,
636 &clip_start, &clip_stop);
639 state->start_time = clip_start;
640 state->duration = clip_stop - clip_start;
646 /* looking for subtitle text; empty line ends this
649 g_string_append_c (state->buf, '\n');
650 g_string_append (state->buf, line);
651 if (strlen (line) == 0) {
652 ret = g_markup_escape_text (state->buf->str, state->buf->len);
653 g_string_truncate (state->buf, 0);
655 subrip_unescape_formatting (ret);
656 strip_trailing_newlines (ret);
657 subrip_fix_up_markup (&ret);
662 g_return_val_if_reached (NULL);
667 parse_mpsub (ParserState * state, const gchar * line)
672 switch (state->state) {
674 /* looking for two floats (offset, duration) */
675 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
677 state->start_time += state->duration + GST_SECOND * t1;
678 state->duration = GST_SECOND * t2;
682 { /* No need to parse that text if it's out of segment */
683 gint64 clip_start = 0, clip_stop = 0;
684 gboolean in_seg = FALSE;
686 /* Check our segment start/stop */
687 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
688 state->start_time, state->start_time + state->duration,
689 &clip_start, &clip_stop);
692 state->start_time = clip_start;
693 state->duration = clip_stop - clip_start;
699 /* looking for subtitle text; empty line ends this
702 g_string_append_c (state->buf, '\n');
703 g_string_append (state->buf, line);
704 if (strlen (line) == 0) {
705 ret = g_strdup (state->buf->str);
706 g_string_truncate (state->buf, 0);
712 g_assert_not_reached ();
718 parser_state_init (ParserState * state)
720 GST_DEBUG ("initialising parser");
723 g_string_truncate (state->buf, 0);
725 state->buf = g_string_new (NULL);
728 state->start_time = 0;
731 state->segment = NULL;
735 parser_state_dispose (ParserState * state)
738 g_string_free (state->buf, TRUE);
741 if (state->user_data) {
742 sami_context_reset (state);
747 * FIXME: maybe we should pass along a second argument, the preceding
748 * text buffer, because that is how this originally worked, even though
749 * I don't really see the use of that.
752 static GstSubParseFormat
753 gst_sub_parse_data_format_autodetect (gchar * match_str)
755 static gboolean need_init_regexps = TRUE;
756 static regex_t mdvd_rx;
757 static regex_t subrip_rx;
760 /* initialize the regexps used the first time around */
761 if (need_init_regexps) {
765 need_init_regexps = FALSE;
766 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
767 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
768 (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
769 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
770 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
771 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
772 regerror (err, &subrip_rx, errstr, 127);
773 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
777 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
778 GST_LOG ("MicroDVD (frame based) format detected");
779 return GST_SUB_PARSE_FORMAT_MDVDSUB;
781 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
782 GST_LOG ("SubRip (time based) format detected");
783 return GST_SUB_PARSE_FORMAT_SUBRIP;
785 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
786 GST_LOG ("MPSub (time based) format detected");
787 return GST_SUB_PARSE_FORMAT_MPSUB;
789 if (strstr (match_str, "<SAMI>") != NULL ||
790 strstr (match_str, "<sami>") != NULL) {
791 GST_LOG ("SAMI (time based) format detected");
792 return GST_SUB_PARSE_FORMAT_SAMI;
794 /* we're boldly assuming the first subtitle appears within the first hour */
795 if (sscanf (match_str, "0:%02u:%02u:", &n1, &n2) == 2 ||
796 sscanf (match_str, "0:%02u:%02u=", &n1, &n2) == 2 ||
797 sscanf (match_str, "00:%02u:%02u:", &n1, &n2) == 2 ||
798 sscanf (match_str, "00:%02u:%02u=", &n1, &n2) == 2 ||
799 sscanf (match_str, "00:%02u:%02u,%u=", &n1, &n2, &n3) == 3) {
800 GST_LOG ("TMPlayer (time based) format detected");
801 return GST_SUB_PARSE_FORMAT_TMPLAYER;
804 GST_DEBUG ("no subtitle format detected");
805 return GST_SUB_PARSE_FORMAT_UNKNOWN;
809 gst_sub_parse_format_autodetect (GstSubParse * self)
812 GstSubParseFormat format;
814 if (strlen (self->textbuf->str) < 35) {
815 GST_DEBUG ("File too small to be a subtitles file");
819 data = g_strndup (self->textbuf->str, 35);
820 format = gst_sub_parse_data_format_autodetect (data);
823 self->parser_type = format;
824 parser_state_init (&self->state);
827 case GST_SUB_PARSE_FORMAT_MDVDSUB:
828 self->parse_line = parse_mdvdsub;
829 return gst_caps_new_simple ("text/x-pango-markup", NULL);
830 case GST_SUB_PARSE_FORMAT_SUBRIP:
831 self->parse_line = parse_subrip;
832 return gst_caps_new_simple ("text/x-pango-markup", NULL);
833 case GST_SUB_PARSE_FORMAT_MPSUB:
834 self->parse_line = parse_mpsub;
835 return gst_caps_new_simple ("text/plain", NULL);
836 case GST_SUB_PARSE_FORMAT_SAMI:
837 self->parse_line = parse_sami;
838 sami_context_init (&self->state);
839 return gst_caps_new_simple ("text/x-pango-markup", NULL);
840 case GST_SUB_PARSE_FORMAT_TMPLAYER:
841 self->parse_line = parse_tmplayer;
842 return gst_caps_new_simple ("text/plain", NULL);
843 case GST_SUB_PARSE_FORMAT_UNKNOWN:
845 GST_DEBUG ("no subtitle format detected");
846 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
847 ("The input is not a valid/supported subtitle file"), (NULL));
853 feed_textbuf (GstSubParse * self, GstBuffer * buf)
855 if (GST_BUFFER_OFFSET (buf) != self->offset) {
856 /* flush the parser state */
857 parser_state_init (&self->state);
858 g_string_truncate (self->textbuf, 0);
859 sami_context_reset (&self->state);
862 self->textbuf = g_string_append_len (self->textbuf,
863 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
864 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
865 self->next_offset = self->offset;
867 gst_buffer_unref (buf);
871 handle_buffer (GstSubParse * self, GstBuffer * buf)
873 GstFlowReturn ret = GST_FLOW_OK;
874 GstCaps *caps = NULL;
875 gchar *line, *subtitle;
877 feed_textbuf (self, buf);
879 /* make sure we know the format */
880 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
881 if (!(caps = gst_sub_parse_format_autodetect (self))) {
882 return GST_FLOW_UNEXPECTED;
884 if (!gst_pad_set_caps (self->srcpad, caps)) {
885 gst_caps_unref (caps);
886 return GST_FLOW_UNEXPECTED;
888 gst_caps_unref (caps);
891 while ((line = get_next_line (self)) && !self->flushing) {
892 /* Set segment on our parser state machine */
893 self->state.segment = self->segment;
894 /* Now parse the line, out of segment lines will just return NULL */
895 GST_LOG_OBJECT (self, "Parsing line '%s'", line);
896 subtitle = self->parse_line (&self->state, line);
900 guint subtitle_len = strlen (subtitle);
902 /* +1 for terminating NUL character */
903 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
904 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
905 GST_PAD_CAPS (self->srcpad), &buf);
907 if (ret == GST_FLOW_OK) {
908 /* copy terminating NUL character as well */
909 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
910 GST_BUFFER_SIZE (buf) = subtitle_len;
911 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
912 GST_BUFFER_DURATION (buf) = self->state.duration;
914 gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
915 self->state.start_time);
917 GST_DEBUG_OBJECT (self, "Sending text '%s', %" GST_TIME_FORMAT " + %"
918 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
919 GST_TIME_ARGS (self->state.duration));
921 ret = gst_pad_push (self->srcpad, buf);
927 if (GST_FLOW_IS_FATAL (ret))
936 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
941 self = GST_SUBPARSE (GST_PAD_PARENT (sinkpad));
943 /* Push newsegment if needed */
944 if (self->need_segment) {
945 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
946 self->segment->rate, self->segment->format,
947 self->segment->last_stop, self->segment->stop,
948 self->segment->time));
949 self->need_segment = FALSE;
952 ret = handle_buffer (self, buf);
958 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
960 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
961 gboolean ret = FALSE;
963 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
965 switch (GST_EVENT_TYPE (event)) {
967 /* Make sure the last subrip chunk is pushed out even
968 * if the file does not have an empty line at the end */
969 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
970 GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
972 GST_DEBUG ("EOS. Pushing remaining text (if any)");
973 GST_BUFFER_DATA (buf)[0] = '\n';
974 GST_BUFFER_DATA (buf)[1] = '\0'; /* play it safe */
975 GST_BUFFER_SIZE (buf) = 1;
976 GST_BUFFER_OFFSET (buf) = self->offset;
977 gst_sub_parse_chain (pad, buf);
979 ret = gst_pad_event_default (pad, event);
982 case GST_EVENT_NEWSEGMENT:
986 gint64 start, stop, time;
989 GST_DEBUG_OBJECT (self, "received new segment");
991 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
994 /* now copy over the values */
995 gst_segment_set_newsegment (self->segment, update, rate, format,
999 gst_event_unref (event);
1002 case GST_EVENT_FLUSH_START:
1004 self->flushing = TRUE;
1006 ret = gst_pad_event_default (pad, event);
1009 case GST_EVENT_FLUSH_STOP:
1011 self->flushing = FALSE;
1013 ret = gst_pad_event_default (pad, event);
1017 ret = gst_pad_event_default (pad, event);
1021 gst_object_unref (self);
1027 static GstStateChangeReturn
1028 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1030 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1031 GstSubParse *self = GST_SUBPARSE (element);
1033 switch (transition) {
1034 case GST_STATE_CHANGE_READY_TO_PAUSED:
1035 /* format detection will init the parser state */
1037 self->next_offset = 0;
1038 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1039 self->valid_utf8 = TRUE;
1040 g_string_truncate (self->textbuf, 0);
1046 ret = parent_class->change_state (element, transition);
1047 if (ret == GST_STATE_CHANGE_FAILURE)
1050 switch (transition) {
1051 case GST_STATE_CHANGE_PAUSED_TO_READY:
1052 parser_state_dispose (&self->state);
1053 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1066 /* FIXME 0.11: these caps are ugly, use app/x-subtitle + type field or so;
1067 * also, give different subtitle formats really different types */
1068 static GstStaticCaps tmp_caps =
1069 GST_STATIC_CAPS ("application/x-subtitle-tmplayer");
1070 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1071 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1073 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1074 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1075 #define TMP_CAPS (gst_static_caps_get (&tmp_caps))
1078 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1080 GstSubParseFormat format;
1085 if (!(data = gst_type_find_peek (tf, 0, 36)))
1088 /* make sure string passed to _autodetect() is NUL-terminated */
1089 str = g_strndup ((gchar *) data, 35);
1090 format = gst_sub_parse_data_format_autodetect (str);
1094 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1095 GST_DEBUG ("MicroDVD format detected");
1098 case GST_SUB_PARSE_FORMAT_SUBRIP:
1099 GST_DEBUG ("SubRip format detected");
1102 case GST_SUB_PARSE_FORMAT_MPSUB:
1103 GST_DEBUG ("MPSub format detected");
1106 case GST_SUB_PARSE_FORMAT_SAMI:
1107 GST_DEBUG ("SAMI (time-based) format detected");
1110 case GST_SUB_PARSE_FORMAT_TMPLAYER:
1111 GST_DEBUG ("TMPlayer (time based) format detected");
1115 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1116 GST_DEBUG ("no subtitle format detected");
1120 /* if we're here, it's ok */
1121 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1125 plugin_init (GstPlugin * plugin)
1127 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", "txt",
1131 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1133 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1134 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1137 if (!gst_element_register (plugin, "subparse",
1138 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1139 !gst_element_register (plugin, "ssaparse",
1140 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1147 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1151 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)