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