update for activation changes
[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         if (G_UNLIKELY (demux->priv->srcpad == NULL)) {
650           gst_buffer_unref (outbuf);
651           return GST_FLOW_ERROR;
652         }
653
654         /* Might need a new segment before the buffer */
655         if (demux->priv->need_newseg) {
656           if (!gst_tag_demux_send_new_segment (demux)) {
657             GST_WARNING_OBJECT (demux, "Downstream did not handle newsegment "
658                 "event as it should");
659           }
660           demux->priv->need_newseg = FALSE;
661         }
662
663         /* send any pending events we cached */
664         gst_tag_demux_send_pending_events (demux);
665
666         /* Send our own pending tag event */
667         if (demux->priv->send_tag_event) {
668           gst_tag_demux_send_tag_event (demux);
669           demux->priv->send_tag_event = FALSE;
670         }
671
672         GST_LOG_OBJECT (demux, "Pushing buffer %p", outbuf);
673
674         return gst_pad_push (demux->priv->srcpad, outbuf);
675       }
676     }
677   }
678   return GST_FLOW_OK;
679 }
680
681 static gboolean
682 gst_tag_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
683 {
684   GstTagDemux *demux;
685   gboolean ret;
686
687   demux = GST_TAG_DEMUX (parent);
688
689   switch (GST_EVENT_TYPE (event)) {
690     case GST_EVENT_EOS:
691       if (demux->priv->srcpad == NULL) {
692         GST_WARNING_OBJECT (demux, "EOS before we found a type");
693         GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
694       }
695       ret = gst_pad_event_default (pad, parent, event);
696       break;
697     case GST_EVENT_SEGMENT:
698     {
699       gst_event_copy_segment (event, &demux->priv->segment);
700
701       demux->priv->need_newseg = TRUE;
702       gst_event_unref (event);
703       ret = TRUE;
704       break;
705     }
706     case GST_EVENT_FLUSH_STOP:
707     case GST_EVENT_FLUSH_START:
708       ret = gst_pad_event_default (pad, parent, event);
709       break;
710     default:
711       if (demux->priv->need_newseg && GST_EVENT_IS_SERIALIZED (event)) {
712         /* Cache all events if we have a pending segment, so they don't get
713          * lost (esp. tag events) */
714         GST_INFO_OBJECT (demux, "caching event: %" GST_PTR_FORMAT, event);
715         GST_OBJECT_LOCK (demux);
716         demux->priv->pending_events =
717             g_list_append (demux->priv->pending_events, event);
718         GST_OBJECT_UNLOCK (demux);
719         ret = TRUE;
720       } else {
721         ret = gst_pad_event_default (pad, parent, event);
722       }
723       break;
724   }
725
726   return ret;
727 }
728
729 static gboolean
730 gst_tag_demux_get_upstream_size (GstTagDemux * tagdemux)
731 {
732   gint64 len;
733
734   /* Short-cut if we already queried upstream */
735   if (tagdemux->priv->upstream_size > 0)
736     return TRUE;
737
738   if (!gst_pad_peer_query_duration (tagdemux->priv->sinkpad, GST_FORMAT_BYTES,
739           &len) || len <= 0) {
740     return FALSE;
741   }
742
743   tagdemux->priv->upstream_size = len;
744   return TRUE;
745 }
746
747 static gboolean
748 gst_tag_demux_srcpad_event (GstPad * pad, GstObject * parent, GstEvent * event)
749 {
750   GstTagDemux *tagdemux;
751   gboolean res = FALSE;
752
753   tagdemux = GST_TAG_DEMUX (parent);
754
755   /* Handle SEEK events, with adjusted byte offsets and sizes. */
756
757   switch (GST_EVENT_TYPE (event)) {
758     case GST_EVENT_SEEK:
759     {
760       gdouble rate;
761       GstFormat format;
762       GstSeekType cur_type, stop_type;
763       GstSeekFlags flags;
764       gint64 cur, stop;
765
766       gst_event_parse_seek (event, &rate, &format, &flags,
767           &cur_type, &cur, &stop_type, &stop);
768
769       if (format == GST_FORMAT_BYTES &&
770           tagdemux->priv->state == GST_TAG_DEMUX_STREAMING &&
771           gst_pad_is_linked (tagdemux->priv->sinkpad)) {
772         GstEvent *upstream;
773
774         switch (cur_type) {
775           case GST_SEEK_TYPE_SET:
776             if (cur == -1)
777               cur = 0;
778             cur += tagdemux->priv->strip_start;
779             break;
780           case GST_SEEK_TYPE_END:
781             /* Adjust the seek to be relative to the start of any end tag
782              * (note: 10 bytes before end is represented by stop=-10) */
783             if (cur > 0)
784               cur = 0;
785             cur -= tagdemux->priv->strip_end;
786             break;
787           case GST_SEEK_TYPE_NONE:
788           default:
789             break;
790         }
791         switch (stop_type) {
792           case GST_SEEK_TYPE_SET:
793             if (stop != -1) {
794               /* -1 means the end of the file, pass it upstream intact */
795               stop += tagdemux->priv->strip_start;
796             }
797             break;
798           case GST_SEEK_TYPE_END:
799             /* Adjust the seek to be relative to the start of any end tag
800              * (note: 10 bytes before end is represented by stop=-10) */
801             if (stop > 0)
802               stop = 0;
803             stop -= tagdemux->priv->strip_end;
804             break;
805           case GST_SEEK_TYPE_NONE:
806           default:
807             break;
808         }
809         upstream = gst_event_new_seek (rate, format, flags,
810             cur_type, cur, stop_type, stop);
811         res = gst_pad_push_event (tagdemux->priv->sinkpad, upstream);
812       }
813       break;
814     }
815     default:
816       res = gst_pad_push_event (tagdemux->priv->sinkpad, event);
817       event = NULL;
818       break;
819   }
820
821   if (event)
822     gst_event_unref (event);
823
824   return res;
825 }
826
827 /* Read and interpret any end tag when activating in pull_range.
828  * Returns FALSE if pad activation should fail. */
829 static gboolean
830 gst_tag_demux_pull_end_tag (GstTagDemux * demux, GstTagList ** tags)
831 {
832   GstTagDemuxResult parse_ret;
833   GstTagDemuxClass *klass;
834   GstFlowReturn flow_ret;
835   GstTagList *new_tags = NULL;
836   GstBuffer *buffer = NULL;
837   gboolean have_tag;
838   gboolean res = FALSE;
839   guint64 offset;
840   guint tagsize;
841   gsize bsize;
842
843   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
844
845   g_assert (klass->identify_tag != NULL);
846   g_assert (klass->parse_tag != NULL);
847
848   if (klass->min_end_size == 0) {
849     GST_DEBUG_OBJECT (demux, "Not looking for tag at the end");
850     return TRUE;
851   }
852
853   if (demux->priv->upstream_size < klass->min_end_size) {
854     GST_DEBUG_OBJECT (demux, "File too small");
855     return TRUE;
856   }
857
858   /* Pull enough to identify the tag and retrieve its total size */
859   offset = demux->priv->upstream_size - klass->min_end_size;
860
861   flow_ret = gst_pad_pull_range (demux->priv->sinkpad, offset,
862       klass->min_end_size, &buffer);
863
864   if (flow_ret != GST_FLOW_OK) {
865     GST_DEBUG_OBJECT (demux, "Could not read tag header from end of file, "
866         "ret = %s", gst_flow_get_name (flow_ret));
867     goto done;
868   }
869
870   bsize = gst_buffer_get_size (buffer);
871
872   if (bsize < klass->min_end_size) {
873     GST_DEBUG_OBJECT (demux, "Only managed to read %" G_GSIZE_FORMAT " bytes"
874         "from file (required: %u bytes)", bsize, klass->min_end_size);
875     goto done;
876   }
877
878   have_tag = klass->identify_tag (demux, buffer, FALSE, &tagsize);
879
880   if (!have_tag) {
881     GST_DEBUG_OBJECT (demux, "Could not find tag at end");
882     goto done;
883   }
884
885   /* Now pull the entire tag */
886   do {
887     guint newsize, saved_size;
888
889     GST_DEBUG_OBJECT (demux, "Identified tag at end, size=%u bytes", tagsize);
890
891     demux->priv->strip_end = tagsize;
892
893     g_assert (tagsize >= klass->min_end_size);
894
895     /* Get buffer that's exactly the requested size */
896     if (bsize != tagsize) {
897       gst_buffer_unref (buffer);
898       buffer = NULL;
899
900       offset = demux->priv->upstream_size - tagsize;
901
902       flow_ret = gst_pad_pull_range (demux->priv->sinkpad, offset,
903           tagsize, &buffer);
904
905       if (flow_ret != GST_FLOW_OK) {
906         GST_DEBUG_OBJECT (demux, "Could not read data from end of file at "
907             "offset %" G_GUINT64_FORMAT ". ret = %s", offset,
908             gst_flow_get_name (flow_ret));
909         goto done;
910       }
911
912       bsize = gst_buffer_get_size (buffer);
913
914       if (bsize < tagsize) {
915         GST_DEBUG_OBJECT (demux, "Only managed to read %" G_GSIZE_FORMAT
916             " bytes from file", bsize);
917         goto done;
918       }
919     }
920
921     GST_BUFFER_OFFSET (buffer) = offset;
922
923     saved_size = bsize;
924     gst_buffer_set_size (buffer, tagsize);
925     newsize = tagsize;
926
927     parse_ret = klass->parse_tag (demux, buffer, FALSE, &newsize, &new_tags);
928
929     gst_buffer_set_size (buffer, saved_size);
930
931     switch (parse_ret) {
932       case GST_TAG_DEMUX_RESULT_OK:
933         res = TRUE;
934         demux->priv->strip_end = newsize;
935         GST_DEBUG_OBJECT (demux, "Read tag at end, size %d",
936             demux->priv->strip_end);
937         break;
938       case GST_TAG_DEMUX_RESULT_BROKEN_TAG:
939         res = TRUE;
940         demux->priv->strip_end = newsize;
941         GST_WARNING_OBJECT (demux, "Ignoring broken tag at end, size %d",
942             demux->priv->strip_end);
943         break;
944       case GST_TAG_DEMUX_RESULT_AGAIN:
945         GST_DEBUG_OBJECT (demux, "Re-parse, this time with %d bytes", newsize);
946         g_assert (newsize != tagsize);
947         tagsize = newsize;
948         break;
949     }
950   } while (parse_ret == GST_TAG_DEMUX_RESULT_AGAIN);
951
952   *tags = new_tags;
953   new_tags = NULL;
954
955 done:
956   if (new_tags)
957     gst_tag_list_free (new_tags);
958   if (buffer)
959     gst_buffer_unref (buffer);
960   return res;
961 }
962
963 /* Read and interpret any tag at the start when activating in
964  * pull_range. Returns FALSE if pad activation should fail. */
965 static gboolean
966 gst_tag_demux_pull_start_tag (GstTagDemux * demux, GstTagList ** tags)
967 {
968   GstTagDemuxResult parse_ret;
969   GstTagDemuxClass *klass;
970   GstFlowReturn flow_ret;
971   GstTagList *new_tags = NULL;
972   GstBuffer *buffer = NULL;
973   gboolean have_tag;
974   gboolean res = FALSE;
975   guint req, tagsize;
976   gsize bsize;
977
978   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
979
980   g_assert (klass->identify_tag != NULL);
981   g_assert (klass->parse_tag != NULL);
982
983   if (klass->min_start_size == 0) {
984     GST_DEBUG_OBJECT (demux, "Not looking for tag at the beginning");
985     return TRUE;
986   }
987
988   /* Handle tag at start. Try with 4kB to start with */
989   req = MAX (klass->min_start_size, 4096);
990
991   /* Pull enough to identify the tag and retrieve its total size */
992   flow_ret = gst_pad_pull_range (demux->priv->sinkpad, 0, req, &buffer);
993   if (flow_ret != GST_FLOW_OK) {
994     GST_DEBUG_OBJECT (demux, "Could not read data from start of file ret=%s",
995         gst_flow_get_name (flow_ret));
996     goto done;
997   }
998
999   bsize = gst_buffer_get_size (buffer);
1000
1001   if (bsize < klass->min_start_size) {
1002     GST_DEBUG_OBJECT (demux, "Only managed to read %" G_GSIZE_FORMAT
1003         " bytes from file - no tag in this file", bsize);
1004     goto done;
1005   }
1006
1007   have_tag = klass->identify_tag (demux, buffer, TRUE, &tagsize);
1008
1009   if (!have_tag) {
1010     GST_DEBUG_OBJECT (demux, "Could not find start tag");
1011     res = TRUE;
1012     goto done;
1013   }
1014
1015   GST_DEBUG_OBJECT (demux, "Identified start tag, size = %u bytes", tagsize);
1016
1017   do {
1018     guint newsize, saved_size;
1019
1020     demux->priv->strip_start = tagsize;
1021
1022     /* Now pull the entire tag */
1023     g_assert (tagsize >= klass->min_start_size);
1024
1025     if (bsize < tagsize) {
1026       gst_buffer_unref (buffer);
1027       buffer = NULL;
1028
1029       flow_ret = gst_pad_pull_range (demux->priv->sinkpad, 0, tagsize, &buffer);
1030       if (flow_ret != GST_FLOW_OK) {
1031         GST_DEBUG_OBJECT (demux, "Could not read data from start of file, "
1032             "ret = %s", gst_flow_get_name (flow_ret));
1033         goto done;
1034       }
1035
1036       bsize = gst_buffer_get_size (buffer);
1037
1038       if (bsize < tagsize) {
1039         GST_DEBUG_OBJECT (demux, "Only managed to read %" G_GSIZE_FORMAT
1040             " bytes from file", bsize);
1041         GST_ELEMENT_ERROR (demux, STREAM, DECODE,
1042             (_("Failed to read tag: not enough data")), (NULL));
1043         goto done;
1044       }
1045     }
1046
1047     saved_size = bsize;
1048     gst_buffer_set_size (buffer, tagsize);
1049     newsize = tagsize;
1050     parse_ret = klass->parse_tag (demux, buffer, TRUE, &newsize, &new_tags);
1051
1052     gst_buffer_set_size (buffer, saved_size);
1053
1054     switch (parse_ret) {
1055       case GST_TAG_DEMUX_RESULT_OK:
1056         res = TRUE;
1057         demux->priv->strip_start = newsize;
1058         GST_DEBUG_OBJECT (demux, "Read start tag of size %d", newsize);
1059         break;
1060       case GST_TAG_DEMUX_RESULT_BROKEN_TAG:
1061         res = TRUE;
1062         demux->priv->strip_start = newsize;
1063         GST_WARNING_OBJECT (demux, "Ignoring broken start tag of size %d",
1064             demux->priv->strip_start);
1065         break;
1066       case GST_TAG_DEMUX_RESULT_AGAIN:
1067         GST_DEBUG_OBJECT (demux, "Re-parse, this time with %d bytes", newsize);
1068         g_assert (newsize != tagsize);
1069         tagsize = newsize;
1070         break;
1071     }
1072   } while (parse_ret == GST_TAG_DEMUX_RESULT_AGAIN);
1073
1074   *tags = new_tags;
1075   new_tags = NULL;
1076
1077 done:
1078   if (new_tags)
1079     gst_tag_list_free (new_tags);
1080   if (buffer)
1081     gst_buffer_unref (buffer);
1082   return res;
1083 }
1084
1085 /* This function operates similarly to gst_type_find_element_activate
1086  * in the typefind element
1087  * 1. try to activate in pull mode. if not, switch to push and succeed.
1088  * 2. try to read tags in pull mode
1089  * 3. typefind the contents
1090  * 4. deactivate pull mode.
1091  * 5. if we didn't find any caps, fail.
1092  * 6. Add the srcpad
1093  * 7. if the sink pad is activated, we are in pull mode. succeed.
1094  *    otherwise activate both pads in push mode and succeed.
1095  */
1096 static gboolean
1097 gst_tag_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
1098 {
1099   GstTypeFindProbability probability = 0;
1100   GstTagDemuxClass *klass;
1101   GstTagDemux *demux;
1102   GstTagList *start_tags = NULL;
1103   GstTagList *end_tags = NULL;
1104   gboolean e_tag_ok, s_tag_ok;
1105   gboolean ret = FALSE;
1106   GstCaps *caps = NULL;
1107   GstQuery *query;
1108   gboolean pull_mode;
1109
1110   demux = GST_TAG_DEMUX (parent);
1111   klass = GST_TAG_DEMUX_CLASS (G_OBJECT_GET_CLASS (demux));
1112
1113   /* 1: */
1114   /* If we can activate pull_range upstream, then read any end and start
1115    * tags, otherwise activate in push mode and the chain function will 
1116    * collect buffers, read the start tag and output a buffer to end
1117    * preroll.
1118    */
1119   query = gst_query_new_scheduling ();
1120
1121   if (!gst_pad_peer_query (sinkpad, query)) {
1122     gst_query_unref (query);
1123     goto activate_push;
1124   }
1125
1126   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
1127   gst_query_unref (query);
1128
1129   if (!pull_mode)
1130     goto activate_push;
1131
1132   if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE))
1133     goto activate_push;
1134
1135   /* Look for tags at start and end of file */
1136   GST_DEBUG_OBJECT (demux, "Activated pull mode. Looking for tags");
1137   if (!gst_tag_demux_get_upstream_size (demux))
1138     return FALSE;
1139
1140   demux->priv->strip_start = 0;
1141   demux->priv->strip_end = 0;
1142
1143   s_tag_ok = gst_tag_demux_pull_start_tag (demux, &start_tags);
1144   e_tag_ok = gst_tag_demux_pull_end_tag (demux, &end_tags);
1145
1146   if (klass->merge_tags != NULL) {
1147     demux->priv->parsed_tags = klass->merge_tags (demux, start_tags, end_tags);
1148   } else {
1149     /* we merge in REPLACE mode, so put the less important tags first, which
1150      * we'll just assume is the end tag (subclasses may change this behaviour
1151      * or make it configurable by overriding the merge_tags vfunc) */
1152     demux->priv->parsed_tags =
1153         gst_tag_list_merge (end_tags, start_tags, GST_TAG_MERGE_REPLACE);
1154   }
1155
1156   if (start_tags)
1157     gst_tag_list_free (start_tags);
1158   if (end_tags)
1159     gst_tag_list_free (end_tags);
1160
1161   if (!e_tag_ok && !s_tag_ok)
1162     return FALSE;
1163
1164   if (demux->priv->parsed_tags != NULL) {
1165     demux->priv->send_tag_event = TRUE;
1166   }
1167
1168   if (demux->priv->upstream_size <=
1169       demux->priv->strip_start + demux->priv->strip_end) {
1170     /* There was no data (probably due to a truncated file) */
1171     GST_DEBUG_OBJECT (demux, "No data in file");
1172     /* so we don't know about type either */
1173     GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
1174     goto done_activate;
1175   }
1176
1177   /* 3 - Do typefinding on data */
1178   caps = gst_type_find_helper_get_range (GST_OBJECT (demux), NULL,
1179       (GstTypeFindHelperGetRangeFunction) gst_tag_demux_read_range,
1180       demux->priv->upstream_size
1181       - (demux->priv->strip_start + demux->priv->strip_end), NULL,
1182       &probability);
1183
1184   GST_DEBUG_OBJECT (demux, "Found type %" GST_PTR_FORMAT " with a "
1185       "probability of %u", caps, probability);
1186
1187   /* 4 - Deactivate pull mode */
1188   if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, FALSE)) {
1189     if (caps)
1190       gst_caps_unref (caps);
1191     GST_DEBUG_OBJECT (demux, "Could not deactivate sinkpad after reading tags");
1192     return FALSE;
1193   }
1194
1195   /* 5 - If we didn't find the caps, fail */
1196   if (caps == NULL) {
1197     GST_DEBUG_OBJECT (demux, "Could not detect type of contents");
1198     GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
1199     goto done_activate;
1200   }
1201
1202   /* tag reading and typefinding were already done, don't do them again in
1203    * the chain function if we end up in push mode */
1204   demux->priv->state = GST_TAG_DEMUX_STREAMING;
1205
1206   /* 6 Set the srcpad caps now we know them */
1207   gst_tag_demux_set_src_caps (demux, caps);
1208
1209   /* 7 - if the sinkpad is active, it was done by downstream so we're 
1210    * done, otherwise switch to push */
1211   ret = TRUE;
1212   if (!gst_pad_is_active (sinkpad)) {
1213     ret = gst_pad_activate_mode (demux->priv->srcpad, GST_PAD_MODE_PUSH, TRUE);
1214     ret &= gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
1215   }
1216
1217 done_activate:
1218
1219   if (caps)
1220     gst_caps_unref (caps);
1221
1222   return ret;
1223
1224 activate_push:
1225   {
1226     GST_DEBUG_OBJECT (demux, "No pull mode. Changing to push, but won't be "
1227         "able to read end tags");
1228     demux->priv->state = GST_TAG_DEMUX_READ_START_TAG;
1229     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
1230   }
1231 }
1232
1233 static gboolean
1234 gst_tag_demux_src_activate_mode (GstPad * pad, GstObject * parent,
1235     GstPadMode mode, gboolean active)
1236 {
1237   gboolean res = TRUE;
1238   GstTagDemux *demux = GST_TAG_DEMUX (parent);
1239
1240   switch (mode) {
1241     case GST_PAD_MODE_PULL:
1242       res = gst_pad_activate_mode (demux->priv->sinkpad, mode, active);
1243       break;
1244     default:
1245       break;
1246   }
1247   return res;
1248 }
1249
1250 static GstFlowReturn
1251 gst_tag_demux_read_range (GstTagDemux * demux, GstObject * parent,
1252     guint64 offset, guint length, GstBuffer ** buffer)
1253 {
1254   GstFlowReturn ret;
1255   guint64 in_offset;
1256   guint in_length;
1257   gsize size;
1258
1259   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1260
1261   /* Adjust offset and length of the request to trim off tag information. 
1262    * For the returned buffer, adjust the output offset to match what downstream
1263    * should see */
1264   in_offset = offset + demux->priv->strip_start;
1265
1266   if (!gst_tag_demux_get_upstream_size (demux))
1267     return GST_FLOW_ERROR;
1268
1269   if (in_offset + length >= demux->priv->upstream_size - demux->priv->strip_end) {
1270     if (in_offset + demux->priv->strip_end >= demux->priv->upstream_size)
1271       return GST_FLOW_EOS;
1272     in_length = demux->priv->upstream_size - demux->priv->strip_end - in_offset;
1273   } else {
1274     in_length = length;
1275   }
1276
1277   ret = gst_pad_pull_range (demux->priv->sinkpad, in_offset, in_length, buffer);
1278
1279   if (ret == GST_FLOW_OK && *buffer) {
1280     if (!gst_tag_demux_trim_buffer (demux, buffer, &size))
1281       goto read_beyond_end;
1282
1283     /* this should only happen in streaming mode */
1284     g_assert (*buffer != NULL);
1285   }
1286
1287   return ret;
1288
1289 read_beyond_end:
1290   {
1291     GST_DEBUG_OBJECT (demux, "attempted read beyond end of file");
1292     if (*buffer != NULL) {
1293       gst_buffer_unref (*buffer);
1294       *buffer = NULL;
1295     }
1296     return GST_FLOW_EOS;
1297   }
1298 }
1299
1300 static GstFlowReturn
1301 gst_tag_demux_src_getrange (GstPad * srcpad, GstObject * parent,
1302     guint64 offset, guint length, GstBuffer ** buffer)
1303 {
1304   GstTagDemux *demux = GST_TAG_DEMUX (parent);
1305
1306   /* downstream in pull mode won't miss a newsegment event,
1307    * but it likely appreciates other (tag) events */
1308   if (demux->priv->need_newseg) {
1309     gst_tag_demux_send_pending_events (demux);
1310     demux->priv->need_newseg = FALSE;
1311   }
1312
1313   if (demux->priv->send_tag_event) {
1314     gst_tag_demux_send_tag_event (demux);
1315     demux->priv->send_tag_event = FALSE;
1316   }
1317
1318   return gst_tag_demux_read_range (demux, NULL, offset, length, buffer);
1319 }
1320
1321 static GstStateChangeReturn
1322 gst_tag_demux_change_state (GstElement * element, GstStateChange transition)
1323 {
1324   GstStateChangeReturn ret;
1325   GstTagDemux *demux = GST_TAG_DEMUX (element);
1326
1327   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1328
1329   switch (transition) {
1330     case GST_STATE_CHANGE_PAUSED_TO_READY:
1331       gst_tag_demux_reset (demux);
1332       break;
1333     default:
1334       break;
1335   }
1336   return ret;
1337 }
1338
1339 static gboolean
1340 gst_tag_demux_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
1341 {
1342   /* For a position or duration query, adjust the returned
1343    * bytes to strip off the end and start areas */
1344   GstTagDemux *demux = GST_TAG_DEMUX (parent);
1345   GstFormat format;
1346   gint64 result;
1347
1348   if (!gst_pad_peer_query (demux->priv->sinkpad, query))
1349     return FALSE;
1350
1351   switch (GST_QUERY_TYPE (query)) {
1352     case GST_QUERY_POSITION:
1353     {
1354       gst_query_parse_position (query, &format, &result);
1355       if (format == GST_FORMAT_BYTES) {
1356         result -= demux->priv->strip_start;
1357         gst_query_set_position (query, format, result);
1358       }
1359       break;
1360     }
1361     case GST_QUERY_DURATION:
1362     {
1363       gst_query_parse_duration (query, &format, &result);
1364       if (format == GST_FORMAT_BYTES) {
1365         result -= demux->priv->strip_start + demux->priv->strip_end;
1366         gst_query_set_duration (query, format, result);
1367       }
1368       break;
1369     }
1370     default:
1371       break;
1372   }
1373
1374   return TRUE;
1375 }
1376
1377 static void
1378 gst_tag_demux_send_pending_events (GstTagDemux * demux)
1379 {
1380   GList *events;
1381
1382   /* send any pending events we cached */
1383   GST_OBJECT_LOCK (demux);
1384   events = demux->priv->pending_events;
1385   demux->priv->pending_events = NULL;
1386   GST_OBJECT_UNLOCK (demux);
1387
1388   while (events != NULL) {
1389     GST_DEBUG_OBJECT (demux->priv->srcpad, "sending cached %s event: %"
1390         GST_PTR_FORMAT, GST_EVENT_TYPE_NAME (events->data), events->data);
1391     gst_pad_push_event (demux->priv->srcpad, GST_EVENT (events->data));
1392     events = g_list_delete_link (events, events);
1393   }
1394 }
1395
1396 static void
1397 gst_tag_demux_send_tag_event (GstTagDemux * demux)
1398 {
1399   /* FIXME: what's the correct merge mode? Docs need to tell... */
1400   GstTagList *merged = gst_tag_list_merge (demux->priv->event_tags,
1401       demux->priv->parsed_tags, GST_TAG_MERGE_KEEP);
1402
1403   if (demux->priv->parsed_tags)
1404     gst_element_post_message (GST_ELEMENT (demux),
1405         gst_message_new_tag (GST_OBJECT (demux),
1406             gst_tag_list_copy (demux->priv->parsed_tags)));
1407
1408   if (merged) {
1409     GstEvent *event = gst_event_new_tag (merged);
1410
1411     GST_EVENT_TIMESTAMP (event) = 0;
1412     GST_DEBUG_OBJECT (demux, "Sending tag event on src pad");
1413     gst_pad_push_event (demux->priv->srcpad, event);
1414   }
1415 }
1416
1417 static gboolean
1418 gst_tag_demux_send_new_segment (GstTagDemux * tagdemux)
1419 {
1420   GstEvent *event;
1421   gint64 start, stop, position;
1422   GstSegment *seg = &tagdemux->priv->segment;
1423   GstSegment newseg;
1424
1425   if (seg->format == GST_FORMAT_UNDEFINED) {
1426     GST_LOG_OBJECT (tagdemux,
1427         "No new segment received before first buffer. Using default");
1428     gst_segment_init (seg, GST_FORMAT_BYTES);
1429     seg->start = tagdemux->priv->strip_start;
1430     seg->time = tagdemux->priv->strip_start;
1431   }
1432
1433   /* Can't adjust segments in non-BYTES formats */
1434   if (tagdemux->priv->segment.format != GST_FORMAT_BYTES) {
1435     event = gst_event_new_segment (seg);
1436     return gst_pad_push_event (tagdemux->priv->srcpad, event);
1437   }
1438
1439   start = seg->start;
1440   stop = seg->stop;
1441   position = seg->time;
1442
1443   g_return_val_if_fail (start != -1, FALSE);
1444   g_return_val_if_fail (position != -1, FALSE);
1445
1446   if (tagdemux->priv->strip_end > 0) {
1447     if (gst_tag_demux_get_upstream_size (tagdemux)) {
1448       guint64 v1tag_offset =
1449           tagdemux->priv->upstream_size - tagdemux->priv->strip_end;
1450
1451       if (start >= v1tag_offset) {
1452         /* Segment is completely within the end tag, output an open-ended
1453          * segment, even though all the buffers will get trimmed away */
1454         start = v1tag_offset;
1455         stop = -1;
1456       }
1457
1458       if (stop != -1 && stop >= v1tag_offset) {
1459         GST_DEBUG_OBJECT (tagdemux,
1460             "Segment crosses the end tag. Trimming end");
1461         stop = v1tag_offset;
1462       }
1463     }
1464   }
1465
1466   if (tagdemux->priv->strip_start > 0) {
1467     if (start > tagdemux->priv->strip_start)
1468       start -= tagdemux->priv->strip_start;
1469     else
1470       start = 0;
1471
1472     if (position > tagdemux->priv->strip_start)
1473       position -= tagdemux->priv->strip_start;
1474     else
1475       position = 0;
1476
1477     if (stop != -1) {
1478       if (stop > tagdemux->priv->strip_start)
1479         stop -= tagdemux->priv->strip_start;
1480       else
1481         stop = 0;
1482     }
1483   }
1484
1485   GST_DEBUG_OBJECT (tagdemux, "Sending segment %" GST_SEGMENT_FORMAT, seg);
1486
1487   gst_segment_copy_into (seg, &newseg);
1488   newseg.start = start;
1489   newseg.stop = stop;
1490   newseg.position = position;
1491   event = gst_event_new_segment (&newseg);
1492
1493   return gst_pad_push_event (tagdemux->priv->srcpad, event);
1494 }