8bb331434e7fba8dcfb2c08304d793044eb617cf
[framework/multimedia/gst-plugins-base0.10.git] / gst-libs / gst / tag / gsttagdemux.c
1 /* GStreamer Base Class for Tag Demuxing
2  * Copyright (C) 2005 Jan Schmidt <thaytan@mad.scientist.com>
3  * Copyright (C) 2006-2007 Tim-Philipp Müller <tim centricular net>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:gsttagdemux
23  * @see_also: GstApeDemux, GstID3Demux
24  * @short_description: Base class for demuxing tags that are in chunks
25  *                     directly at the beginning or at the end of a file
26  * 
27  * <refsect2>
28  * <para>
29  * Provides a base class for demuxing tags at the beginning or end of a
30  * stream and handles things like typefinding, querying, seeking, and
31  * different modes of operation (chain-based, pull_range-based, and providing
32  * downstream elements with random access if upstream supports that). The tag
33  * is stripped from the output, and all offsets are adjusted for the tag
34  * sizes, so that to the downstream element the stream will appear as if
35  * there was no tag at all. Also, once the tag has been parsed, GstTagDemux
36  * will try to determine the media type of the resulting stream and add a
37  * source pad with the appropriate caps in order to facilitate auto-plugging.
38  * </para>
39  * <title>Deriving from GstTagDemux</title>
40  * <para>
41  * Subclasses have to do four things:
42  * <itemizedlist>
43  *  <listitem><para>
44  *  In their base init function, they must add a pad template for the sink
45  *  pad to the element class, describing the media type they can parse in
46  *  the caps of the pad template.
47  *  </para></listitem>
48  *  <listitem><para>
49  *  In their class init function, they must override
50  *  GST_TAG_DEMUX_CLASS(demux_klass)->identify_tag with their own identify
51  *  function.
52  *  </para></listitem>
53  *  <listitem><para>
54  *  In their class init function, they must override
55  *  GST_TAG_DEMUX_CLASS(demux_klass)->parse_tag with their own parse
56  *  function.
57  *  </para></listitem>
58  *  <listitem><para>
59  *  In their class init function, they must also set
60  *  GST_TAG_DEMUX_CLASS(demux_klass)->min_start_size and/or 
61  *  GST_TAG_DEMUX_CLASS(demux_klass)->min_end_size to the minimum size required
62  *  for the identify function to decide whether the stream has a supported tag
63  *  or not. A class parsing ID3v1 tags, for example, would set min_end_size to
64  *  128 bytes.
65  *  </para></listitem>
66  * </itemizedlist>
67  * </para>
68  * </refsect2>
69  */
70
71 #ifdef HAVE_CONFIG_H
72 #include "config.h"
73 #endif
74
75 #include "gsttagdemux.h"
76
77 #include <gst/base/gsttypefindhelper.h>
78 #include <gst/gst-i18n-plugin.h>
79 #include <string.h>
80
81 typedef enum
82 {
83   GST_TAG_DEMUX_READ_START_TAG,
84   GST_TAG_DEMUX_TYPEFINDING,
85   GST_TAG_DEMUX_STREAMING
86 } GstTagDemuxState;
87
88 struct _GstTagDemuxPrivate
89 {
90   GstPad *srcpad;
91   GstPad *sinkpad;
92
93   /* Number of bytes to remove from the
94    * start of file (tag at beginning) */
95   guint strip_start;
96
97   /* Number of bytes to remove from the
98    * end of file (tag at end) */
99   guint strip_end;
100
101   gint64 upstream_size;
102
103   GstTagDemuxState state;
104   GstBuffer *collect;
105   GstCaps *src_caps;
106
107   GstTagList *event_tags;
108   GstTagList *parsed_tags;
109   gboolean send_tag_event;
110
111   GstSegment segment;
112   gboolean need_newseg;
113   gboolean newseg_update;
114
115   GList *pending_events;
116 };
117
118 /* Require at least 8kB of data before we attempt typefind. 
119  * Seems a decent value based on test files
120  * 40kB is massive overkill for the maximum, I think, but it 
121  * doesn't do any harm (tpm: increased to 64kB after watching
122  * typefinding fail on a wavpack file that needed 42kB to succeed) */
123 #define TYPE_FIND_MIN_SIZE 8192
124 #define TYPE_FIND_MAX_SIZE 65536
125
126 GST_DEBUG_CATEGORY_STATIC (tagdemux_debug);
127 #define GST_CAT_DEFAULT (tagdemux_debug)
128
129 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
130     GST_PAD_SRC,
131     GST_PAD_SOMETIMES,
132     GST_STATIC_CAPS ("ANY")
133     );
134
135 static void gst_tag_demux_dispose (GObject * object);
136
137 static GstFlowReturn gst_tag_demux_chain (GstPad * pad, GstBuffer * buf);
138 static gboolean gst_tag_demux_sink_event (GstPad * pad, GstEvent * event);
139
140 static gboolean gst_tag_demux_src_activate_pull (GstPad * pad, gboolean active);
141 static GstFlowReturn gst_tag_demux_read_range (GstTagDemux * tagdemux,
142     guint64 offset, guint length, GstBuffer ** buffer);
143
144 static gboolean gst_tag_demux_src_checkgetrange (GstPad * srcpad);
145 static GstFlowReturn gst_tag_demux_src_getrange (GstPad * srcpad,
146     guint64 offset, guint length, GstBuffer ** buffer);
147
148 static gboolean gst_tag_demux_add_srcpad (GstTagDemux * tagdemux,
149     GstCaps * new_caps);
150 static gboolean gst_tag_demux_remove_srcpad (GstTagDemux * tagdemux);
151
152 static gboolean gst_tag_demux_srcpad_event (GstPad * pad, GstEvent * event);
153 static gboolean gst_tag_demux_sink_activate (GstPad * sinkpad);
154 static GstStateChangeReturn gst_tag_demux_change_state (GstElement * element,
155     GstStateChange transition);
156 static gboolean gst_tag_demux_pad_query (GstPad * pad, GstQuery * query);
157 static const GstQueryType *gst_tag_demux_get_query_types (GstPad * pad);
158 static gboolean gst_tag_demux_get_upstream_size (GstTagDemux * tagdemux);
159 static void gst_tag_demux_send_pending_events (GstTagDemux * tagdemux);
160 static void gst_tag_demux_send_tag_event (GstTagDemux * tagdemux);
161 static gboolean gst_tag_demux_send_new_segment (GstTagDemux * tagdemux);
162
163 static void gst_tag_demux_base_init (gpointer g_class);
164 static void gst_tag_demux_class_init (gpointer g_class, gpointer d);
165 static void gst_tag_demux_init (GstTagDemux * obj, GstTagDemuxClass * klass);
166
167 static gpointer parent_class;   /* NULL */
168
169 GType
170 gst_tag_demux_result_get_type (void)
171 {
172   static GType etype = 0;
173   if (etype == 0) {
174     static const GEnumValue values[] = {
175       {GST_TAG_DEMUX_RESULT_BROKEN_TAG, "GST_TAG_DEMUX_RESULT_BROKEN_TAG",
176           "broken-tag"},
177       {GST_TAG_DEMUX_RESULT_AGAIN, "GST_TAG_DEMUX_RESULT_AGAIN", "again"},
178       {GST_TAG_DEMUX_RESULT_OK, "GST_TAG_DEMUX_RESULT_OK", "ok"},
179       {0, NULL, NULL}
180     };
181     etype = g_enum_register_static ("GstTagDemuxResult", values);
182   }
183   return etype;
184 }
185
186 /* Cannot use boilerplate macros here because we want the abstract flag */
187 GType
188 gst_tag_demux_get_type (void)
189 {
190   static GType object_type;     /* 0 */
191
192   if (object_type == 0) {
193     static const GTypeInfo object_info = {
194       sizeof (GstTagDemuxClass),
195       gst_tag_demux_base_init,
196       NULL,                     /* base_finalize */
197       gst_tag_demux_class_init,
198       NULL,                     /* class_finalize */
199       NULL,                     /* class_data */
200       sizeof (GstTagDemux),
201       0,                        /* n_preallocs */
202       (GInstanceInitFunc) gst_tag_demux_init
203     };
204
205     object_type = g_type_register_static (GST_TYPE_ELEMENT,
206         "GstTagDemux", &object_info, G_TYPE_FLAG_ABSTRACT);
207   }
208
209   return object_type;
210 }
211
212 static void
213 gst_tag_demux_base_init (gpointer klass)
214 {
215   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
216
217   gst_element_class_add_pad_template (element_class,
218       gst_static_pad_template_get (&src_factory));
219
220   GST_DEBUG_CATEGORY_INIT (tagdemux_debug, "tagdemux", 0,
221       "tag demux base class");
222 }
223
224 static void
225 gst_tag_demux_class_init (gpointer klass, gpointer d)
226 {
227   GstTagDemuxClass *tagdemux_class = GST_TAG_DEMUX_CLASS (klass);
228   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
229   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
230
231   parent_class = g_type_class_peek_parent (klass);
232
233   gobject_class->dispose = gst_tag_demux_dispose;
234
235   element_class->change_state = GST_DEBUG_FUNCPTR (gst_tag_demux_change_state);
236
237   g_type_class_add_private (klass, sizeof (GstTagDemuxPrivate));
238
239   /* subclasses must set at least one of these */
240   tagdemux_class->min_start_size = 0;
241   tagdemux_class->min_end_size = 0;
242 }
243
244 static void
245 gst_tag_demux_reset (GstTagDemux * tagdemux)
246 {
247   GstBuffer **buffer_p = &tagdemux->priv->collect;
248   GstCaps **caps_p = &tagdemux->priv->src_caps;
249
250   tagdemux->priv->strip_start = 0;
251   tagdemux->priv->strip_end = 0;
252   tagdemux->priv->upstream_size = -1;
253   tagdemux->priv->state = GST_TAG_DEMUX_READ_START_TAG;
254   tagdemux->priv->send_tag_event = FALSE;
255
256   gst_buffer_replace (buffer_p, NULL);
257   gst_caps_replace (caps_p, NULL);
258
259   gst_tag_demux_remove_srcpad (tagdemux);
260
261   if (tagdemux->priv->event_tags) {
262     gst_tag_list_free (tagdemux->priv->event_tags);
263     tagdemux->priv->event_tags = NULL;
264   }
265   if (tagdemux->priv->parsed_tags) {
266     gst_tag_list_free (tagdemux->priv->parsed_tags);
267     tagdemux->priv->parsed_tags = NULL;
268   }
269
270   gst_segment_init (&tagdemux->priv->segment, GST_FORMAT_UNDEFINED);
271   tagdemux->priv->need_newseg = TRUE;
272   tagdemux->priv->newseg_update = FALSE;
273
274   g_list_foreach (tagdemux->priv->pending_events,
275       (GFunc) gst_mini_object_unref, NULL);
276   g_list_free (tagdemux->priv->pending_events);
277   tagdemux->priv->pending_events = NULL;
278 }
279
280 static void
281 gst_tag_demux_init (GstTagDemux * demux, GstTagDemuxClass * gclass)
282 {
283   GstElementClass *element_klass = GST_ELEMENT_CLASS (gclass);
284   GstPadTemplate *tmpl;
285
286   demux->priv = g_type_instance_get_private ((GTypeInstance *) demux,
287       GST_TYPE_TAG_DEMUX);
288
289   tmpl = gst_element_class_get_pad_template (element_klass, "sink");
290   if (tmpl) {
291     demux->priv->sinkpad = gst_pad_new_from_template (tmpl, "sink");
292
293     gst_pad_set_activate_function (demux->priv->sinkpad,
294         GST_DEBUG_FUNCPTR (gst_tag_demux_sink_activate));
295     gst_pad_set_event_function (demux->priv->sinkpad,
296         GST_DEBUG_FUNCPTR (gst_tag_demux_sink_event));
297     gst_pad_set_chain_function (demux->priv->sinkpad,
298         GST_DEBUG_FUNCPTR (gst_tag_demux_chain));
299     gst_element_add_pad (GST_ELEMENT (demux), demux->priv->sinkpad);
300   }
301
302   gst_tag_demux_reset (demux);
303 }
304
305 static void
306 gst_tag_demux_dispose (GObject * object)
307 {
308   GstTagDemux *tagdemux = GST_TAG_DEMUX (object);
309
310   gst_tag_demux_reset (tagdemux);
311
312   G_OBJECT_CLASS (parent_class)->dispose (object);
313 }
314
315 static gboolean
316 gst_tag_demux_add_srcpad (GstTagDemux * tagdemux, GstCaps * new_caps)
317 {
318   if (tagdemux->priv->src_caps == NULL ||
319       !gst_caps_is_equal (new_caps, tagdemux->priv->src_caps)) {
320
321     gst_caps_replace (&tagdemux->priv->src_caps, new_caps);
322
323     if (tagdemux->priv->srcpad != NULL) {
324       GST_DEBUG_OBJECT (tagdemux, "Changing src pad caps to %" GST_PTR_FORMAT,
325           tagdemux->priv->src_caps);
326
327       gst_pad_set_caps (tagdemux->priv->srcpad, tagdemux->priv->src_caps);
328     }
329   } else {
330     /* Caps never changed */
331   }
332
333   if (tagdemux->priv->srcpad == NULL) {
334     tagdemux->priv->srcpad =
335         gst_pad_new_from_template (gst_element_class_get_pad_template
336         (GST_ELEMENT_GET_CLASS (tagdemux), "src"), "src");
337     g_return_val_if_fail (tagdemux->priv->srcpad != NULL, FALSE);
338
339     gst_pad_set_query_type_function (tagdemux->priv->srcpad,
340         GST_DEBUG_FUNCPTR (gst_tag_demux_get_query_types));
341     gst_pad_set_query_function (tagdemux->priv->srcpad,
342         GST_DEBUG_FUNCPTR (gst_tag_demux_pad_query));
343     gst_pad_set_event_function (tagdemux->priv->srcpad,
344         GST_DEBUG_FUNCPTR (gst_tag_demux_srcpad_event));
345     gst_pad_set_activatepull_function (tagdemux->priv->srcpad,
346         GST_DEBUG_FUNCPTR (gst_tag_demux_src_activate_pull));
347     gst_pad_set_checkgetrange_function (tagdemux->priv->srcpad,
348         GST_DEBUG_FUNCPTR (gst_tag_demux_src_checkgetrange));
349     gst_pad_set_getrange_function (tagdemux->priv->srcpad,
350         GST_DEBUG_FUNCPTR (gst_tag_demux_src_getrange));
351
352     gst_pad_use_fixed_caps (tagdemux->priv->srcpad);
353
354     if (tagdemux->priv->src_caps)
355       gst_pad_set_caps (tagdemux->priv->srcpad, tagdemux->priv->src_caps);
356
357     GST_DEBUG_OBJECT (tagdemux, "Adding src pad with caps %" GST_PTR_FORMAT,
358         tagdemux->priv->src_caps);
359
360     gst_object_ref (tagdemux->priv->srcpad);
361     gst_pad_set_active (tagdemux->priv->srcpad, TRUE);
362     if (!gst_element_add_pad (GST_ELEMENT (tagdemux), tagdemux->priv->srcpad))
363       return FALSE;
364     gst_element_no_more_pads (GST_ELEMENT (tagdemux));
365   }
366
367   return TRUE;
368 }
369
370 static gboolean
371 gst_tag_demux_remove_srcpad (GstTagDemux * demux)
372 {
373   gboolean res = TRUE;
374
375   if (demux->priv->srcpad != NULL) {
376     GST_DEBUG_OBJECT (demux, "Removing src pad");
377     res = gst_element_remove_pad (GST_ELEMENT (demux), demux->priv->srcpad);
378     g_return_val_if_fail (res != FALSE, FALSE);
379     gst_object_unref (demux->priv->srcpad);
380     demux->priv->srcpad = NULL;
381   }
382
383   return res;
384 };
385
386 /* will return FALSE if buffer is beyond end of data; will return TRUE
387  * if buffer was trimmed successfully or didn't need trimming, but may
388  * also return TRUE and set *buf_ref to NULL if the buffer was before
389  * the start of the data */
390 static gboolean
391 gst_tag_demux_trim_buffer (GstTagDemux * tagdemux, GstBuffer ** buf_ref)
392 {
393   GstBuffer *buf = *buf_ref;
394
395   guint trim_start = 0;
396   guint out_size = GST_BUFFER_SIZE (buf);
397   guint64 out_offset = GST_BUFFER_OFFSET (buf);
398   gboolean need_sub = FALSE;
399
400   /* Adjust offset and length */
401   if (!GST_BUFFER_OFFSET_IS_VALID (buf)) {
402     /* Can't change anything without an offset */
403     return TRUE;
404   }
405
406   /* If the buffer crosses the tag at the end of file, trim it */
407   if (tagdemux->priv->strip_end > 0) {
408     if (gst_tag_demux_get_upstream_size (tagdemux)) {
409       guint64 v1tag_offset =
410           tagdemux->priv->upstream_size - tagdemux->priv->strip_end;
411
412       if (out_offset >= v1tag_offset) {
413         GST_DEBUG_OBJECT (tagdemux, "Buffer is past the end of the data");
414         goto no_out_buffer_end;
415       }
416
417       if (out_offset + out_size > v1tag_offset) {
418         out_size = v1tag_offset - out_offset;
419         need_sub = TRUE;
420       }
421     }
422   }
423
424   if (tagdemux->priv->strip_start > 0) {
425     /* If the buffer crosses the tag at the start of file, trim it */
426     if (out_offset <= tagdemux->priv->strip_start) {
427       if (out_offset + out_size <= tagdemux->priv->strip_start) {
428         GST_DEBUG_OBJECT (tagdemux, "Buffer is before the start of the data");
429         goto no_out_buffer_start;
430       }
431
432       trim_start = tagdemux->priv->strip_start - out_offset;
433       out_size -= trim_start;
434       out_offset = 0;
435     } else {
436       out_offset -= tagdemux->priv->strip_start;
437     }
438     need_sub = TRUE;
439   }
440
441   if (need_sub == TRUE) {
442     if (out_size != GST_BUFFER_SIZE (buf) || !gst_buffer_is_writable (buf)) {
443       GstBuffer *sub;
444
445       GST_DEBUG_OBJECT (tagdemux, "Sub-buffering to trim size %d offset %"
446           G_GINT64_FORMAT " to %d offset %" G_GINT64_FORMAT,
447           GST_BUFFER_SIZE (buf), GST_BUFFER_OFFSET (buf), out_size, out_offset);
448
449       sub = gst_buffer_create_sub (buf, trim_start, out_size);
450       g_return_val_if_fail (sub != NULL, FALSE);
451       gst_buffer_unref (buf);
452       *buf_ref = buf = sub;
453     } else {
454       GST_DEBUG_OBJECT (tagdemux, "Adjusting buffer from size %d offset %"
455           G_GINT64_FORMAT " to %d offset %" G_GINT64_FORMAT,
456           GST_BUFFER_SIZE (buf), GST_BUFFER_OFFSET (buf), out_size, out_offset);
457     }
458
459     GST_BUFFER_OFFSET (buf) = out_offset;
460     GST_BUFFER_OFFSET_END (buf) = out_offset + out_size;
461     gst_buffer_set_caps (buf, tagdemux->priv->src_caps);
462   }
463
464   return TRUE;
465
466 no_out_buffer_end:
467   {
468     gst_buffer_unref (buf);
469     *buf_ref = NULL;
470     return FALSE;
471   }
472 no_out_buffer_start:
473   {
474     gst_buffer_unref (buf);
475     *buf_ref = NULL;
476     return TRUE;
477   }
478 }
479
480 static void
481 gst_tag_demux_chain_parse_tag (GstTagDemux * demux, GstBuffer * collect)
482 {
483   GstTagDemuxResult parse_ret;
484   GstTagDemuxClass *klass;
485   guint tagsize = 0;
486   guint available;
487
488   g_assert (gst_buffer_is_metadata_writable (collect));
489
490   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
491
492   /* If we receive a buffer that's from the middle of the file, 
493    * we can't read tags so move to typefinding */
494   if (GST_BUFFER_OFFSET_IS_VALID (collect) && GST_BUFFER_OFFSET (collect) != 0) {
495     GST_DEBUG_OBJECT (demux, "Received buffer from non-zero offset %"
496         G_GINT64_FORMAT ". Can't read tags", GST_BUFFER_OFFSET (collect));
497     demux->priv->state = GST_TAG_DEMUX_TYPEFINDING;
498     return;
499   }
500
501   g_assert (klass->identify_tag != NULL);
502   g_assert (klass->parse_tag != NULL);
503
504   available = GST_BUFFER_SIZE (collect);
505
506   if (available < klass->min_start_size) {
507     GST_DEBUG_OBJECT (demux, "Only %u bytes available, but %u needed "
508         "to identify tag", available, klass->min_start_size);
509     return;                     /* wait for more data */
510   }
511
512   if (!klass->identify_tag (demux, collect, TRUE, &tagsize)) {
513     GST_DEBUG_OBJECT (demux, "Could not identify start tag");
514     demux->priv->state = GST_TAG_DEMUX_TYPEFINDING;
515     return;
516   }
517
518   /* need to set offset of first buffer to 0 or trimming won't work */
519   if (!GST_BUFFER_OFFSET_IS_VALID (collect)) {
520     GST_WARNING_OBJECT (demux, "Fixing up first buffer without offset");
521     GST_BUFFER_OFFSET (collect) = 0;
522   }
523
524   GST_DEBUG_OBJECT (demux, "Identified tag, size = %u bytes", tagsize);
525
526   do {
527     GstTagList *tags = NULL;
528     guint newsize, saved_size;
529
530     demux->priv->strip_start = tagsize;
531
532     if (available < tagsize) {
533       GST_DEBUG_OBJECT (demux, "Only %u bytes available, but %u needed "
534           "to parse tag", available, tagsize);
535       return;                   /* wait for more data */
536     }
537
538     saved_size = GST_BUFFER_SIZE (collect);
539     GST_BUFFER_SIZE (collect) = tagsize;
540     newsize = tagsize;
541
542     parse_ret = klass->parse_tag (demux, collect, TRUE, &newsize, &tags);
543
544     GST_BUFFER_SIZE (collect) = saved_size;
545
546     switch (parse_ret) {
547       case GST_TAG_DEMUX_RESULT_OK:
548         demux->priv->strip_start = newsize;
549         demux->priv->parsed_tags = tags;
550         GST_DEBUG_OBJECT (demux, "Read start tag of size %u", newsize);
551         break;
552       case GST_TAG_DEMUX_RESULT_BROKEN_TAG:
553         demux->priv->strip_start = newsize;
554         demux->priv->parsed_tags = tags;
555         GST_WARNING_OBJECT (demux, "Ignoring broken start tag of size %d",
556             demux->priv->strip_start);
557         break;
558       case GST_TAG_DEMUX_RESULT_AGAIN:
559         GST_DEBUG_OBJECT (demux, "Re-parse, this time with %u bytes", newsize);
560         g_assert (newsize != tagsize);
561         tagsize = newsize;
562         break;
563     }
564   } while (parse_ret == GST_TAG_DEMUX_RESULT_AGAIN);
565
566   GST_LOG_OBJECT (demux, "Parsed tag. Proceeding to typefinding");
567   demux->priv->state = GST_TAG_DEMUX_TYPEFINDING;
568   demux->priv->send_tag_event = TRUE;
569 }
570
571 static GstFlowReturn
572 gst_tag_demux_chain (GstPad * pad, GstBuffer * buf)
573 {
574   GstTagDemux *demux;
575
576   demux = GST_TAG_DEMUX (GST_PAD_PARENT (pad));
577
578   /* Update our segment last_stop info */
579   if (demux->priv->segment.format == GST_FORMAT_BYTES) {
580     if (GST_BUFFER_OFFSET_IS_VALID (buf))
581       demux->priv->segment.last_stop = GST_BUFFER_OFFSET (buf);
582     demux->priv->segment.last_stop += GST_BUFFER_SIZE (buf);
583   } else if (demux->priv->segment.format == GST_FORMAT_TIME) {
584     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf))
585       demux->priv->segment.last_stop = GST_BUFFER_TIMESTAMP (buf);
586     if (GST_BUFFER_DURATION_IS_VALID (buf))
587       demux->priv->segment.last_stop += GST_BUFFER_DURATION (buf);
588   }
589
590   if (demux->priv->collect == NULL) {
591     demux->priv->collect = buf;
592   } else {
593     demux->priv->collect = gst_buffer_join (demux->priv->collect, buf);
594   }
595   buf = NULL;
596
597   switch (demux->priv->state) {
598     case GST_TAG_DEMUX_READ_START_TAG:
599       demux->priv->collect =
600           gst_buffer_make_metadata_writable (demux->priv->collect);
601       gst_tag_demux_chain_parse_tag (demux, demux->priv->collect);
602       if (demux->priv->state != GST_TAG_DEMUX_TYPEFINDING)
603         break;
604       /* Fall-through */
605     case GST_TAG_DEMUX_TYPEFINDING:{
606       GstTypeFindProbability probability = 0;
607       GstBuffer *typefind_buf = NULL;
608       GstCaps *caps;
609
610       if (GST_BUFFER_SIZE (demux->priv->collect) <
611           TYPE_FIND_MIN_SIZE + demux->priv->strip_start)
612         break;                  /* Go get more data first */
613
614       GST_DEBUG_OBJECT (demux, "Typefinding with size %d",
615           GST_BUFFER_SIZE (demux->priv->collect));
616
617       /* Trim the buffer and adjust offset for typefinding */
618       typefind_buf = demux->priv->collect;
619       gst_buffer_ref (typefind_buf);
620       if (!gst_tag_demux_trim_buffer (demux, &typefind_buf))
621         return GST_FLOW_UNEXPECTED;
622
623       if (typefind_buf == NULL)
624         break;                  /* Still need more data */
625
626       caps = gst_type_find_helper_for_buffer (GST_OBJECT (demux),
627           typefind_buf, &probability);
628
629       if (caps == NULL) {
630         if (GST_BUFFER_SIZE (typefind_buf) < TYPE_FIND_MAX_SIZE) {
631           /* Just break for more data */
632           gst_buffer_unref (typefind_buf);
633           return GST_FLOW_OK;
634         }
635
636         /* We failed typefind */
637         GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL),
638             ("Could not detect type for contents within tag"));
639         gst_buffer_unref (typefind_buf);
640         gst_buffer_unref (demux->priv->collect);
641         demux->priv->collect = NULL;
642         return GST_FLOW_ERROR;
643       }
644       gst_buffer_unref (typefind_buf);
645
646       GST_DEBUG_OBJECT (demux, "Found type %" GST_PTR_FORMAT " with a "
647           "probability of %u", caps, probability);
648
649       if (!gst_tag_demux_add_srcpad (demux, caps)) {
650         GST_DEBUG_OBJECT (demux, "Failed to add srcpad");
651         gst_caps_unref (caps);
652         goto error;
653       }
654       gst_caps_unref (caps);
655
656       /* Move onto streaming and fall-through to push out existing
657        * data */
658       demux->priv->state = GST_TAG_DEMUX_STREAMING;
659       /* fall-through */
660     }
661     case GST_TAG_DEMUX_STREAMING:{
662       GstBuffer *outbuf = NULL;
663
664       /* Trim the buffer and adjust offset */
665       if (demux->priv->collect) {
666         outbuf = demux->priv->collect;
667         demux->priv->collect = NULL;
668         if (!gst_tag_demux_trim_buffer (demux, &outbuf))
669           return GST_FLOW_UNEXPECTED;
670       }
671       if (outbuf) {
672         if (G_UNLIKELY (demux->priv->srcpad == NULL)) {
673           gst_buffer_unref (outbuf);
674           return GST_FLOW_ERROR;
675         }
676
677         /* Might need a new segment before the buffer */
678         if (demux->priv->need_newseg) {
679           if (!gst_tag_demux_send_new_segment (demux)) {
680             GST_WARNING_OBJECT (demux, "Downstream did not handle newsegment "
681                 "event as it should");
682           }
683           demux->priv->need_newseg = FALSE;
684         }
685
686         /* send any pending events we cached */
687         gst_tag_demux_send_pending_events (demux);
688
689         /* Send our own pending tag event */
690         if (demux->priv->send_tag_event) {
691           gst_tag_demux_send_tag_event (demux);
692           demux->priv->send_tag_event = FALSE;
693         }
694
695         /* Ensure the caps are set correctly */
696         outbuf = gst_buffer_make_metadata_writable (outbuf);
697         gst_buffer_set_caps (outbuf, GST_PAD_CAPS (demux->priv->srcpad));
698
699         GST_LOG_OBJECT (demux, "Pushing buffer %p", outbuf);
700
701         return gst_pad_push (demux->priv->srcpad, outbuf);
702       }
703     }
704   }
705   return GST_FLOW_OK;
706
707 error:
708   GST_DEBUG_OBJECT (demux, "error in chain function");
709
710   return GST_FLOW_ERROR;
711 }
712
713 static gboolean
714 gst_tag_demux_sink_event (GstPad * pad, GstEvent * event)
715 {
716   GstTagDemux *demux;
717   gboolean ret;
718
719   demux = GST_TAG_DEMUX (gst_pad_get_parent (pad));
720
721   switch (GST_EVENT_TYPE (event)) {
722     case GST_EVENT_EOS:
723       if (demux->priv->srcpad == NULL) {
724         GST_WARNING_OBJECT (demux, "EOS before we found a type");
725         GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
726       }
727       ret = gst_pad_event_default (pad, event);
728       break;
729     case GST_EVENT_NEWSEGMENT:{
730       gboolean update;
731       gdouble rate, arate;
732       GstFormat format;
733       gint64 start, stop, position;
734
735       gst_event_parse_new_segment_full (event, &update, &rate, &arate,
736           &format, &start, &stop, &position);
737
738       gst_segment_set_newsegment_full (&demux->priv->segment, update, rate,
739           arate, format, start, stop, position);
740       demux->priv->newseg_update = update;
741       demux->priv->need_newseg = TRUE;
742       gst_event_unref (event);
743       ret = TRUE;
744       break;
745     }
746     case GST_EVENT_FLUSH_STOP:
747     case GST_EVENT_FLUSH_START:
748       ret = gst_pad_event_default (pad, event);
749       break;
750     default:
751       if (demux->priv->need_newseg && GST_EVENT_IS_SERIALIZED (event)) {
752         /* Cache all events if we have a pending segment, so they don't get
753          * lost (esp. tag events) */
754         GST_INFO_OBJECT (demux, "caching event: %" GST_PTR_FORMAT, event);
755         GST_OBJECT_LOCK (demux);
756         demux->priv->pending_events =
757             g_list_append (demux->priv->pending_events, event);
758         GST_OBJECT_UNLOCK (demux);
759         ret = TRUE;
760       } else {
761         ret = gst_pad_event_default (pad, event);
762       }
763       break;
764   }
765
766   gst_object_unref (demux);
767   return ret;
768 }
769
770 static gboolean
771 gst_tag_demux_get_upstream_size (GstTagDemux * tagdemux)
772 {
773   GstFormat format;
774   gint64 len;
775
776   /* Short-cut if we already queried upstream */
777   if (tagdemux->priv->upstream_size > 0)
778     return TRUE;
779
780   format = GST_FORMAT_BYTES;
781   if (!gst_pad_query_peer_duration (tagdemux->priv->sinkpad, &format, &len) ||
782       len <= 0) {
783     return FALSE;
784   }
785
786   tagdemux->priv->upstream_size = len;
787   return TRUE;
788 }
789
790 static gboolean
791 gst_tag_demux_srcpad_event (GstPad * pad, GstEvent * event)
792 {
793   GstTagDemux *tagdemux;
794   gboolean res = FALSE;
795
796   tagdemux = GST_TAG_DEMUX (gst_pad_get_parent (pad));
797
798   /* Handle SEEK events, with adjusted byte offsets and sizes. */
799
800   switch (GST_EVENT_TYPE (event)) {
801     case GST_EVENT_SEEK:
802     {
803       gdouble rate;
804       GstFormat format;
805       GstSeekType cur_type, stop_type;
806       GstSeekFlags flags;
807       gint64 cur, stop;
808
809       gst_event_parse_seek (event, &rate, &format, &flags,
810           &cur_type, &cur, &stop_type, &stop);
811
812       if (format == GST_FORMAT_BYTES &&
813           tagdemux->priv->state == GST_TAG_DEMUX_STREAMING &&
814           gst_pad_is_linked (tagdemux->priv->sinkpad)) {
815         GstEvent *upstream;
816
817         switch (cur_type) {
818           case GST_SEEK_TYPE_SET:
819             if (cur == -1)
820               cur = 0;
821             cur += tagdemux->priv->strip_start;
822             break;
823           case GST_SEEK_TYPE_CUR:
824             break;
825           case GST_SEEK_TYPE_END:
826             /* Adjust the seek to be relative to the start of any end tag
827              * (note: 10 bytes before end is represented by stop=-10) */
828             if (cur > 0)
829               cur = 0;
830             cur -= tagdemux->priv->strip_end;
831             break;
832           case GST_SEEK_TYPE_NONE:
833           default:
834             break;
835         }
836         switch (stop_type) {
837           case GST_SEEK_TYPE_SET:
838             if (stop != -1) {
839               /* -1 means the end of the file, pass it upstream intact */
840               stop += tagdemux->priv->strip_start;
841             }
842             break;
843           case GST_SEEK_TYPE_CUR:
844             break;
845           case GST_SEEK_TYPE_END:
846             /* Adjust the seek to be relative to the start of any end tag
847              * (note: 10 bytes before end is represented by stop=-10) */
848             if (stop > 0)
849               stop = 0;
850             stop -= tagdemux->priv->strip_end;
851             break;
852           case GST_SEEK_TYPE_NONE:
853           default:
854             break;
855         }
856         upstream = gst_event_new_seek (rate, format, flags,
857             cur_type, cur, stop_type, stop);
858         res = gst_pad_push_event (tagdemux->priv->sinkpad, upstream);
859       }
860       break;
861     }
862     default:
863       res = gst_pad_push_event (tagdemux->priv->sinkpad, event);
864       event = NULL;
865       break;
866   }
867
868   gst_object_unref (tagdemux);
869   if (event)
870     gst_event_unref (event);
871   return res;
872 }
873
874 /* Read and interpret any end tag when activating in pull_range.
875  * Returns FALSE if pad activation should fail. */
876 static gboolean
877 gst_tag_demux_pull_end_tag (GstTagDemux * demux, GstTagList ** tags)
878 {
879   GstTagDemuxResult parse_ret;
880   GstTagDemuxClass *klass;
881   GstFlowReturn flow_ret;
882   GstTagList *new_tags = NULL;
883   GstBuffer *buffer = NULL;
884   gboolean have_tag;
885   gboolean res = FALSE;
886   guint64 offset;
887   guint tagsize;
888
889   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
890
891   g_assert (klass->identify_tag != NULL);
892   g_assert (klass->parse_tag != NULL);
893
894   if (klass->min_end_size == 0) {
895     GST_DEBUG_OBJECT (demux, "Not looking for tag at the end");
896     return TRUE;
897   }
898
899   if (demux->priv->upstream_size < klass->min_end_size) {
900     GST_DEBUG_OBJECT (demux, "File too small");
901     return TRUE;
902   }
903
904   /* Pull enough to identify the tag and retrieve its total size */
905   offset = demux->priv->upstream_size - klass->min_end_size;
906
907   flow_ret = gst_pad_pull_range (demux->priv->sinkpad, offset,
908       klass->min_end_size, &buffer);
909
910   if (flow_ret != GST_FLOW_OK) {
911     GST_DEBUG_OBJECT (demux, "Could not read tag header from end of file, "
912         "ret = %s", gst_flow_get_name (flow_ret));
913     goto done;
914   }
915
916   if (GST_BUFFER_SIZE (buffer) < klass->min_end_size) {
917     GST_DEBUG_OBJECT (demux, "Only managed to read %u bytes from file "
918         "(required: %u bytes)", GST_BUFFER_SIZE (buffer), klass->min_end_size);
919     goto done;
920   }
921
922   have_tag = klass->identify_tag (demux, buffer, FALSE, &tagsize);
923
924   if (!have_tag) {
925     GST_DEBUG_OBJECT (demux, "Could not find tag at end");
926     goto done;
927   }
928
929   /* Now pull the entire tag */
930   do {
931     guint newsize, saved_size;
932
933     GST_DEBUG_OBJECT (demux, "Identified tag at end, size=%u bytes", tagsize);
934
935     demux->priv->strip_end = tagsize;
936
937     g_assert (tagsize >= klass->min_end_size);
938
939     /* Get buffer that's exactly the requested size */
940     if (GST_BUFFER_SIZE (buffer) != tagsize) {
941       gst_buffer_unref (buffer);
942       buffer = NULL;
943
944       offset = demux->priv->upstream_size - tagsize;
945
946       flow_ret = gst_pad_pull_range (demux->priv->sinkpad, offset,
947           tagsize, &buffer);
948
949       if (flow_ret != GST_FLOW_OK) {
950         GST_DEBUG_OBJECT (demux, "Could not read data from end of file at "
951             "offset %" G_GUINT64_FORMAT ". ret = %s", offset,
952             gst_flow_get_name (flow_ret));
953         goto done;
954       }
955
956       if (GST_BUFFER_SIZE (buffer) < tagsize) {
957         GST_DEBUG_OBJECT (demux, "Only managed to read %u bytes from file",
958             GST_BUFFER_SIZE (buffer));
959         goto done;
960       }
961     }
962
963     GST_BUFFER_OFFSET (buffer) = offset;
964
965     saved_size = GST_BUFFER_SIZE (buffer);
966     GST_BUFFER_SIZE (buffer) = tagsize;
967     newsize = tagsize;
968
969     parse_ret = klass->parse_tag (demux, buffer, FALSE, &newsize, &new_tags);
970
971     GST_BUFFER_SIZE (buffer) = saved_size;
972
973     switch (parse_ret) {
974       case GST_TAG_DEMUX_RESULT_OK:
975         res = TRUE;
976         demux->priv->strip_end = newsize;
977         GST_DEBUG_OBJECT (demux, "Read tag at end, size %d",
978             demux->priv->strip_end);
979         break;
980       case GST_TAG_DEMUX_RESULT_BROKEN_TAG:
981         res = TRUE;
982         demux->priv->strip_end = newsize;
983         GST_WARNING_OBJECT (demux, "Ignoring broken tag at end, size %d",
984             demux->priv->strip_end);
985         break;
986       case GST_TAG_DEMUX_RESULT_AGAIN:
987         GST_DEBUG_OBJECT (demux, "Re-parse, this time with %d bytes", newsize);
988         g_assert (newsize != tagsize);
989         tagsize = newsize;
990         break;
991     }
992   } while (parse_ret == GST_TAG_DEMUX_RESULT_AGAIN);
993
994   *tags = new_tags;
995   new_tags = NULL;
996
997 done:
998   if (new_tags)
999     gst_tag_list_free (new_tags);
1000   if (buffer)
1001     gst_buffer_unref (buffer);
1002   return res;
1003 }
1004
1005 /* Read and interpret any tag at the start when activating in
1006  * pull_range. Returns FALSE if pad activation should fail. */
1007 static gboolean
1008 gst_tag_demux_pull_start_tag (GstTagDemux * demux, GstTagList ** tags)
1009 {
1010   GstTagDemuxResult parse_ret;
1011   GstTagDemuxClass *klass;
1012   GstFlowReturn flow_ret;
1013   GstTagList *new_tags = NULL;
1014   GstBuffer *buffer = NULL;
1015   gboolean have_tag;
1016   gboolean res = FALSE;
1017   guint req, tagsize;
1018
1019   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
1020
1021   g_assert (klass->identify_tag != NULL);
1022   g_assert (klass->parse_tag != NULL);
1023
1024   if (klass->min_start_size == 0) {
1025     GST_DEBUG_OBJECT (demux, "Not looking for tag at the beginning");
1026     return TRUE;
1027   }
1028
1029   /* Handle tag at start. Try with 4kB to start with */
1030   req = MAX (klass->min_start_size, 4096);
1031
1032   /* Pull enough to identify the tag and retrieve its total size */
1033   flow_ret = gst_pad_pull_range (demux->priv->sinkpad, 0, req, &buffer);
1034   if (flow_ret != GST_FLOW_OK) {
1035     GST_DEBUG_OBJECT (demux, "Could not read data from start of file ret=%s",
1036         gst_flow_get_name (flow_ret));
1037     goto done;
1038   }
1039
1040   if (GST_BUFFER_SIZE (buffer) < klass->min_start_size) {
1041     GST_DEBUG_OBJECT (demux, "Only managed to read %u bytes from file - "
1042         "no tag in this file", GST_BUFFER_SIZE (buffer));
1043     goto done;
1044   }
1045
1046   have_tag = klass->identify_tag (demux, buffer, TRUE, &tagsize);
1047
1048   if (!have_tag) {
1049     GST_DEBUG_OBJECT (demux, "Could not find start tag");
1050     res = TRUE;
1051     goto done;
1052   }
1053
1054   GST_DEBUG_OBJECT (demux, "Identified start tag, size = %u bytes", tagsize);
1055
1056   do {
1057     guint newsize, saved_size;
1058
1059     demux->priv->strip_start = tagsize;
1060
1061     /* Now pull the entire tag */
1062     g_assert (tagsize >= klass->min_start_size);
1063
1064     if (GST_BUFFER_SIZE (buffer) < tagsize) {
1065       gst_buffer_unref (buffer);
1066       buffer = NULL;
1067
1068       flow_ret = gst_pad_pull_range (demux->priv->sinkpad, 0, tagsize, &buffer);
1069       if (flow_ret != GST_FLOW_OK) {
1070         GST_DEBUG_OBJECT (demux, "Could not read data from start of file, "
1071             "ret = %s", gst_flow_get_name (flow_ret));
1072         goto done;
1073       }
1074
1075       if (GST_BUFFER_SIZE (buffer) < tagsize) {
1076         GST_DEBUG_OBJECT (demux, "Only managed to read %u bytes from file",
1077             GST_BUFFER_SIZE (buffer));
1078         GST_ELEMENT_ERROR (demux, STREAM, DECODE,
1079             (_("Failed to read tag: not enough data")), (NULL));
1080         goto done;
1081       }
1082     }
1083
1084     saved_size = GST_BUFFER_SIZE (buffer);
1085     GST_BUFFER_SIZE (buffer) = tagsize;
1086     newsize = tagsize;
1087     parse_ret = klass->parse_tag (demux, buffer, TRUE, &newsize, &new_tags);
1088
1089     GST_BUFFER_SIZE (buffer) = saved_size;
1090
1091     switch (parse_ret) {
1092       case GST_TAG_DEMUX_RESULT_OK:
1093         res = TRUE;
1094         demux->priv->strip_start = newsize;
1095         GST_DEBUG_OBJECT (demux, "Read start tag of size %d", newsize);
1096         break;
1097       case GST_TAG_DEMUX_RESULT_BROKEN_TAG:
1098         res = TRUE;
1099         demux->priv->strip_start = newsize;
1100         GST_WARNING_OBJECT (demux, "Ignoring broken start tag of size %d",
1101             demux->priv->strip_start);
1102         break;
1103       case GST_TAG_DEMUX_RESULT_AGAIN:
1104         GST_DEBUG_OBJECT (demux, "Re-parse, this time with %d bytes", newsize);
1105         g_assert (newsize != tagsize);
1106         tagsize = newsize;
1107         break;
1108     }
1109   } while (parse_ret == GST_TAG_DEMUX_RESULT_AGAIN);
1110
1111   *tags = new_tags;
1112   new_tags = NULL;
1113
1114 done:
1115   if (new_tags)
1116     gst_tag_list_free (new_tags);
1117   if (buffer)
1118     gst_buffer_unref (buffer);
1119   return res;
1120 }
1121
1122 /* This function operates similarly to gst_type_find_element_activate
1123  * in the typefind element
1124  * 1. try to activate in pull mode. if not, switch to push and succeed.
1125  * 2. try to read tags in pull mode
1126  * 3. typefind the contents
1127  * 4. deactivate pull mode.
1128  * 5. if we didn't find any caps, fail.
1129  * 6. Add the srcpad
1130  * 7. if the sink pad is activated, we are in pull mode. succeed.
1131  *    otherwise activate both pads in push mode and succeed.
1132  */
1133 static gboolean
1134 gst_tag_demux_sink_activate (GstPad * sinkpad)
1135 {
1136   GstTypeFindProbability probability = 0;
1137   GstTagDemuxClass *klass;
1138   GstTagDemux *demux;
1139   GstTagList *start_tags = NULL;
1140   GstTagList *end_tags = NULL;
1141   gboolean e_tag_ok, s_tag_ok;
1142   gboolean ret = FALSE;
1143   GstCaps *caps = NULL;
1144
1145   demux = GST_TAG_DEMUX (GST_PAD_PARENT (sinkpad));
1146   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
1147
1148   /* 1: */
1149   /* If we can activate pull_range upstream, then read any end and start
1150    * tags, otherwise activate in push mode and the chain function will 
1151    * collect buffers, read the start tag and output a buffer to end
1152    * preroll.
1153    */
1154   if (!gst_pad_check_pull_range (sinkpad) ||
1155       !gst_pad_activate_pull (sinkpad, TRUE)) {
1156     GST_DEBUG_OBJECT (demux, "No pull mode. Changing to push, but won't be "
1157         "able to read end tags");
1158     demux->priv->state = GST_TAG_DEMUX_READ_START_TAG;
1159     return gst_pad_activate_push (sinkpad, TRUE);
1160   }
1161
1162   /* Look for tags at start and end of file */
1163   GST_DEBUG_OBJECT (demux, "Activated pull mode. Looking for tags");
1164   if (!gst_tag_demux_get_upstream_size (demux))
1165     return FALSE;
1166
1167   demux->priv->strip_start = 0;
1168   demux->priv->strip_end = 0;
1169
1170   s_tag_ok = gst_tag_demux_pull_start_tag (demux, &start_tags);
1171   e_tag_ok = gst_tag_demux_pull_end_tag (demux, &end_tags);
1172
1173   if (klass->merge_tags != NULL) {
1174     demux->priv->parsed_tags = klass->merge_tags (demux, start_tags, end_tags);
1175   } else {
1176     /* we merge in REPLACE mode, so put the less important tags first, which
1177      * we'll just assume is the end tag (subclasses may change this behaviour
1178      * or make it configurable by overriding the merge_tags vfunc) */
1179     demux->priv->parsed_tags =
1180         gst_tag_list_merge (end_tags, start_tags, GST_TAG_MERGE_REPLACE);
1181   }
1182
1183   if (start_tags)
1184     gst_tag_list_free (start_tags);
1185   if (end_tags)
1186     gst_tag_list_free (end_tags);
1187
1188   if (!e_tag_ok && !s_tag_ok)
1189     return FALSE;
1190
1191   if (demux->priv->parsed_tags != NULL) {
1192     demux->priv->send_tag_event = TRUE;
1193   }
1194
1195   if (demux->priv->upstream_size <=
1196       demux->priv->strip_start + demux->priv->strip_end) {
1197     /* There was no data (probably due to a truncated file) */
1198     GST_DEBUG_OBJECT (demux, "No data in file");
1199     return FALSE;
1200   }
1201
1202   /* 3 - Do typefinding on data */
1203   caps = gst_type_find_helper_get_range (GST_OBJECT (demux),
1204       (GstTypeFindHelperGetRangeFunction) gst_tag_demux_read_range,
1205       demux->priv->upstream_size
1206       - (demux->priv->strip_start + demux->priv->strip_end), &probability);
1207
1208   GST_DEBUG_OBJECT (demux, "Found type %" GST_PTR_FORMAT " with a "
1209       "probability of %u", caps, probability);
1210
1211   /* 4 - Deactivate pull mode */
1212   if (!gst_pad_activate_pull (sinkpad, FALSE)) {
1213     if (caps)
1214       gst_caps_unref (caps);
1215     GST_DEBUG_OBJECT (demux, "Could not deactivate sinkpad after reading tags");
1216     return FALSE;
1217   }
1218
1219   /* 5 - If we didn't find the caps, fail */
1220   if (caps == NULL) {
1221     GST_DEBUG_OBJECT (demux, "Could not detect type of contents");
1222     GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
1223     goto done_activate;
1224   }
1225
1226   /* tag reading and typefinding were already done, don't do them again in
1227    * the chain function if we end up in push mode */
1228   demux->priv->state = GST_TAG_DEMUX_STREAMING;
1229
1230   /* 6 Add the srcpad for output now we know caps. */
1231   if (!gst_tag_demux_add_srcpad (demux, caps)) {
1232     GST_DEBUG_OBJECT (demux, "Could not add source pad");
1233     goto done_activate;
1234   }
1235
1236   /* 7 - if the sinkpad is active, it was done by downstream so we're 
1237    * done, otherwise switch to push */
1238   ret = TRUE;
1239   if (!gst_pad_is_active (sinkpad)) {
1240     ret = gst_pad_activate_push (demux->priv->srcpad, TRUE);
1241     ret &= gst_pad_activate_push (sinkpad, TRUE);
1242   }
1243
1244 done_activate:
1245
1246   if (caps)
1247     gst_caps_unref (caps);
1248
1249   return ret;
1250 }
1251
1252 static gboolean
1253 gst_tag_demux_src_activate_pull (GstPad * pad, gboolean active)
1254 {
1255   GstTagDemux *demux = GST_TAG_DEMUX (GST_PAD_PARENT (pad));
1256
1257   return gst_pad_activate_pull (demux->priv->sinkpad, active);
1258 }
1259
1260 static gboolean
1261 gst_tag_demux_src_checkgetrange (GstPad * srcpad)
1262 {
1263   GstTagDemux *demux = GST_TAG_DEMUX (GST_PAD_PARENT (srcpad));
1264
1265   return gst_pad_check_pull_range (demux->priv->sinkpad);
1266 }
1267
1268 static GstFlowReturn
1269 gst_tag_demux_read_range (GstTagDemux * demux,
1270     guint64 offset, guint length, GstBuffer ** buffer)
1271 {
1272   GstFlowReturn ret;
1273   guint64 in_offset;
1274   guint in_length;
1275
1276   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1277
1278   /* Adjust offset and length of the request to trim off tag information. 
1279    * For the returned buffer, adjust the output offset to match what downstream
1280    * should see */
1281   in_offset = offset + demux->priv->strip_start;
1282
1283   if (!gst_tag_demux_get_upstream_size (demux))
1284     return GST_FLOW_ERROR;
1285
1286   if (in_offset + length >= demux->priv->upstream_size - demux->priv->strip_end) {
1287     if (in_offset + demux->priv->strip_end >= demux->priv->upstream_size)
1288       return GST_FLOW_UNEXPECTED;
1289     in_length = demux->priv->upstream_size - demux->priv->strip_end - in_offset;
1290   } else {
1291     in_length = length;
1292   }
1293
1294   ret = gst_pad_pull_range (demux->priv->sinkpad, in_offset, in_length, buffer);
1295
1296   if (ret == GST_FLOW_OK && *buffer) {
1297     if (!gst_tag_demux_trim_buffer (demux, buffer))
1298       goto read_beyond_end;
1299
1300     /* this should only happen in streaming mode */
1301     g_assert (*buffer != NULL);
1302
1303     gst_buffer_set_caps (*buffer, demux->priv->src_caps);
1304   }
1305
1306   return ret;
1307
1308 read_beyond_end:
1309   {
1310     GST_DEBUG_OBJECT (demux, "attempted read beyond end of file");
1311     if (*buffer != NULL) {
1312       gst_buffer_unref (*buffer);
1313       *buffer = NULL;
1314     }
1315     return GST_FLOW_UNEXPECTED;
1316   }
1317 }
1318
1319 static GstFlowReturn
1320 gst_tag_demux_src_getrange (GstPad * srcpad,
1321     guint64 offset, guint length, GstBuffer ** buffer)
1322 {
1323   GstTagDemux *demux = GST_TAG_DEMUX (GST_PAD_PARENT (srcpad));
1324
1325   /* downstream in pull mode won't miss a newsegment event,
1326    * but it likely appreciates other (tag) events */
1327   if (demux->priv->need_newseg) {
1328     gst_tag_demux_send_pending_events (demux);
1329     demux->priv->need_newseg = FALSE;
1330   }
1331
1332   if (demux->priv->send_tag_event) {
1333     gst_tag_demux_send_tag_event (demux);
1334     demux->priv->send_tag_event = FALSE;
1335   }
1336
1337   return gst_tag_demux_read_range (demux, offset, length, buffer);
1338 }
1339
1340 static GstStateChangeReturn
1341 gst_tag_demux_change_state (GstElement * element, GstStateChange transition)
1342 {
1343   GstStateChangeReturn ret;
1344   GstTagDemux *demux = GST_TAG_DEMUX (element);
1345
1346   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1347
1348   switch (transition) {
1349     case GST_STATE_CHANGE_PAUSED_TO_READY:
1350       gst_tag_demux_reset (demux);
1351       break;
1352     default:
1353       break;
1354   }
1355   return ret;
1356 }
1357
1358 static gboolean
1359 gst_tag_demux_pad_query (GstPad * pad, GstQuery * query)
1360 {
1361   /* For a position or duration query, adjust the returned
1362    * bytes to strip off the end and start areas */
1363
1364   GstTagDemux *demux = GST_TAG_DEMUX (GST_PAD_PARENT (pad));
1365   GstPad *peer = NULL;
1366   GstFormat format;
1367   gint64 result;
1368
1369   if ((peer = gst_pad_get_peer (demux->priv->sinkpad)) == NULL)
1370     return FALSE;
1371
1372   if (!gst_pad_query (peer, query)) {
1373     gst_object_unref (peer);
1374     return FALSE;
1375   }
1376
1377   gst_object_unref (peer);
1378
1379   switch (GST_QUERY_TYPE (query)) {
1380     case GST_QUERY_POSITION:
1381     {
1382       gst_query_parse_position (query, &format, &result);
1383       if (format == GST_FORMAT_BYTES) {
1384         result -= demux->priv->strip_start;
1385         gst_query_set_position (query, format, result);
1386       }
1387       break;
1388     }
1389     case GST_QUERY_DURATION:
1390     {
1391       gst_query_parse_duration (query, &format, &result);
1392       if (format == GST_FORMAT_BYTES) {
1393         result -= demux->priv->strip_start + demux->priv->strip_end;
1394         gst_query_set_duration (query, format, result);
1395       }
1396       break;
1397     }
1398     default:
1399       break;
1400   }
1401
1402   return TRUE;
1403 }
1404
1405 static const GstQueryType *
1406 gst_tag_demux_get_query_types (GstPad * pad)
1407 {
1408   static const GstQueryType types[] = {
1409     GST_QUERY_POSITION,
1410     GST_QUERY_DURATION,
1411     0
1412   };
1413
1414   return types;
1415 }
1416
1417 static void
1418 gst_tag_demux_send_pending_events (GstTagDemux * demux)
1419 {
1420   GList *events;
1421
1422   /* send any pending events we cached */
1423   GST_OBJECT_LOCK (demux);
1424   events = demux->priv->pending_events;
1425   demux->priv->pending_events = NULL;
1426   GST_OBJECT_UNLOCK (demux);
1427
1428   while (events != NULL) {
1429     GST_DEBUG_OBJECT (demux->priv->srcpad, "sending cached %s event: %"
1430         GST_PTR_FORMAT, GST_EVENT_TYPE_NAME (events->data), events->data);
1431     gst_pad_push_event (demux->priv->srcpad, GST_EVENT (events->data));
1432     events = g_list_delete_link (events, events);
1433   }
1434 }
1435
1436 static void
1437 gst_tag_demux_send_tag_event (GstTagDemux * demux)
1438 {
1439   /* FIXME: what's the correct merge mode? Docs need to tell... */
1440   GstTagList *merged = gst_tag_list_merge (demux->priv->event_tags,
1441       demux->priv->parsed_tags, GST_TAG_MERGE_KEEP);
1442
1443   if (demux->priv->parsed_tags)
1444     gst_element_post_message (GST_ELEMENT (demux),
1445         gst_message_new_tag (GST_OBJECT (demux),
1446             gst_tag_list_copy (demux->priv->parsed_tags)));
1447
1448   if (merged) {
1449     GstEvent *event = gst_event_new_tag (merged);
1450
1451     GST_EVENT_TIMESTAMP (event) = 0;
1452     GST_DEBUG_OBJECT (demux, "Sending tag event on src pad");
1453     gst_pad_push_event (demux->priv->srcpad, event);
1454   }
1455 }
1456
1457 static gboolean
1458 gst_tag_demux_send_new_segment (GstTagDemux * tagdemux)
1459 {
1460   GstEvent *event;
1461   gint64 start, stop, position;
1462   GstSegment *seg = &tagdemux->priv->segment;
1463
1464   if (seg->format == GST_FORMAT_UNDEFINED) {
1465     GST_LOG_OBJECT (tagdemux,
1466         "No new segment received before first buffer. Using default");
1467     gst_segment_set_newsegment (seg, FALSE, 1.0,
1468         GST_FORMAT_BYTES, tagdemux->priv->strip_start, -1,
1469         tagdemux->priv->strip_start);
1470   }
1471
1472   /* Can't adjust segments in non-BYTES formats */
1473   if (tagdemux->priv->segment.format != GST_FORMAT_BYTES) {
1474     event = gst_event_new_new_segment_full (tagdemux->priv->newseg_update,
1475         seg->rate, seg->applied_rate, seg->format, seg->start,
1476         seg->stop, seg->time);
1477     return gst_pad_push_event (tagdemux->priv->srcpad, event);
1478   }
1479
1480   start = seg->start;
1481   stop = seg->stop;
1482   position = seg->time;
1483
1484   g_return_val_if_fail (start != -1, FALSE);
1485   g_return_val_if_fail (position != -1, FALSE);
1486
1487   if (tagdemux->priv->strip_end > 0) {
1488     if (gst_tag_demux_get_upstream_size (tagdemux)) {
1489       guint64 v1tag_offset =
1490           tagdemux->priv->upstream_size - tagdemux->priv->strip_end;
1491
1492       if (start >= v1tag_offset) {
1493         /* Segment is completely within the end tag, output an open-ended
1494          * segment, even though all the buffers will get trimmed away */
1495         start = v1tag_offset;
1496         stop = -1;
1497       }
1498
1499       if (stop != -1 && stop >= v1tag_offset) {
1500         GST_DEBUG_OBJECT (tagdemux,
1501             "Segment crosses the end tag. Trimming end");
1502         stop = v1tag_offset;
1503       }
1504     }
1505   }
1506
1507   if (tagdemux->priv->strip_start > 0) {
1508     if (start > tagdemux->priv->strip_start)
1509       start -= tagdemux->priv->strip_start;
1510     else
1511       start = 0;
1512
1513     if (position > tagdemux->priv->strip_start)
1514       position -= tagdemux->priv->strip_start;
1515     else
1516       position = 0;
1517
1518     if (stop != -1) {
1519       if (stop > tagdemux->priv->strip_start)
1520         stop -= tagdemux->priv->strip_start;
1521       else
1522         stop = 0;
1523     }
1524   }
1525
1526   GST_DEBUG_OBJECT (tagdemux,
1527       "Sending new segment update %d, rate %g, format %d, "
1528       "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT ", position %"
1529       G_GINT64_FORMAT, tagdemux->priv->newseg_update, seg->rate, seg->format,
1530       start, stop, position);
1531
1532   event = gst_event_new_new_segment_full (tagdemux->priv->newseg_update,
1533       seg->rate, seg->applied_rate, seg->format, start, stop, position);
1534   return gst_pad_push_event (tagdemux->priv->srcpad, event);
1535 }