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