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"
35 GST_DEBUG_CATEGORY_STATIC (sub_parse_debug);
36 #define GST_CAT_DEFAULT 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")
68 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
71 GST_STATIC_CAPS ("application/x-subtitle")
75 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
78 GST_STATIC_CAPS ("text/plain; text/x-pango-markup")
81 static void gst_sub_parse_base_init (GstSubParseClass * klass);
82 static void gst_sub_parse_class_init (GstSubParseClass * klass);
83 static void gst_sub_parse_init (GstSubParse * subparse);
85 static gboolean gst_sub_parse_src_event (GstPad * pad, GstEvent * event);
86 static gboolean gst_sub_parse_sink_event (GstPad * pad, GstEvent * event);
88 static GstStateChangeReturn gst_sub_parse_change_state (GstElement * element,
89 GstStateChange transition);
91 static GstFlowReturn gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf);
93 static GstElementClass *parent_class = NULL;
96 gst_sub_parse_get_type (void)
98 static GType sub_parse_type = 0;
100 if (!sub_parse_type) {
101 static const GTypeInfo sub_parse_info = {
102 sizeof (GstSubParseClass),
103 (GBaseInitFunc) gst_sub_parse_base_init,
105 (GClassInitFunc) gst_sub_parse_class_init,
108 sizeof (GstSubParse),
110 (GInstanceInitFunc) gst_sub_parse_init,
113 sub_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
114 "GstSubParse", &sub_parse_info, 0);
117 return sub_parse_type;
121 gst_sub_parse_base_init (GstSubParseClass * klass)
123 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
125 gst_element_class_add_pad_template (element_class,
126 gst_static_pad_template_get (&sink_templ));
127 gst_element_class_add_pad_template (element_class,
128 gst_static_pad_template_get (&src_templ));
129 gst_element_class_set_details (element_class, &sub_parse_details);
133 gst_sub_parse_dispose (GObject * object)
135 GstSubParse *subparse = GST_SUBPARSE (object);
137 GST_DEBUG_OBJECT (subparse, "cleaning up subtitle parser");
139 if (subparse->segment) {
140 gst_segment_free (subparse->segment);
141 subparse->segment = NULL;
143 if (subparse->encoding) {
144 g_free (subparse->encoding);
145 subparse->encoding = NULL;
147 if (subparse->textbuf) {
148 g_string_free (subparse->textbuf, TRUE);
149 subparse->textbuf = NULL;
151 sami_context_deinit (&subparse->state);
153 GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
157 gst_sub_parse_class_init (GstSubParseClass * klass)
159 GObjectClass *object_class = G_OBJECT_CLASS (klass);
160 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
162 parent_class = g_type_class_peek_parent (klass);
164 object_class->dispose = gst_sub_parse_dispose;
165 object_class->set_property = gst_sub_parse_set_property;
166 object_class->get_property = gst_sub_parse_get_property;
168 element_class->change_state = gst_sub_parse_change_state;
170 g_object_class_install_property (object_class, PROP_ENCODING,
171 g_param_spec_string ("subtitle-encoding", "subtitle charset encoding",
172 "Encoding to assume if input subtitles are not in UTF-8 encoding. "
173 "If not set, the GST_SUBTITLE_ENCODING environment variable will "
174 "be checked for an encoding to use. If that is not set either, "
175 "ISO-8859-15 will be assumed.", DEFAULT_ENCODING, G_PARAM_READWRITE));
179 gst_sub_parse_init (GstSubParse * subparse)
181 subparse->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
182 gst_pad_set_chain_function (subparse->sinkpad,
183 GST_DEBUG_FUNCPTR (gst_sub_parse_chain));
184 gst_pad_set_event_function (subparse->sinkpad,
185 GST_DEBUG_FUNCPTR (gst_sub_parse_sink_event));
186 gst_element_add_pad (GST_ELEMENT (subparse), subparse->sinkpad);
188 subparse->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
189 gst_pad_set_event_function (subparse->srcpad,
190 GST_DEBUG_FUNCPTR (gst_sub_parse_src_event));
191 gst_element_add_pad (GST_ELEMENT (subparse), subparse->srcpad);
193 subparse->textbuf = g_string_new (NULL);
194 subparse->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
195 subparse->flushing = FALSE;
196 subparse->segment = gst_segment_new ();
197 if (subparse->segment) {
198 gst_segment_init (subparse->segment, GST_FORMAT_TIME);
199 subparse->need_segment = TRUE;
201 GST_WARNING_OBJECT (subparse, "segment creation failed");
202 g_assert_not_reached ();
204 subparse->encoding = g_strdup (DEFAULT_ENCODING);
208 * Source pad functions.
212 gst_sub_parse_src_event (GstPad * pad, GstEvent * event)
214 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
215 gboolean ret = FALSE;
217 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
219 switch (GST_EVENT_TYPE (event)) {
223 GstSeekType start_type, stop_type;
228 gst_event_parse_seek (event, &rate, &format, &self->segment_flags,
229 &start_type, &start, &stop_type, &stop);
231 if (format != GST_FORMAT_TIME) {
232 GST_WARNING_OBJECT (self, "we only support seeking in TIME format");
233 gst_event_unref (event);
237 /* Convert that seek to a seeking in bytes at position 0,
238 FIXME: could use an index */
239 ret = gst_pad_push_event (self->sinkpad,
240 gst_event_new_seek (rate, GST_FORMAT_BYTES, self->segment_flags,
241 GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, 0));
244 /* Apply the seek to our segment */
245 gst_segment_set_seek (self->segment, rate, format, self->segment_flags,
246 start_type, start, stop_type, stop, &update);
248 GST_DEBUG_OBJECT (self, "segment configured from %" GST_TIME_FORMAT
249 " to %" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT,
250 GST_TIME_ARGS (self->segment->start),
251 GST_TIME_ARGS (self->segment->stop),
252 GST_TIME_ARGS (self->segment->last_stop));
254 self->next_offset = 0;
256 self->need_segment = TRUE;
258 GST_WARNING_OBJECT (self, "seek to 0 bytes failed");
261 gst_event_unref (event);
265 ret = gst_pad_event_default (pad, event);
270 gst_object_unref (self);
276 gst_sub_parse_set_property (GObject * object, guint prop_id,
277 const GValue * value, GParamSpec * pspec)
279 GstSubParse *subparse = GST_SUBPARSE (object);
281 GST_OBJECT_LOCK (subparse);
284 g_free (subparse->encoding);
285 subparse->encoding = g_value_dup_string (value);
286 GST_LOG_OBJECT (object, "subtitle encoding set to %s",
287 GST_STR_NULL (subparse->encoding));
290 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
293 GST_OBJECT_UNLOCK (subparse);
297 gst_sub_parse_get_property (GObject * object, guint prop_id,
298 GValue * value, GParamSpec * pspec)
300 GstSubParse *subparse = GST_SUBPARSE (object);
302 GST_OBJECT_LOCK (subparse);
305 g_value_set_string (value, subparse->encoding);
308 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
311 GST_OBJECT_UNLOCK (subparse);
315 convert_encoding (GstSubParse * self, const gchar * str, gsize len)
317 const gchar *encoding;
321 if (self->valid_utf8) {
322 if (g_utf8_validate (str, len, NULL)) {
323 GST_LOG_OBJECT (self, "valid UTF-8, no conversion needed");
324 return g_strndup (str, len);
326 GST_INFO_OBJECT (self, "invalid UTF-8!");
327 self->valid_utf8 = FALSE;
330 encoding = self->encoding;
331 if (encoding == NULL || *encoding == '\0') {
332 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
334 if (encoding == NULL || *encoding == '\0') {
335 /* if local encoding is UTF-8 and no encoding specified
336 * via the environment variable, assume ISO-8859-15 */
337 if (g_get_charset (&encoding)) {
338 encoding = "ISO-8859-15";
342 ret = g_convert_with_fallback (str, len, "UTF-8", encoding, "*", NULL,
346 GST_WARNING_OBJECT (self, "could not convert string from '%s' to UTF-8: %s",
347 encoding, err->message);
350 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
351 ret = g_convert_with_fallback (str, len, "UTF-8", "ISO-8859-15", "*",
355 GST_LOG_OBJECT (self, "successfully converted %d characters from %s to UTF-8"
356 "%s", len, encoding, (err) ? " , using ISO-8859-15 as fallback" : "");
362 get_next_line (GstSubParse * self)
365 const char *line_end;
367 gboolean have_r = FALSE;
369 line_end = strchr (self->textbuf->str, '\n');
372 /* end-of-line not found; return for more data */
376 /* get rid of '\r' */
377 if (line_end != self->textbuf->str && *(line_end - 1) == '\r') {
382 line_len = line_end - self->textbuf->str;
383 line = convert_encoding (self, self->textbuf->str, line_len);
384 self->textbuf = g_string_erase (self->textbuf, 0,
385 line_len + (have_r ? 2 : 1));
390 parse_mdvdsub (ParserState * state, const gchar * line)
392 const gchar *line_split;
394 guint start_frame, end_frame;
395 gint64 clip_start = 0, clip_stop = 0;
396 gboolean in_seg = FALSE;
398 /* FIXME: hardcoded for now, but detecting the correct value is
399 * not going to be easy, I suspect... */
400 const double frames_per_sec = 24000 / 1001.;
404 /* style variables */
409 if (sscanf (line, "{%u}{%u}", &start_frame, &end_frame) != 2) {
410 g_warning ("Parse of the following line, assumed to be in microdvd .sub"
411 " format, failed:\n%s", line);
415 state->start_time = (start_frame - 1000) / frames_per_sec * GST_SECOND;
416 state->duration = (end_frame - start_frame) / frames_per_sec * GST_SECOND;
418 /* Check our segment start/stop */
419 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
420 state->start_time, state->start_time + state->duration, &clip_start,
423 /* No need to parse that text if it's out of segment */
425 state->start_time = clip_start;
426 state->duration = clip_stop - clip_start;
431 /* skip the {%u}{%u} part */
432 line = strchr (line, '}') + 1;
433 line = strchr (line, '}') + 1;
435 markup = g_string_new (NULL);
440 /* parse style markup */
441 if (strncmp (line, "{y:i}", 5) == 0) {
443 line = strchr (line, '}') + 1;
445 if (strncmp (line, "{y:b}", 5) == 0) {
447 line = strchr (line, '}') + 1;
449 if (sscanf (line, "{s:%u}", &fontsize) == 1) {
450 line = strchr (line, '}') + 1;
452 if ((line_split = strchr (line, '|')))
453 line_chunk = g_markup_escape_text (line, line_split - line);
455 line_chunk = g_markup_escape_text (line, strlen (line));
456 markup = g_string_append (markup, "<span");
458 g_string_append (markup, " style=\"italic\"");
460 g_string_append (markup, " weight=\"bold\"");
462 g_string_append_printf (markup, " size=\"%u\"", fontsize * 1000);
463 g_string_append_printf (markup, ">%s</span>", line_chunk);
466 g_string_append (markup, "\n");
467 line = line_split + 1;
473 g_string_free (markup, FALSE);
474 GST_DEBUG ("parse_mdvdsub returning (%f+%f): %s",
475 state->start_time / (double) GST_SECOND,
476 state->duration / (double) GST_SECOND, ret);
481 strip_trailing_newlines (gchar * txt)
487 while (len > 1 && txt[len - 1] == '\n') {
494 /* we want to escape text in general, but retain basic markup like
495 * <i></i>, <u></u>, and <b></b>. The easiest and safest way is to
496 * just unescape a white list of allowed markups again after
497 * escaping everything (the text between these simple markers isn't
498 * necessarily escaped, so it seems best to do it like this) */
500 subrip_unescape_formatting (gchar * txt)
504 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
505 if (g_ascii_strncasecmp (pos, "<u>", 9) == 0 ||
506 g_ascii_strncasecmp (pos, "<i>", 9) == 0 ||
507 g_ascii_strncasecmp (pos, "<b>", 9) == 0) {
509 pos[1] = g_ascii_tolower (pos[4]);
511 /* move NUL terminator as well */
512 g_memmove (pos + 3, pos + 9, strlen (pos + 9) + 1);
517 for (pos = txt; pos != NULL && *pos != '\0'; ++pos) {
518 if (g_ascii_strncasecmp (pos, "</u>", 10) == 0 ||
519 g_ascii_strncasecmp (pos, "</i>", 10) == 0 ||
520 g_ascii_strncasecmp (pos, "</b>", 10) == 0) {
523 pos[2] = g_ascii_tolower (pos[5]);
525 /* move NUL terminator as well */
526 g_memmove (pos + 4, pos + 10, strlen (pos + 10) + 1);
532 /* we only allow <i>, <u> and <b>, so let's take a simple approach. This code
533 * assumes the input has been escaped and subrip_unescape_formatting() has then
534 * been run over the input! This function adds missing closing markup tags and
535 * removes broken closing tags for tags that have never been opened. */
537 subrip_fix_up_markup (gchar ** p_txt)
539 gchar *cur, *next_tag;
541 guint num_open_tags = 0;
543 g_assert (*p_txt != NULL);
546 while (*cur != '\0') {
547 next_tag = strchr (cur, '<');
548 if (next_tag == NULL)
554 if (num_open_tags == 0 || open_tags[num_open_tags - 1] != *next_tag) {
555 GST_LOG ("broken input, closing tag '%c' is not open", *next_tag);
556 g_memmove (next_tag - 2, next_tag + 2, strlen (next_tag + 2) + 1);
559 /* it's all good, closing tag which is open */
567 if (num_open_tags == G_N_ELEMENTS (open_tags))
568 return; /* something dodgy is going on, stop parsing */
569 open_tags[num_open_tags] = *next_tag;
573 GST_ERROR ("unexpected tag '%c' (%s)", *next_tag, next_tag);
574 g_assert_not_reached ();
580 if (num_open_tags > 0) {
583 s = g_string_new (*p_txt);
584 while (num_open_tags > 0) {
585 GST_LOG ("adding missing closing tag '%c'", open_tags[num_open_tags - 1]);
586 g_string_append_c (s, '<');
587 g_string_append_c (s, '/');
588 g_string_append_c (s, open_tags[num_open_tags - 1]);
589 g_string_append_c (s, '>');
593 *p_txt = g_string_free (s, FALSE);
598 parse_subrip (ParserState * state, const gchar * line)
600 guint h1, m1, s1, ms1;
601 guint h2, m2, s2, ms2;
605 switch (state->state) {
607 /* looking for a single integer */
608 if (sscanf (line, "%u", &subnum) == 1)
612 /* looking for start_time --> end_time */
613 if (sscanf (line, "%u:%u:%u,%u --> %u:%u:%u,%u",
614 &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) {
617 (((guint64) h1) * 3600 + m1 * 60 + s1) * GST_SECOND +
620 (((guint64) h2) * 3600 + m2 * 60 + s2) * GST_SECOND +
621 ms2 * GST_MSECOND - state->start_time;
623 GST_DEBUG ("error parsing subrip time line");
628 { /* No need to parse that text if it's out of segment */
629 gint64 clip_start = 0, clip_stop = 0;
630 gboolean in_seg = FALSE;
632 /* Check our segment start/stop */
633 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
634 state->start_time, state->start_time + state->duration,
635 &clip_start, &clip_stop);
638 state->start_time = clip_start;
639 state->duration = clip_stop - clip_start;
645 /* looking for subtitle text; empty line ends this
648 g_string_append_c (state->buf, '\n');
649 g_string_append (state->buf, line);
650 if (strlen (line) == 0) {
651 ret = g_markup_escape_text (state->buf->str, state->buf->len);
652 g_string_truncate (state->buf, 0);
654 subrip_unescape_formatting (ret);
655 strip_trailing_newlines (ret);
656 subrip_fix_up_markup (&ret);
661 g_return_val_if_reached (NULL);
666 parse_mpsub (ParserState * state, const gchar * line)
671 switch (state->state) {
673 /* looking for two floats (offset, duration) */
674 if (sscanf (line, "%f %f", &t1, &t2) == 2) {
676 state->start_time += state->duration + GST_SECOND * t1;
677 state->duration = GST_SECOND * t2;
681 { /* No need to parse that text if it's out of segment */
682 gint64 clip_start = 0, clip_stop = 0;
683 gboolean in_seg = FALSE;
685 /* Check our segment start/stop */
686 in_seg = gst_segment_clip (state->segment, GST_FORMAT_TIME,
687 state->start_time, state->start_time + state->duration,
688 &clip_start, &clip_stop);
691 state->start_time = clip_start;
692 state->duration = clip_stop - clip_start;
698 /* looking for subtitle text; empty line ends this
701 g_string_append_c (state->buf, '\n');
702 g_string_append (state->buf, line);
703 if (strlen (line) == 0) {
704 ret = g_strdup (state->buf->str);
705 g_string_truncate (state->buf, 0);
711 g_assert_not_reached ();
717 parser_state_init (ParserState * state)
719 GST_DEBUG ("initialising parser");
722 g_string_truncate (state->buf, 0);
724 state->buf = g_string_new (NULL);
727 state->start_time = 0;
730 state->segment = NULL;
734 parser_state_dispose (ParserState * state)
737 g_string_free (state->buf, TRUE);
740 if (state->user_data) {
741 sami_context_reset (state);
746 * FIXME: maybe we should pass along a second argument, the preceding
747 * text buffer, because that is how this originally worked, even though
748 * I don't really see the use of that.
751 static GstSubParseFormat
752 gst_sub_parse_data_format_autodetect (gchar * match_str)
754 static gboolean need_init_regexps = TRUE;
755 static regex_t mdvd_rx;
756 static regex_t subrip_rx;
758 /* initialize the regexps used the first time around */
759 if (need_init_regexps) {
763 need_init_regexps = FALSE;
764 if ((err = regcomp (&mdvd_rx, "^\\{[0-9]+\\}\\{[0-9]+\\}",
765 REG_EXTENDED | REG_NEWLINE | REG_NOSUB) != 0) ||
766 (err = regcomp (&subrip_rx, "^[1-9]([0-9]){0,3}(\x0d)?\x0a"
767 "[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}"
768 " --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]{3}",
769 REG_EXTENDED | REG_NEWLINE | REG_NOSUB)) != 0) {
770 regerror (err, &subrip_rx, errstr, 127);
771 GST_WARNING ("Compilation of subrip regex failed: %s", errstr);
775 if (regexec (&mdvd_rx, match_str, 0, NULL, 0) == 0) {
776 GST_LOG ("MicroDVD (frame based) format detected");
777 return GST_SUB_PARSE_FORMAT_MDVDSUB;
779 if (regexec (&subrip_rx, match_str, 0, NULL, 0) == 0) {
780 GST_LOG ("SubRip (time based) format detected");
781 return GST_SUB_PARSE_FORMAT_SUBRIP;
783 if (!strncmp (match_str, "FORMAT=TIME", 11)) {
784 GST_LOG ("MPSub (time based) format detected");
785 return GST_SUB_PARSE_FORMAT_MPSUB;
787 if (strstr (match_str, "<SAMI>") != NULL ||
788 strstr (match_str, "<sami>") != NULL) {
789 GST_LOG ("SAMI (time based) format detected");
790 return GST_SUB_PARSE_FORMAT_SAMI;
793 GST_DEBUG ("no subtitle format detected");
794 return GST_SUB_PARSE_FORMAT_UNKNOWN;
798 gst_sub_parse_format_autodetect (GstSubParse * self)
801 GstSubParseFormat format;
803 if (strlen (self->textbuf->str) < 35) {
804 GST_DEBUG ("File too small to be a subtitles file");
808 data = g_strndup (self->textbuf->str, 35);
809 format = gst_sub_parse_data_format_autodetect (data);
812 self->parser_type = format;
813 parser_state_init (&self->state);
816 case GST_SUB_PARSE_FORMAT_MDVDSUB:
817 self->parse_line = parse_mdvdsub;
818 return gst_caps_new_simple ("text/x-pango-markup", NULL);
819 case GST_SUB_PARSE_FORMAT_SUBRIP:
820 self->parse_line = parse_subrip;
821 return gst_caps_new_simple ("text/x-pango-markup", NULL);
822 case GST_SUB_PARSE_FORMAT_MPSUB:
823 self->parse_line = parse_mpsub;
824 return gst_caps_new_simple ("text/plain", NULL);
825 case GST_SUB_PARSE_FORMAT_SAMI:
826 self->parse_line = parse_sami;
827 sami_context_init (&self->state);
828 return gst_caps_new_simple ("text/x-pango-markup", NULL);
829 case GST_SUB_PARSE_FORMAT_UNKNOWN:
831 GST_DEBUG ("no subtitle format detected");
832 GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE,
833 ("The input is not a valid/supported subtitle file"), (NULL));
839 feed_textbuf (GstSubParse * self, GstBuffer * buf)
841 if (GST_BUFFER_OFFSET (buf) != self->offset) {
842 /* flush the parser state */
843 parser_state_init (&self->state);
844 g_string_truncate (self->textbuf, 0);
845 sami_context_reset (&self->state);
848 self->textbuf = g_string_append_len (self->textbuf,
849 (gchar *) GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
850 self->offset = GST_BUFFER_OFFSET (buf) + GST_BUFFER_SIZE (buf);
851 self->next_offset = self->offset;
853 gst_buffer_unref (buf);
857 handle_buffer (GstSubParse * self, GstBuffer * buf)
859 GstFlowReturn ret = GST_FLOW_OK;
860 GstCaps *caps = NULL;
861 gchar *line, *subtitle;
863 feed_textbuf (self, buf);
865 /* make sure we know the format */
866 if (G_UNLIKELY (self->parser_type == GST_SUB_PARSE_FORMAT_UNKNOWN)) {
867 if (!(caps = gst_sub_parse_format_autodetect (self))) {
868 return GST_FLOW_UNEXPECTED;
870 if (!gst_pad_set_caps (self->srcpad, caps)) {
871 gst_caps_unref (caps);
872 return GST_FLOW_UNEXPECTED;
874 gst_caps_unref (caps);
877 while ((line = get_next_line (self)) && !self->flushing) {
878 /* Set segment on our parser state machine */
879 self->state.segment = self->segment;
880 /* Now parse the line, out of segment lines will just return NULL */
881 GST_DEBUG ("Parsing line '%s'", line);
882 subtitle = self->parse_line (&self->state, line);
886 guint subtitle_len = strlen (subtitle);
888 /* +1 for terminating NUL character */
889 ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
890 GST_BUFFER_OFFSET_NONE, subtitle_len + 1,
891 GST_PAD_CAPS (self->srcpad), &buf);
893 if (ret == GST_FLOW_OK) {
894 /* copy terminating NUL character as well */
895 memcpy (GST_BUFFER_DATA (buf), subtitle, subtitle_len + 1);
896 GST_BUFFER_SIZE (buf) = subtitle_len;
897 GST_BUFFER_TIMESTAMP (buf) = self->state.start_time;
898 GST_BUFFER_DURATION (buf) = self->state.duration;
900 gst_segment_set_last_stop (self->segment, GST_FORMAT_TIME,
901 self->state.start_time);
903 GST_DEBUG ("Sending text '%s', %" GST_TIME_FORMAT " + %"
904 GST_TIME_FORMAT, subtitle, GST_TIME_ARGS (self->state.start_time),
905 GST_TIME_ARGS (self->state.duration));
907 ret = gst_pad_push (self->srcpad, buf);
913 if (GST_FLOW_IS_FATAL (ret))
922 gst_sub_parse_chain (GstPad * sinkpad, GstBuffer * buf)
927 GST_DEBUG ("gst_sub_parse_chain");
928 self = GST_SUBPARSE (gst_pad_get_parent (sinkpad));
930 /* Push newsegment if needed */
931 if (self->need_segment) {
932 gst_pad_push_event (self->srcpad, gst_event_new_new_segment (FALSE,
933 self->segment->rate, self->segment->format,
934 self->segment->last_stop, self->segment->stop,
935 self->segment->time));
936 self->need_segment = FALSE;
939 ret = handle_buffer (self, buf);
941 gst_object_unref (self);
947 gst_sub_parse_sink_event (GstPad * pad, GstEvent * event)
949 GstSubParse *self = GST_SUBPARSE (gst_pad_get_parent (pad));
950 gboolean ret = FALSE;
952 GST_DEBUG ("Handling %s event", GST_EVENT_TYPE_NAME (event));
954 switch (GST_EVENT_TYPE (event)) {
956 /* Make sure the last subrip chunk is pushed out even
957 * if the file does not have an empty line at the end */
958 if (self->parser_type == GST_SUB_PARSE_FORMAT_SUBRIP) {
959 GstBuffer *buf = gst_buffer_new_and_alloc (1 + 1);
961 GST_DEBUG ("EOS. Pushing remaining text (if any)");
962 GST_BUFFER_DATA (buf)[0] = '\n';
963 GST_BUFFER_DATA (buf)[1] = '\0'; /* play it safe */
964 GST_BUFFER_SIZE (buf) = 1;
965 GST_BUFFER_OFFSET (buf) = self->offset;
966 gst_sub_parse_chain (pad, buf);
968 ret = gst_pad_event_default (pad, event);
971 case GST_EVENT_NEWSEGMENT:
975 gint64 start, stop, time;
978 GST_DEBUG_OBJECT (self, "received new segment");
980 gst_event_parse_new_segment (event, &update, &rate, &format, &start,
983 /* now copy over the values */
984 gst_segment_set_newsegment (self->segment, update, rate, format,
988 gst_event_unref (event);
991 case GST_EVENT_FLUSH_START:
993 self->flushing = TRUE;
995 ret = gst_pad_event_default (pad, event);
998 case GST_EVENT_FLUSH_STOP:
1000 self->flushing = FALSE;
1002 ret = gst_pad_event_default (pad, event);
1006 ret = gst_pad_event_default (pad, event);
1010 gst_object_unref (self);
1016 static GstStateChangeReturn
1017 gst_sub_parse_change_state (GstElement * element, GstStateChange transition)
1019 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1020 GstSubParse *self = GST_SUBPARSE (element);
1022 switch (transition) {
1023 case GST_STATE_CHANGE_READY_TO_PAUSED:
1024 /* format detection will init the parser state */
1026 self->next_offset = 0;
1027 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1028 self->valid_utf8 = TRUE;
1029 g_string_truncate (self->textbuf, 0);
1035 ret = parent_class->change_state (element, transition);
1036 if (ret == GST_STATE_CHANGE_FAILURE)
1039 switch (transition) {
1040 case GST_STATE_CHANGE_PAUSED_TO_READY:
1041 parser_state_dispose (&self->state);
1042 self->parser_type = GST_SUB_PARSE_FORMAT_UNKNOWN;
1055 static GstStaticCaps smi_caps = GST_STATIC_CAPS ("application/x-subtitle-sami");
1056 static GstStaticCaps sub_caps = GST_STATIC_CAPS ("application/x-subtitle");
1058 #define SUB_CAPS (gst_static_caps_get (&sub_caps))
1059 #define SAMI_CAPS (gst_static_caps_get (&smi_caps))
1062 gst_subparse_type_find (GstTypeFind * tf, gpointer private)
1064 GstSubParseFormat format;
1069 if (!(data = gst_type_find_peek (tf, 0, 36)))
1072 /* make sure string passed to _autodetect() is NUL-terminated */
1073 str = g_strndup ((gchar *) data, 35);
1074 format = gst_sub_parse_data_format_autodetect (str);
1078 case GST_SUB_PARSE_FORMAT_MDVDSUB:
1079 GST_DEBUG ("MicroDVD format detected");
1082 case GST_SUB_PARSE_FORMAT_SUBRIP:
1083 GST_DEBUG ("SubRip format detected");
1086 case GST_SUB_PARSE_FORMAT_MPSUB:
1087 GST_DEBUG ("MPSub format detected");
1090 case GST_SUB_PARSE_FORMAT_SAMI:
1091 GST_DEBUG ("SAMI (time-based) format detected");
1095 case GST_SUB_PARSE_FORMAT_UNKNOWN:
1096 GST_DEBUG ("no subtitle format detected");
1100 /* if we're here, it's ok */
1101 gst_type_find_suggest (tf, GST_TYPE_FIND_MAXIMUM, caps);
1105 plugin_init (GstPlugin * plugin)
1107 static gchar *sub_exts[] = { "srt", "sub", "mpsub", "mdvd", "smi", NULL };
1109 GST_DEBUG_CATEGORY_INIT (sub_parse_debug, "subparse", 0, ".sub parser");
1111 if (!gst_type_find_register (plugin, "subparse_typefind", GST_RANK_MARGINAL,
1112 gst_subparse_type_find, sub_exts, SUB_CAPS, NULL, NULL))
1115 if (!gst_element_register (plugin, "subparse",
1116 GST_RANK_PRIMARY, GST_TYPE_SUBPARSE) ||
1117 !gst_element_register (plugin, "ssaparse",
1118 GST_RANK_PRIMARY, GST_TYPE_SSA_PARSE)) {
1125 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1129 plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)