gst: Implement segment-done event
[platform/upstream/gstreamer.git] / gst / aiff / aiffparse.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: t; c-basic-offset: 2 -*- */
2 /* GStreamer AIFF parser
3  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
4  *               <2006> Nokia Corporation, Stefan Kost <stefan.kost@nokia.com>.
5  *               <2008> Pioneers of the Inevitable <songbird@songbirdnest.com>
6  *
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:element-aiffparse
26  *
27  * <refsect2>
28  * <para>
29  * Parse a .aiff file into raw or compressed audio.
30  * </para>
31  * <para>
32  * AIFFparse supports both push and pull mode operations, making it possible to
33  * stream from a network source.
34  * </para>
35  * <title>Example launch line</title>
36  * <para>
37  * <programlisting>
38  * gst-launch filesrc location=sine.aiff ! aiffparse ! audioconvert ! alsasink
39  * </programlisting>
40  * Read a aiff file and output to the soundcard using the ALSA element. The
41  * aiff file is assumed to contain raw uncompressed samples.
42  * </para>
43  * <para>
44  * <programlisting>
45  * gst-launch gnomevfssrc location=http://www.example.org/sine.aiff ! queue ! aiffparse ! audioconvert ! alsasink
46  * </programlisting>
47  * Stream data from a network url.
48  * </para>
49  * </refsect2>
50  */
51
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55
56 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
57  * with newer GLib versions (>= 2.31.0) */
58 #define GLIB_DISABLE_DEPRECATION_WARNINGS
59
60 #include <string.h>
61 #include <math.h>
62
63 #include "aiffparse.h"
64 #include <gst/audio/audio.h>
65 #include <gst/tag/tag.h>
66 #include <gst/gst-i18n-plugin.h>
67
68 GST_DEBUG_CATEGORY (aiffparse_debug);
69 #define GST_CAT_DEFAULT (aiffparse_debug)
70
71 static void gst_aiff_parse_dispose (GObject * object);
72
73 static gboolean gst_aiff_parse_sink_activate (GstPad * sinkpad);
74 static gboolean gst_aiff_parse_sink_activate_pull (GstPad * sinkpad,
75     gboolean active);
76 static gboolean gst_aiff_parse_send_event (GstElement * element,
77     GstEvent * event);
78 static GstStateChangeReturn gst_aiff_parse_change_state (GstElement * element,
79     GstStateChange transition);
80
81 static const GstQueryType *gst_aiff_parse_get_query_types (GstPad * pad);
82 static gboolean gst_aiff_parse_pad_query (GstPad * pad, GstQuery * query);
83 static gboolean gst_aiff_parse_pad_convert (GstPad * pad,
84     GstFormat src_format,
85     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
86
87 static GstFlowReturn gst_aiff_parse_chain (GstPad * pad, GstBuffer * buf);
88 static void gst_aiff_parse_loop (GstPad * pad);
89 static gboolean gst_aiff_parse_srcpad_event (GstPad * pad, GstEvent * event);
90
91 static GstStaticPadTemplate sink_template_factory =
92 GST_STATIC_PAD_TEMPLATE ("sink",
93     GST_PAD_SINK,
94     GST_PAD_ALWAYS,
95     GST_STATIC_CAPS ("audio/x-aiff")
96     );
97
98 static GstStaticPadTemplate src_template_factory =
99     GST_STATIC_PAD_TEMPLATE ("src",
100     GST_PAD_SRC,
101     GST_PAD_ALWAYS,
102     GST_STATIC_CAPS (GST_AUDIO_INT_PAD_TEMPLATE_CAPS ";"
103         GST_AUDIO_FLOAT_PAD_TEMPLATE_CAPS)
104     );
105
106 GST_BOILERPLATE (GstAiffParse, gst_aiff_parse, GstElement, GST_TYPE_ELEMENT);
107
108 static void
109 gst_aiff_parse_base_init (gpointer g_class)
110 {
111   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
112
113   gst_element_class_add_pad_template (element_class,
114       gst_static_pad_template_get (&sink_template_factory));
115   gst_element_class_add_pad_template (element_class,
116       gst_static_pad_template_get (&src_template_factory));
117
118   gst_element_class_set_details_simple (element_class,
119       "AIFF audio demuxer", "Codec/Demuxer/Audio",
120       "Parse a .aiff file into raw audio",
121       "Pioneers of the Inevitable <songbird@songbirdnest.com>");
122 }
123
124 static void
125 gst_aiff_parse_class_init (GstAiffParseClass * klass)
126 {
127   GstElementClass *gstelement_class;
128   GObjectClass *object_class;
129
130   gstelement_class = (GstElementClass *) klass;
131   object_class = (GObjectClass *) klass;
132
133   parent_class = g_type_class_peek_parent (klass);
134
135   object_class->dispose = gst_aiff_parse_dispose;
136
137   gstelement_class->change_state =
138       GST_DEBUG_FUNCPTR (gst_aiff_parse_change_state);
139   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_aiff_parse_send_event);
140 }
141
142 static void
143 gst_aiff_parse_reset (GstAiffParse * aiff)
144 {
145   aiff->state = AIFF_PARSE_START;
146
147   /* These will all be set correctly in the fmt chunk */
148   aiff->rate = 0;
149   aiff->width = 0;
150   aiff->depth = 0;
151   aiff->channels = 0;
152   aiff->bps = 0;
153   aiff->offset = 0;
154   aiff->end_offset = 0;
155   aiff->dataleft = 0;
156   aiff->datasize = 0;
157   aiff->datastart = 0;
158   aiff->duration = 0;
159   aiff->got_comm = FALSE;
160
161   if (aiff->caps) {
162     gst_caps_unref (aiff->caps);
163     aiff->caps = NULL;
164   }
165   if (aiff->seek_event)
166     gst_event_unref (aiff->seek_event);
167   aiff->seek_event = NULL;
168   if (aiff->adapter) {
169     gst_adapter_clear (aiff->adapter);
170     aiff->adapter = NULL;
171   }
172
173   if (aiff->tags != NULL) {
174     gst_tag_list_free (aiff->tags);
175     aiff->tags = NULL;
176   }
177 }
178
179 static void
180 gst_aiff_parse_dispose (GObject * object)
181 {
182   GstAiffParse *aiff = GST_AIFF_PARSE (object);
183
184   GST_DEBUG_OBJECT (aiff, "AIFF: Dispose");
185   gst_aiff_parse_reset (aiff);
186
187   G_OBJECT_CLASS (parent_class)->dispose (object);
188 }
189
190 static void
191 gst_aiff_parse_init (GstAiffParse * aiffparse, GstAiffParseClass * g_class)
192 {
193   gst_aiff_parse_reset (aiffparse);
194
195   /* sink */
196   aiffparse->sinkpad =
197       gst_pad_new_from_static_template (&sink_template_factory, "sink");
198   gst_pad_set_activate_function (aiffparse->sinkpad,
199       GST_DEBUG_FUNCPTR (gst_aiff_parse_sink_activate));
200   gst_pad_set_activatepull_function (aiffparse->sinkpad,
201       GST_DEBUG_FUNCPTR (gst_aiff_parse_sink_activate_pull));
202   gst_pad_set_chain_function (aiffparse->sinkpad,
203       GST_DEBUG_FUNCPTR (gst_aiff_parse_chain));
204   gst_element_add_pad (GST_ELEMENT_CAST (aiffparse), aiffparse->sinkpad);
205
206   /* source */
207   aiffparse->srcpad =
208       gst_pad_new_from_static_template (&src_template_factory, "src");
209   gst_pad_use_fixed_caps (aiffparse->srcpad);
210   gst_pad_set_query_type_function (aiffparse->srcpad,
211       GST_DEBUG_FUNCPTR (gst_aiff_parse_get_query_types));
212   gst_pad_set_query_function (aiffparse->srcpad,
213       GST_DEBUG_FUNCPTR (gst_aiff_parse_pad_query));
214   gst_pad_set_event_function (aiffparse->srcpad,
215       GST_DEBUG_FUNCPTR (gst_aiff_parse_srcpad_event));
216   gst_element_add_pad (GST_ELEMENT_CAST (aiffparse), aiffparse->srcpad);
217 }
218
219 static gboolean
220 gst_aiff_parse_parse_file_header (GstAiffParse * aiff, GstBuffer * buf)
221 {
222   guint8 *data;
223   guint32 header, type = 0;
224
225   if (GST_BUFFER_SIZE (buf) < 12) {
226     GST_WARNING_OBJECT (aiff, "Buffer too short");
227     goto not_aiff;
228   }
229
230   data = GST_BUFFER_DATA (buf);
231
232   header = GST_READ_UINT32_LE (data);
233   type = GST_READ_UINT32_LE (data + 8);
234
235   if (header != GST_MAKE_FOURCC ('F', 'O', 'R', 'M'))
236     goto not_aiff;
237
238   if (type == GST_MAKE_FOURCC ('A', 'I', 'F', 'F'))
239     aiff->is_aifc = FALSE;
240   else if (type == GST_MAKE_FOURCC ('A', 'I', 'F', 'C'))
241     aiff->is_aifc = TRUE;
242   else
243     goto not_aiff;
244
245   gst_buffer_unref (buf);
246   return TRUE;
247
248   /* ERRORS */
249 not_aiff:
250   {
251     GST_ELEMENT_ERROR (aiff, STREAM, WRONG_TYPE, (NULL),
252         ("File is not an AIFF file: %" GST_FOURCC_FORMAT,
253             GST_FOURCC_ARGS (type)));
254     gst_buffer_unref (buf);
255     return FALSE;
256   }
257 }
258
259 static GstFlowReturn
260 gst_aiff_parse_stream_init (GstAiffParse * aiff)
261 {
262   GstFlowReturn res;
263   GstBuffer *buf = NULL;
264
265   if ((res = gst_pad_pull_range (aiff->sinkpad,
266               aiff->offset, 12, &buf)) != GST_FLOW_OK)
267     return res;
268   else if (!gst_aiff_parse_parse_file_header (aiff, buf))
269     return GST_FLOW_ERROR;
270
271   aiff->offset += 12;
272
273   return GST_FLOW_OK;
274 }
275
276 /* This function is used to perform seeks on the element in
277  * pull mode.
278  *
279  * It also works when event is NULL, in which case it will just
280  * start from the last configured segment. This technique is
281  * used when activating the element and to perform the seek in
282  * READY.
283  */
284 static gboolean
285 gst_aiff_parse_perform_seek (GstAiffParse * aiff, GstEvent * event)
286 {
287   gboolean res;
288   gdouble rate;
289   GstFormat format, bformat;
290   GstSeekFlags flags;
291   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
292   gint64 cur, stop, upstream_size;
293   gboolean flush;
294   gboolean update;
295   GstSegment seeksegment = { 0, };
296   gint64 last_stop;
297
298   if (event) {
299     GST_DEBUG_OBJECT (aiff, "doing seek with event");
300
301     gst_event_parse_seek (event, &rate, &format, &flags,
302         &cur_type, &cur, &stop_type, &stop);
303
304     /* no negative rates yet */
305     if (rate < 0.0)
306       goto negative_rate;
307
308     if (format != aiff->segment.format) {
309       GST_INFO_OBJECT (aiff, "converting seek-event from %s to %s",
310           gst_format_get_name (format),
311           gst_format_get_name (aiff->segment.format));
312       res = TRUE;
313       if (cur_type != GST_SEEK_TYPE_NONE)
314         res =
315             gst_pad_query_convert (aiff->srcpad, format, cur,
316             &aiff->segment.format, &cur);
317       if (res && stop_type != GST_SEEK_TYPE_NONE)
318         res =
319             gst_pad_query_convert (aiff->srcpad, format, stop,
320             &aiff->segment.format, &stop);
321       if (!res)
322         goto no_format;
323
324       format = aiff->segment.format;
325     }
326   } else {
327     GST_DEBUG_OBJECT (aiff, "doing seek without event");
328     flags = 0;
329     rate = 1.0;
330     cur_type = GST_SEEK_TYPE_SET;
331     stop_type = GST_SEEK_TYPE_SET;
332   }
333
334   /* get flush flag */
335   flush = flags & GST_SEEK_FLAG_FLUSH;
336
337   /* now we need to make sure the streaming thread is stopped. We do this by
338    * either sending a FLUSH_START event downstream which will cause the
339    * streaming thread to stop with a WRONG_STATE.
340    * For a non-flushing seek we simply pause the task, which will happen as soon
341    * as it completes one iteration (and thus might block when the sink is
342    * blocking in preroll). */
343   if (flush) {
344     GST_DEBUG_OBJECT (aiff, "sending flush start");
345     gst_pad_push_event (aiff->srcpad, gst_event_new_flush_start ());
346   } else {
347     gst_pad_pause_task (aiff->sinkpad);
348   }
349
350   /* we should now be able to grab the streaming thread because we stopped it
351    * with the above flush/pause code */
352   GST_PAD_STREAM_LOCK (aiff->sinkpad);
353
354   /* save current position */
355   last_stop = aiff->segment.last_stop;
356
357   GST_DEBUG_OBJECT (aiff, "stopped streaming at %" G_GINT64_FORMAT, last_stop);
358
359   /* copy segment, we need this because we still need the old
360    * segment when we close the current segment. */
361   memcpy (&seeksegment, &aiff->segment, sizeof (GstSegment));
362
363   /* configure the seek parameters in the seeksegment. We will then have the
364    * right values in the segment to perform the seek */
365   if (event) {
366     GST_DEBUG_OBJECT (aiff, "configuring seek");
367     gst_segment_set_seek (&seeksegment, rate, format, flags,
368         cur_type, cur, stop_type, stop, &update);
369   }
370
371   /* figure out the last position we need to play. If it's configured (stop !=
372    * -1), use that, else we play until the total duration of the file */
373   if ((stop = seeksegment.stop) == -1)
374     stop = seeksegment.duration;
375
376   GST_DEBUG_OBJECT (aiff, "cur_type =%d", cur_type);
377   if ((cur_type != GST_SEEK_TYPE_NONE)) {
378     /* bring offset to bytes, if the bps is 0, we have the segment in BYTES and
379      * we can just copy the last_stop. If not, we use the bps to convert TIME to
380      * bytes. */
381     if (aiff->bps > 0)
382       aiff->offset =
383           gst_util_uint64_scale_ceil (seeksegment.last_stop,
384           (guint64) aiff->bps, GST_SECOND);
385     else
386       aiff->offset = seeksegment.last_stop;
387     GST_LOG_OBJECT (aiff, "offset=%" G_GUINT64_FORMAT, aiff->offset);
388     aiff->offset -= (aiff->offset % aiff->bytes_per_sample);
389     GST_LOG_OBJECT (aiff, "offset=%" G_GUINT64_FORMAT, aiff->offset);
390     aiff->offset += aiff->datastart;
391     GST_LOG_OBJECT (aiff, "offset=%" G_GUINT64_FORMAT, aiff->offset);
392   } else {
393     GST_LOG_OBJECT (aiff, "continue from offset=%" G_GUINT64_FORMAT,
394         aiff->offset);
395   }
396
397   if (stop_type != GST_SEEK_TYPE_NONE) {
398     if (aiff->bps > 0)
399       aiff->end_offset =
400           gst_util_uint64_scale_ceil (stop, (guint64) aiff->bps, GST_SECOND);
401     else
402       aiff->end_offset = stop;
403     GST_LOG_OBJECT (aiff, "end_offset=%" G_GUINT64_FORMAT, aiff->end_offset);
404     aiff->end_offset -= (aiff->end_offset % aiff->bytes_per_sample);
405     GST_LOG_OBJECT (aiff, "end_offset=%" G_GUINT64_FORMAT, aiff->end_offset);
406     aiff->end_offset += aiff->datastart;
407     GST_LOG_OBJECT (aiff, "end_offset=%" G_GUINT64_FORMAT, aiff->end_offset);
408   } else {
409     GST_LOG_OBJECT (aiff, "continue to end_offset=%" G_GUINT64_FORMAT,
410         aiff->end_offset);
411   }
412
413   /* make sure filesize is not exceeded due to rounding errors or so,
414    * same precaution as in _stream_headers */
415   bformat = GST_FORMAT_BYTES;
416   if (gst_pad_query_peer_duration (aiff->sinkpad, &bformat, &upstream_size))
417     aiff->end_offset = MIN (aiff->end_offset, upstream_size);
418
419   /* this is the range of bytes we will use for playback */
420   aiff->offset = MIN (aiff->offset, aiff->end_offset);
421   aiff->dataleft = aiff->end_offset - aiff->offset;
422
423   GST_DEBUG_OBJECT (aiff,
424       "seek: rate %lf, offset %" G_GUINT64_FORMAT ", end %" G_GUINT64_FORMAT
425       ", segment %" GST_TIME_FORMAT " -- %" GST_TIME_FORMAT, rate, aiff->offset,
426       aiff->end_offset, GST_TIME_ARGS (seeksegment.start),
427       GST_TIME_ARGS (stop));
428
429   /* prepare for streaming again */
430   if (flush) {
431     /* if we sent a FLUSH_START, we now send a FLUSH_STOP */
432     GST_DEBUG_OBJECT (aiff, "sending flush stop");
433     gst_pad_push_event (aiff->srcpad, gst_event_new_flush_stop ());
434   } else if (aiff->segment_running) {
435     /* we are running the current segment and doing a non-flushing seek,
436      * close the segment first based on the previous last_stop. */
437     GST_DEBUG_OBJECT (aiff, "closing running segment %" G_GINT64_FORMAT
438         " to %" G_GINT64_FORMAT, aiff->segment.accum, aiff->segment.last_stop);
439
440     /* queue the segment for sending in the stream thread */
441     if (aiff->close_segment)
442       gst_event_unref (aiff->close_segment);
443     aiff->close_segment = gst_event_new_new_segment (TRUE,
444         aiff->segment.rate, aiff->segment.format,
445         aiff->segment.accum, aiff->segment.last_stop, aiff->segment.accum);
446
447     /* keep track of our last_stop */
448     seeksegment.accum = aiff->segment.last_stop;
449   }
450
451   /* now we did the seek and can activate the new segment values */
452   memcpy (&aiff->segment, &seeksegment, sizeof (GstSegment));
453
454   /* if we're doing a segment seek, post a SEGMENT_START message */
455   if (aiff->segment.flags & GST_SEEK_FLAG_SEGMENT) {
456     gst_element_post_message (GST_ELEMENT_CAST (aiff),
457         gst_message_new_segment_start (GST_OBJECT_CAST (aiff),
458             aiff->segment.format, aiff->segment.last_stop));
459   }
460
461   /* now create the newsegment */
462   GST_DEBUG_OBJECT (aiff, "Creating newsegment from %" G_GINT64_FORMAT
463       " to %" G_GINT64_FORMAT, aiff->segment.last_stop, stop);
464
465   /* store the newsegment event so it can be sent from the streaming thread. */
466   if (aiff->start_segment)
467     gst_event_unref (aiff->start_segment);
468   aiff->start_segment =
469       gst_event_new_new_segment (FALSE, aiff->segment.rate,
470       aiff->segment.format, aiff->segment.last_stop, stop,
471       aiff->segment.last_stop);
472
473   /* mark discont if we are going to stream from another position. */
474   if (last_stop != aiff->segment.last_stop) {
475     GST_DEBUG_OBJECT (aiff, "mark DISCONT, we did a seek to another position");
476     aiff->discont = TRUE;
477   }
478
479   /* and start the streaming task again */
480   aiff->segment_running = TRUE;
481   if (!aiff->streaming) {
482     gst_pad_start_task (aiff->sinkpad, (GstTaskFunction) gst_aiff_parse_loop,
483         aiff->sinkpad, NULL);
484   }
485
486   GST_PAD_STREAM_UNLOCK (aiff->sinkpad);
487
488   return TRUE;
489
490   /* ERRORS */
491 negative_rate:
492   {
493     GST_DEBUG_OBJECT (aiff, "negative playback rates are not supported yet.");
494     return FALSE;
495   }
496 no_format:
497   {
498     GST_DEBUG_OBJECT (aiff, "unsupported format given, seek aborted.");
499     return FALSE;
500   }
501 }
502
503 /*
504  * gst_aiff_parse_peek_chunk_info:
505  * @aiff AIFFparse object
506  * @tag holder for tag
507  * @size holder for tag size
508  *
509  * Peek next chunk info (tag and size)
510  *
511  * Returns: %TRUE when the chunk info (header) is available
512  */
513 static gboolean
514 gst_aiff_parse_peek_chunk_info (GstAiffParse * aiff, guint32 * tag,
515     guint32 * size)
516 {
517   const guint8 *data = NULL;
518
519   if (gst_adapter_available (aiff->adapter) < 8)
520     return FALSE;
521
522   data = gst_adapter_peek (aiff->adapter, 8);
523   *tag = GST_READ_UINT32_LE (data);
524   *size = GST_READ_UINT32_BE (data + 4);
525
526   GST_DEBUG ("Next chunk size is %d bytes, type %" GST_FOURCC_FORMAT, *size,
527       GST_FOURCC_ARGS (*tag));
528
529   return TRUE;
530 }
531
532 /*
533  * gst_aiff_parse_peek_chunk:
534  * @aiff AIFFparse object
535  * @tag holder for tag
536  * @size holder for tag size
537  *
538  * Peek enough data for one full chunk
539  *
540  * Returns: %TRUE when the full chunk is available
541  */
542 static gboolean
543 gst_aiff_parse_peek_chunk (GstAiffParse * aiff, guint32 * tag, guint32 * size)
544 {
545   guint32 peek_size = 0;
546   guint available;
547
548   if (!gst_aiff_parse_peek_chunk_info (aiff, tag, size))
549     return FALSE;
550
551   GST_DEBUG ("Need to peek chunk of %d bytes", *size);
552   peek_size = (*size + 1) & ~1;
553
554   available = gst_adapter_available (aiff->adapter);
555   if (available >= (8 + peek_size)) {
556     return TRUE;
557   } else {
558     GST_LOG ("but only %u bytes available now", available);
559     return FALSE;
560   }
561 }
562
563 static gboolean
564 gst_aiff_parse_peek_data (GstAiffParse * aiff, guint32 size,
565     const guint8 ** data)
566 {
567   if (gst_adapter_available (aiff->adapter) < size)
568     return FALSE;
569
570   *data = gst_adapter_peek (aiff->adapter, size);
571   return TRUE;
572 }
573
574 /*
575  * gst_aiff_parse_calculate_duration:
576  * @aiff: aiffparse object
577  *
578  * Calculate duration on demand and store in @aiff.
579  *
580  * Returns: %TRUE if duration is available.
581  */
582 static gboolean
583 gst_aiff_parse_calculate_duration (GstAiffParse * aiff)
584 {
585   if (aiff->duration > 0)
586     return TRUE;
587
588   if (aiff->datasize > 0 && aiff->bps > 0) {
589     aiff->duration =
590         gst_util_uint64_scale_ceil (aiff->datasize, GST_SECOND,
591         (guint64) aiff->bps);
592     GST_INFO_OBJECT (aiff, "Got duration %" GST_TIME_FORMAT,
593         GST_TIME_ARGS (aiff->duration));
594     return TRUE;
595   }
596   return FALSE;
597 }
598
599 static void
600 gst_aiff_parse_ignore_chunk (GstAiffParse * aiff, GstBuffer * buf, guint32 tag,
601     guint32 size)
602 {
603   guint flush;
604
605   if (aiff->streaming) {
606     if (!gst_aiff_parse_peek_chunk (aiff, &tag, &size))
607       return;
608   }
609   GST_DEBUG_OBJECT (aiff, "Ignoring tag %" GST_FOURCC_FORMAT,
610       GST_FOURCC_ARGS (tag));
611   flush = 8 + ((size + 1) & ~1);
612   aiff->offset += flush;
613   if (aiff->streaming) {
614     gst_adapter_flush (aiff->adapter, flush);
615   } else {
616     gst_buffer_unref (buf);
617   }
618 }
619
620 static double
621 gst_aiff_parse_read_IEEE80 (guint8 * buf)
622 {
623   int s = buf[0] & 0xff;
624   int e = ((buf[0] & 0x7f) << 8) | (buf[1] & 0xff);
625   double f = ((unsigned long) (buf[2] & 0xff) << 24) |
626       ((buf[3] & 0xff) << 16) | ((buf[4] & 0xff) << 8) | (buf[5] & 0xff);
627
628   if (e == 32767) {
629     if (buf[2] & 0x80)
630       return HUGE_VAL;          /* Really NaN, but this won't happen in reality */
631     else {
632       if (s)
633         return -HUGE_VAL;
634       else
635         return HUGE_VAL;
636     }
637   }
638
639   f = ldexp (f, 32);
640   f += ((buf[6] & 0xff) << 24) |
641       ((buf[7] & 0xff) << 16) | ((buf[8] & 0xff) << 8) | (buf[9] & 0xff);
642
643   return ldexp (f, e - 16446);
644 }
645
646 static gboolean
647 gst_aiff_parse_parse_comm (GstAiffParse * aiff, GstBuffer * buf)
648 {
649   guint8 *data;
650   int size;
651
652   if (aiff->is_aifc)
653     size = 22;
654   else
655     size = 18;
656
657   if (GST_BUFFER_SIZE (buf) < size) {
658     GST_WARNING_OBJECT (aiff, "COMM chunk too short, cannot parse header");
659     return FALSE;
660   }
661
662   data = GST_BUFFER_DATA (buf);
663
664   aiff->channels = GST_READ_UINT16_BE (data);
665   aiff->total_frames = GST_READ_UINT32_BE (data + 2);
666   aiff->depth = GST_READ_UINT16_BE (data + 6);
667   aiff->width = GST_ROUND_UP_8 (aiff->depth);
668   aiff->rate = (int) gst_aiff_parse_read_IEEE80 (data + 8);
669
670   aiff->floating_point = FALSE;
671
672   if (aiff->is_aifc) {
673     guint32 fourcc = GST_READ_UINT32_LE (data + 18);
674
675     /* We only support the 'trivial' uncompressed AIFC, but it can be
676      * either big or little endian */
677     switch (fourcc) {
678       case GST_MAKE_FOURCC ('N', 'O', 'N', 'E'):
679         aiff->endianness = G_BIG_ENDIAN;
680         break;
681       case GST_MAKE_FOURCC ('s', 'o', 'w', 't'):
682         aiff->endianness = G_LITTLE_ENDIAN;
683         break;
684       case GST_MAKE_FOURCC ('F', 'L', '3', '2'):
685       case GST_MAKE_FOURCC ('f', 'l', '3', '2'):
686         aiff->floating_point = TRUE;
687         aiff->width = aiff->depth = 32;
688         aiff->endianness = G_BIG_ENDIAN;
689         break;
690       case GST_MAKE_FOURCC ('f', 'l', '6', '4'):
691         aiff->floating_point = TRUE;
692         aiff->width = aiff->depth = 64;
693         aiff->endianness = G_BIG_ENDIAN;
694         break;
695       default:
696         GST_WARNING_OBJECT (aiff, "Unsupported compression in AIFC "
697             "file: %" GST_FOURCC_FORMAT,
698             GST_FOURCC_ARGS (GST_READ_UINT32_LE (data + 18)));
699         return FALSE;
700
701     }
702   } else
703     aiff->endianness = G_BIG_ENDIAN;
704
705   return TRUE;
706 }
707
708 static GstFlowReturn
709 gst_aiff_parse_read_chunk (GstAiffParse * aiff, guint64 * offset, guint32 * tag,
710     GstBuffer ** data)
711 {
712   guint size;
713   GstFlowReturn res;
714   GstBuffer *buf;
715
716   if ((res =
717           gst_pad_pull_range (aiff->sinkpad, *offset, 8, &buf)) != GST_FLOW_OK)
718     return res;
719
720   *tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
721   size = GST_READ_UINT32_BE (GST_BUFFER_DATA (buf) + 4);
722
723   if ((res =
724           gst_pad_pull_range (aiff->sinkpad, (*offset) + 8, size,
725               &buf)) != GST_FLOW_OK)
726     return res;
727   else if (GST_BUFFER_SIZE (buf) < size)
728     goto too_small;
729
730   *data = buf;
731   *offset += 8 + GST_ROUND_UP_2 (size);
732
733   return GST_FLOW_OK;
734
735   /* ERRORS */
736 too_small:
737   {
738     /* short read, we return UNEXPECTED to mark the EOS case */
739     GST_DEBUG_OBJECT (aiff, "not enough data (available=%u, needed=%u)",
740         GST_BUFFER_SIZE (buf), size);
741     gst_buffer_unref (buf);
742     return GST_FLOW_UNEXPECTED;
743   }
744
745 }
746
747 static GstCaps *
748 gst_aiff_parse_create_caps (GstAiffParse * aiff)
749 {
750   GstCaps *caps;
751
752   if (aiff->floating_point) {
753     caps = gst_caps_new_simple ("audio/x-raw-float",
754         "width", G_TYPE_INT, aiff->width,
755         "channels", G_TYPE_INT, aiff->channels,
756         "endianness", G_TYPE_INT, aiff->endianness,
757         "rate", G_TYPE_INT, aiff->rate, NULL);
758   } else {
759     caps = gst_caps_new_simple ("audio/x-raw-int",
760         "width", G_TYPE_INT, aiff->width,
761         "depth", G_TYPE_INT, aiff->depth,
762         "channels", G_TYPE_INT, aiff->channels,
763         "endianness", G_TYPE_INT, aiff->endianness,
764         "rate", G_TYPE_INT, aiff->rate, "signed", G_TYPE_BOOLEAN, TRUE, NULL);
765   }
766
767   GST_DEBUG_OBJECT (aiff, "Created caps: %" GST_PTR_FORMAT, caps);
768   return caps;
769 }
770
771 static GstFlowReturn
772 gst_aiff_parse_stream_headers (GstAiffParse * aiff)
773 {
774   GstFlowReturn res;
775   GstBuffer *buf;
776   guint32 tag, size;
777   gboolean gotdata = FALSE;
778   gboolean done = FALSE;
779   GstEvent **event_p;
780   GstFormat bformat;
781   gint64 upstream_size = 0;
782
783   bformat = GST_FORMAT_BYTES;
784   gst_pad_query_peer_duration (aiff->sinkpad, &bformat, &upstream_size);
785   GST_DEBUG_OBJECT (aiff, "upstream size %" G_GUINT64_FORMAT, upstream_size);
786
787   /* loop headers until we get data */
788   while (!done) {
789     if (aiff->streaming) {
790       if (!gst_aiff_parse_peek_chunk_info (aiff, &tag, &size))
791         return GST_FLOW_OK;
792     } else {
793       if ((res =
794               gst_pad_pull_range (aiff->sinkpad, aiff->offset, 8,
795                   &buf)) != GST_FLOW_OK)
796         goto header_read_error;
797       tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
798       size = GST_READ_UINT32_BE (GST_BUFFER_DATA (buf) + 4);
799     }
800
801     GST_INFO_OBJECT (aiff,
802         "Got TAG: %" GST_FOURCC_FORMAT ", offset %" G_GUINT64_FORMAT,
803         GST_FOURCC_ARGS (tag), aiff->offset);
804
805     /* We just keep reading chunks until we find the one we're interested in.
806      */
807     switch (tag) {
808       case GST_MAKE_FOURCC ('C', 'O', 'M', 'M'):{
809         if (aiff->streaming) {
810           if (!gst_aiff_parse_peek_chunk (aiff, &tag, &size))
811             return GST_FLOW_OK;
812
813           gst_adapter_flush (aiff->adapter, 8);
814           aiff->offset += 8;
815
816           buf = gst_adapter_take_buffer (aiff->adapter, size);
817         } else {
818           if ((res = gst_aiff_parse_read_chunk (aiff,
819                       &aiff->offset, &tag, &buf)) != GST_FLOW_OK)
820             return res;
821         }
822
823         if (!gst_aiff_parse_parse_comm (aiff, buf)) {
824           gst_buffer_unref (buf);
825           goto parse_header_error;
826         }
827
828         gst_buffer_unref (buf);
829
830         /* do sanity checks of header fields */
831         if (aiff->channels == 0)
832           goto no_channels;
833         if (aiff->rate == 0)
834           goto no_rate;
835
836         GST_DEBUG_OBJECT (aiff, "creating the caps");
837
838         aiff->caps = gst_aiff_parse_create_caps (aiff);
839         if (!aiff->caps)
840           goto unknown_format;
841
842         gst_pad_set_caps (aiff->srcpad, aiff->caps);
843
844         aiff->bytes_per_sample = aiff->channels * aiff->width / 8;
845         aiff->bps = aiff->bytes_per_sample * aiff->rate;
846
847         if (aiff->bytes_per_sample <= 0)
848           goto no_bytes_per_sample;
849
850         aiff->got_comm = TRUE;
851         break;
852       }
853       case GST_MAKE_FOURCC ('S', 'S', 'N', 'D'):{
854         GstBuffer *ssndbuf = NULL;
855         const guint8 *ssnddata = NULL;
856         guint32 datasize;
857
858         GST_DEBUG_OBJECT (aiff, "Got 'SSND' TAG, size : %d", size);
859
860         /* Now, read the 8-byte header in the SSND chunk */
861         if (aiff->streaming) {
862           if (!gst_aiff_parse_peek_data (aiff, 16, &ssnddata))
863             return GST_FLOW_OK;
864         } else {
865           gst_buffer_unref (buf);
866           if ((res =
867                   gst_pad_pull_range (aiff->sinkpad, aiff->offset, 16,
868                       &ssndbuf)) != GST_FLOW_OK)
869             goto header_read_error;
870           ssnddata = GST_BUFFER_DATA (ssndbuf);
871         }
872
873         aiff->ssnd_offset = GST_READ_UINT32_BE (ssnddata + 8);
874         aiff->ssnd_blocksize = GST_READ_UINT32_BE (ssnddata + 12);
875
876         gotdata = TRUE;
877         if (aiff->streaming) {
878           gst_adapter_flush (aiff->adapter, 16);
879         } else {
880           gst_buffer_unref (ssndbuf);
881         }
882         /* 8 byte chunk header, 8 byte SSND header */
883         aiff->offset += 16;
884
885         datasize = size - 16;
886
887         aiff->datastart = aiff->offset + aiff->ssnd_offset;
888         /* file might be truncated */
889         if (upstream_size) {
890           size = MIN (datasize, (upstream_size - aiff->datastart));
891         }
892         aiff->datasize = (guint64) datasize;
893         aiff->dataleft = (guint64) datasize;
894         aiff->end_offset = datasize + aiff->datastart;
895         if (!aiff->streaming) {
896           /* We will continue looking at chunks until the end - to read tags,
897            * etc. */
898           aiff->offset += datasize;
899         }
900         GST_DEBUG_OBJECT (aiff, "datasize = %d", datasize);
901         if (aiff->streaming) {
902           done = TRUE;
903         }
904         break;
905       }
906       case GST_MAKE_FOURCC ('I', 'D', '3', ' '):{
907         GstTagList *tags;
908
909         if (aiff->streaming) {
910           if (!gst_aiff_parse_peek_chunk (aiff, &tag, &size))
911             return GST_FLOW_OK;
912
913           gst_adapter_flush (aiff->adapter, 8);
914           aiff->offset += 8;
915
916           buf = gst_adapter_take_buffer (aiff->adapter, size);
917         } else {
918           if ((res = gst_aiff_parse_read_chunk (aiff,
919                       &aiff->offset, &tag, &buf)) != GST_FLOW_OK)
920             return res;
921         }
922
923         GST_LOG_OBJECT (aiff, "ID3 chunk of size %u", GST_BUFFER_SIZE (buf));
924
925         tags = gst_tag_list_from_id3v2_tag (buf);
926         gst_buffer_unref (buf);
927
928         GST_INFO_OBJECT (aiff, "ID3 tags: %" GST_PTR_FORMAT, tags);
929
930         if (aiff->tags == NULL) {
931           aiff->tags = tags;
932         } else {
933           gst_tag_list_insert (aiff->tags, tags, GST_TAG_MERGE_APPEND);
934           gst_tag_list_free (tags);
935         }
936         break;
937       }
938       default:
939         gst_aiff_parse_ignore_chunk (aiff, buf, tag, size);
940     }
941
942     if (upstream_size && (aiff->offset >= upstream_size)) {
943       /* Now we have gone through the whole file */
944       done = TRUE;
945     }
946   }
947
948   /* We read all the chunks (in pull mode) or reached the SSND chunk
949    * (in push mode). We must have both COMM and SSND now; error out 
950    * otherwise.
951    */
952   if (!aiff->got_comm) {
953     GST_WARNING_OBJECT (aiff, "Failed to find COMM chunk");
954     goto no_header;
955   }
956   if (!gotdata) {
957     GST_WARNING_OBJECT (aiff, "Failed to find SSND chunk");
958     goto no_data;
959   }
960
961   GST_DEBUG_OBJECT (aiff, "Finished parsing headers");
962
963   if (gst_aiff_parse_calculate_duration (aiff)) {
964     gst_segment_init (&aiff->segment, GST_FORMAT_TIME);
965     gst_segment_set_duration (&aiff->segment, GST_FORMAT_TIME, aiff->duration);
966   } else {
967     /* no bitrate, let downstream peer do the math, we'll feed it bytes. */
968     gst_segment_init (&aiff->segment, GST_FORMAT_BYTES);
969     gst_segment_set_duration (&aiff->segment, GST_FORMAT_BYTES, aiff->datasize);
970   }
971
972   /* now we have all the info to perform a pending seek if any, if no
973    * event, this will still do the right thing and it will also send
974    * the right newsegment event downstream. */
975   gst_aiff_parse_perform_seek (aiff, aiff->seek_event);
976   /* remove pending event */
977   event_p = &aiff->seek_event;
978   gst_event_replace (event_p, NULL);
979
980   /* we just started, we are discont */
981   aiff->discont = TRUE;
982
983   aiff->state = AIFF_PARSE_DATA;
984
985   return GST_FLOW_OK;
986
987   /* ERROR */
988 no_header:
989   {
990     GST_ELEMENT_ERROR (aiff, STREAM, TYPE_NOT_FOUND, (NULL),
991         ("Invalid AIFF header (no COMM found)"));
992     return GST_FLOW_ERROR;
993   }
994 no_data:
995   {
996     GST_ELEMENT_ERROR (aiff, STREAM, TYPE_NOT_FOUND, (NULL),
997         ("Invalid AIFF: no SSND found"));
998     return GST_FLOW_ERROR;
999   }
1000 parse_header_error:
1001   {
1002     GST_ELEMENT_ERROR (aiff, STREAM, DEMUX, (NULL),
1003         ("Couldn't parse audio header"));
1004     return GST_FLOW_ERROR;
1005   }
1006 no_channels:
1007   {
1008     GST_ELEMENT_ERROR (aiff, STREAM, FAILED, (NULL),
1009         ("Stream claims to contain no channels - invalid data"));
1010     return GST_FLOW_ERROR;
1011   }
1012 no_rate:
1013   {
1014     GST_ELEMENT_ERROR (aiff, STREAM, FAILED, (NULL),
1015         ("Stream with sample_rate == 0 - invalid data"));
1016     return GST_FLOW_ERROR;
1017   }
1018 no_bytes_per_sample:
1019   {
1020     GST_ELEMENT_ERROR (aiff, STREAM, FAILED, (NULL),
1021         ("Could not caluclate bytes per sample - invalid data"));
1022     return GST_FLOW_ERROR;
1023   }
1024 unknown_format:
1025   {
1026     GST_ELEMENT_ERROR (aiff, STREAM, TYPE_NOT_FOUND, (NULL),
1027         ("No caps found for format 0x%x, %d channels, %d Hz",
1028             aiff->format, aiff->channels, aiff->rate));
1029     return GST_FLOW_ERROR;
1030   }
1031 header_read_error:
1032   {
1033     GST_ELEMENT_ERROR (aiff, STREAM, DEMUX, (NULL),
1034         ("Couldn't read in header"));
1035     return GST_FLOW_ERROR;
1036   }
1037 }
1038
1039 /*
1040  * Read AIFF file tag when streaming
1041  */
1042 static GstFlowReturn
1043 gst_aiff_parse_parse_stream_init (GstAiffParse * aiff)
1044 {
1045   if (gst_adapter_available (aiff->adapter) >= 12) {
1046     GstBuffer *tmp;
1047
1048     /* _take flushes the data */
1049     tmp = gst_adapter_take_buffer (aiff->adapter, 12);
1050
1051     GST_DEBUG ("Parsing aiff header");
1052     if (!gst_aiff_parse_parse_file_header (aiff, tmp))
1053       return GST_FLOW_ERROR;
1054
1055     aiff->offset += 12;
1056     /* Go to next state */
1057     aiff->state = AIFF_PARSE_HEADER;
1058   }
1059   return GST_FLOW_OK;
1060 }
1061
1062 /* handle an event sent directly to the element.
1063  *
1064  * This event can be sent either in the READY state or the
1065  * >READY state. The only event of interest really is the seek
1066  * event.
1067  *
1068  * In the READY state we can only store the event and try to
1069  * respect it when going to PAUSED. We assume we are in the
1070  * READY state when our parsing state != AIFF_PARSE_DATA.
1071  *
1072  * When we are steaming, we can simply perform the seek right
1073  * away.
1074  */
1075 static gboolean
1076 gst_aiff_parse_send_event (GstElement * element, GstEvent * event)
1077 {
1078   GstAiffParse *aiff = GST_AIFF_PARSE (element);
1079   gboolean res = FALSE;
1080   GstEvent **event_p;
1081
1082   GST_DEBUG_OBJECT (aiff, "received event %s", GST_EVENT_TYPE_NAME (event));
1083
1084   switch (GST_EVENT_TYPE (event)) {
1085     case GST_EVENT_SEEK:
1086       if (aiff->state == AIFF_PARSE_DATA) {
1087         /* we can handle the seek directly when streaming data */
1088         res = gst_aiff_parse_perform_seek (aiff, event);
1089       } else {
1090         GST_DEBUG_OBJECT (aiff, "queuing seek for later");
1091
1092         event_p = &aiff->seek_event;
1093         gst_event_replace (event_p, event);
1094
1095         /* we always return true */
1096         res = TRUE;
1097       }
1098       break;
1099     default:
1100       break;
1101   }
1102   gst_event_unref (event);
1103   return res;
1104 }
1105
1106 #define MAX_BUFFER_SIZE 4096
1107
1108 static GstFlowReturn
1109 gst_aiff_parse_stream_data (GstAiffParse * aiff)
1110 {
1111   GstBuffer *buf = NULL;
1112   GstFlowReturn res = GST_FLOW_OK;
1113   guint64 desired, obtained;
1114   GstClockTime timestamp, next_timestamp, duration;
1115   guint64 pos, nextpos;
1116
1117 iterate_adapter:
1118   GST_LOG_OBJECT (aiff,
1119       "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT " , dataleft: %"
1120       G_GINT64_FORMAT, aiff->offset, aiff->end_offset, aiff->dataleft);
1121
1122   /* Get the next n bytes and output them */
1123   if (aiff->dataleft == 0 || aiff->dataleft < aiff->bytes_per_sample)
1124     goto found_eos;
1125
1126   /* scale the amount of data by the segment rate so we get equal
1127    * amounts of data regardless of the playback rate */
1128   desired =
1129       MIN (gst_guint64_to_gdouble (aiff->dataleft),
1130       MAX_BUFFER_SIZE * aiff->segment.abs_rate);
1131
1132   if (desired >= aiff->bytes_per_sample && aiff->bytes_per_sample > 0)
1133     desired -= (desired % aiff->bytes_per_sample);
1134
1135   GST_LOG_OBJECT (aiff, "Fetching %" G_GINT64_FORMAT " bytes of data "
1136       "from the sinkpad", desired);
1137
1138   if (aiff->streaming) {
1139     guint avail = gst_adapter_available (aiff->adapter);
1140
1141     if (avail < desired) {
1142       GST_LOG_OBJECT (aiff, "Got only %d bytes of data from the sinkpad",
1143           avail);
1144       return GST_FLOW_OK;
1145     }
1146
1147     buf = gst_adapter_take_buffer (aiff->adapter, desired);
1148   } else {
1149     if ((res = gst_pad_pull_range (aiff->sinkpad, aiff->offset,
1150                 desired, &buf)) != GST_FLOW_OK)
1151       goto pull_error;
1152   }
1153
1154   /* If we have a pending close/start segment, send it now. */
1155   if (G_UNLIKELY (aiff->close_segment != NULL)) {
1156     gst_pad_push_event (aiff->srcpad, aiff->close_segment);
1157     aiff->close_segment = NULL;
1158   }
1159   if (G_UNLIKELY (aiff->start_segment != NULL)) {
1160     gst_pad_push_event (aiff->srcpad, aiff->start_segment);
1161     aiff->start_segment = NULL;
1162   }
1163   if (G_UNLIKELY (aiff->tags != NULL)) {
1164     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (aiff), aiff->srcpad,
1165         aiff->tags);
1166     aiff->tags = NULL;
1167   }
1168
1169   obtained = GST_BUFFER_SIZE (buf);
1170
1171   /* our positions in bytes */
1172   pos = aiff->offset - aiff->datastart;
1173   nextpos = pos + obtained;
1174
1175   /* update offsets, does not overflow. */
1176   GST_BUFFER_OFFSET (buf) = pos / aiff->bytes_per_sample;
1177   GST_BUFFER_OFFSET_END (buf) = nextpos / aiff->bytes_per_sample;
1178
1179   if (aiff->bps > 0) {
1180     /* and timestamps if we have a bitrate, be careful for overflows */
1181     timestamp =
1182         gst_util_uint64_scale_ceil (pos, GST_SECOND, (guint64) aiff->bps);
1183     next_timestamp =
1184         gst_util_uint64_scale_ceil (nextpos, GST_SECOND, (guint64) aiff->bps);
1185     duration = next_timestamp - timestamp;
1186
1187     /* update current running segment position */
1188     gst_segment_set_last_stop (&aiff->segment, GST_FORMAT_TIME, next_timestamp);
1189   } else {
1190     /* no bitrate, all we know is that the first sample has timestamp 0, all
1191      * other positions and durations have unknown timestamp. */
1192     if (pos == 0)
1193       timestamp = 0;
1194     else
1195       timestamp = GST_CLOCK_TIME_NONE;
1196     duration = GST_CLOCK_TIME_NONE;
1197     /* update current running segment position with byte offset */
1198     gst_segment_set_last_stop (&aiff->segment, GST_FORMAT_BYTES, nextpos);
1199   }
1200   if (aiff->discont) {
1201     GST_DEBUG_OBJECT (aiff, "marking DISCONT");
1202     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1203     aiff->discont = FALSE;
1204   }
1205
1206   GST_BUFFER_TIMESTAMP (buf) = timestamp;
1207   GST_BUFFER_DURATION (buf) = duration;
1208   gst_buffer_set_caps (buf, aiff->caps);
1209
1210   GST_LOG_OBJECT (aiff,
1211       "Got buffer. timestamp:%" GST_TIME_FORMAT " , duration:%" GST_TIME_FORMAT
1212       ", size:%u", GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration),
1213       GST_BUFFER_SIZE (buf));
1214
1215   if ((res = gst_pad_push (aiff->srcpad, buf)) != GST_FLOW_OK)
1216     goto push_error;
1217
1218   if (obtained < aiff->dataleft) {
1219     aiff->offset += obtained;
1220     aiff->dataleft -= obtained;
1221   } else {
1222     aiff->offset += aiff->dataleft;
1223     aiff->dataleft = 0;
1224   }
1225
1226   /* Iterate until need more data, so adapter size won't grow */
1227   if (aiff->streaming) {
1228     GST_LOG_OBJECT (aiff,
1229         "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT, aiff->offset,
1230         aiff->end_offset);
1231     goto iterate_adapter;
1232   }
1233   return res;
1234
1235   /* ERROR */
1236 found_eos:
1237   {
1238     GST_DEBUG_OBJECT (aiff, "found EOS");
1239     return GST_FLOW_UNEXPECTED;
1240   }
1241 pull_error:
1242   {
1243     /* check if we got EOS */
1244     if (res == GST_FLOW_UNEXPECTED)
1245       goto found_eos;
1246
1247     GST_WARNING_OBJECT (aiff,
1248         "Error getting %" G_GINT64_FORMAT " bytes from the "
1249         "sinkpad (dataleft = %" G_GINT64_FORMAT ")", desired, aiff->dataleft);
1250     return res;
1251   }
1252 push_error:
1253   {
1254     GST_INFO_OBJECT (aiff,
1255         "Error pushing on srcpad %s:%s, reason %s, is linked? = %d",
1256         GST_DEBUG_PAD_NAME (aiff->srcpad), gst_flow_get_name (res),
1257         gst_pad_is_linked (aiff->srcpad));
1258     return res;
1259   }
1260 }
1261
1262 static void
1263 gst_aiff_parse_loop (GstPad * pad)
1264 {
1265   GstFlowReturn ret;
1266   GstAiffParse *aiff = GST_AIFF_PARSE (GST_PAD_PARENT (pad));
1267
1268   GST_LOG_OBJECT (aiff, "process data");
1269
1270   switch (aiff->state) {
1271     case AIFF_PARSE_START:
1272       GST_INFO_OBJECT (aiff, "AIFF_PARSE_START");
1273       if ((ret = gst_aiff_parse_stream_init (aiff)) != GST_FLOW_OK)
1274         goto pause;
1275
1276       aiff->state = AIFF_PARSE_HEADER;
1277       /* fall-through */
1278
1279     case AIFF_PARSE_HEADER:
1280       GST_INFO_OBJECT (aiff, "AIFF_PARSE_HEADER");
1281       if ((ret = gst_aiff_parse_stream_headers (aiff)) != GST_FLOW_OK)
1282         goto pause;
1283
1284       aiff->state = AIFF_PARSE_DATA;
1285       GST_INFO_OBJECT (aiff, "AIFF_PARSE_DATA");
1286       /* fall-through */
1287
1288     case AIFF_PARSE_DATA:
1289       if ((ret = gst_aiff_parse_stream_data (aiff)) != GST_FLOW_OK)
1290         goto pause;
1291       break;
1292     default:
1293       g_assert_not_reached ();
1294   }
1295   return;
1296
1297   /* ERRORS */
1298 pause:
1299   {
1300     const gchar *reason = gst_flow_get_name (ret);
1301
1302     GST_DEBUG_OBJECT (aiff, "pausing task, reason %s", reason);
1303     aiff->segment_running = FALSE;
1304     gst_pad_pause_task (pad);
1305
1306     if (ret == GST_FLOW_UNEXPECTED) {
1307       /* perform EOS logic */
1308       if (aiff->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1309         GstClockTime stop;
1310
1311         if ((stop = aiff->segment.stop) == -1)
1312           stop = aiff->segment.duration;
1313
1314         gst_element_post_message (GST_ELEMENT_CAST (aiff),
1315             gst_message_new_segment_done (GST_OBJECT_CAST (aiff),
1316                 aiff->segment.format, stop));
1317         gst_pad_push_event (aiff->srcpad,
1318             gst_evnet_new_segment_done (aiff->segment.format, stop));
1319       } else {
1320         gst_pad_push_event (aiff->srcpad, gst_event_new_eos ());
1321       }
1322     } else if (ret < GST_FLOW_UNEXPECTED || ret == GST_FLOW_NOT_LINKED) {
1323       /* for fatal errors we post an error message, post the error
1324        * first so the app knows about the error first. */
1325       GST_ELEMENT_ERROR (aiff, STREAM, FAILED,
1326           (_("Internal data flow error.")),
1327           ("streaming task paused, reason %s (%d)", reason, ret));
1328       gst_pad_push_event (aiff->srcpad, gst_event_new_eos ());
1329     }
1330     return;
1331   }
1332 }
1333
1334 static GstFlowReturn
1335 gst_aiff_parse_chain (GstPad * pad, GstBuffer * buf)
1336 {
1337   GstFlowReturn ret;
1338   GstAiffParse *aiff = GST_AIFF_PARSE (GST_PAD_PARENT (pad));
1339
1340   GST_LOG_OBJECT (aiff, "adapter_push %u bytes", GST_BUFFER_SIZE (buf));
1341
1342   gst_adapter_push (aiff->adapter, buf);
1343
1344   switch (aiff->state) {
1345     case AIFF_PARSE_START:
1346       GST_INFO_OBJECT (aiff, "AIFF_PARSE_START");
1347       if ((ret = gst_aiff_parse_parse_stream_init (aiff)) != GST_FLOW_OK)
1348         goto done;
1349
1350       if (aiff->state != AIFF_PARSE_HEADER)
1351         break;
1352
1353       /* otherwise fall-through */
1354     case AIFF_PARSE_HEADER:
1355       GST_INFO_OBJECT (aiff, "AIFF_PARSE_HEADER");
1356       if ((ret = gst_aiff_parse_stream_headers (aiff)) != GST_FLOW_OK)
1357         goto done;
1358
1359       if (!aiff->got_comm || aiff->datastart == 0)
1360         break;
1361
1362       aiff->state = AIFF_PARSE_DATA;
1363       GST_INFO_OBJECT (aiff, "AIFF_PARSE_DATA");
1364
1365       /* fall-through */
1366     case AIFF_PARSE_DATA:
1367       if ((ret = gst_aiff_parse_stream_data (aiff)) != GST_FLOW_OK)
1368         goto done;
1369       break;
1370     default:
1371       g_return_val_if_reached (GST_FLOW_ERROR);
1372   }
1373 done:
1374   return ret;
1375 }
1376
1377 static gboolean
1378 gst_aiff_parse_pad_convert (GstPad * pad,
1379     GstFormat src_format, gint64 src_value,
1380     GstFormat * dest_format, gint64 * dest_value)
1381 {
1382   GstAiffParse *aiffparse;
1383   gboolean res = TRUE;
1384
1385   aiffparse = GST_AIFF_PARSE (GST_PAD_PARENT (pad));
1386
1387   if (*dest_format == src_format) {
1388     *dest_value = src_value;
1389     return TRUE;
1390   }
1391
1392   if (aiffparse->bytes_per_sample <= 0)
1393     return FALSE;
1394
1395   GST_INFO_OBJECT (aiffparse, "converting value from %s to %s",
1396       gst_format_get_name (src_format), gst_format_get_name (*dest_format));
1397
1398   switch (src_format) {
1399     case GST_FORMAT_BYTES:
1400       switch (*dest_format) {
1401         case GST_FORMAT_DEFAULT:
1402           *dest_value = src_value / aiffparse->bytes_per_sample;
1403           break;
1404         case GST_FORMAT_TIME:
1405           if (aiffparse->bps > 0) {
1406             *dest_value = gst_util_uint64_scale_ceil (src_value, GST_SECOND,
1407                 (guint64) aiffparse->bps);
1408             break;
1409           }
1410           /* Else fallthrough */
1411         default:
1412           res = FALSE;
1413           goto done;
1414       }
1415       break;
1416
1417     case GST_FORMAT_DEFAULT:
1418       switch (*dest_format) {
1419         case GST_FORMAT_BYTES:
1420           *dest_value = src_value * aiffparse->bytes_per_sample;
1421           break;
1422         case GST_FORMAT_TIME:
1423           *dest_value = gst_util_uint64_scale (src_value, GST_SECOND,
1424               (guint64) aiffparse->rate);
1425           break;
1426         default:
1427           res = FALSE;
1428           goto done;
1429       }
1430       break;
1431
1432     case GST_FORMAT_TIME:
1433       switch (*dest_format) {
1434         case GST_FORMAT_BYTES:
1435           if (aiffparse->bps > 0) {
1436             *dest_value = gst_util_uint64_scale (src_value,
1437                 (guint64) aiffparse->bps, GST_SECOND);
1438             break;
1439           }
1440           /* Else fallthrough */
1441           break;
1442         case GST_FORMAT_DEFAULT:
1443           *dest_value = gst_util_uint64_scale (src_value,
1444               (guint64) aiffparse->rate, GST_SECOND);
1445           break;
1446         default:
1447           res = FALSE;
1448           goto done;
1449       }
1450       break;
1451
1452     default:
1453       res = FALSE;
1454       goto done;
1455   }
1456
1457 done:
1458   return res;
1459
1460 }
1461
1462 static const GstQueryType *
1463 gst_aiff_parse_get_query_types (GstPad * pad)
1464 {
1465   static const GstQueryType types[] = {
1466     GST_QUERY_DURATION,
1467     GST_QUERY_CONVERT,
1468     GST_QUERY_SEEKING,
1469     0
1470   };
1471
1472   return types;
1473 }
1474
1475 /* handle queries for location and length in requested format */
1476 static gboolean
1477 gst_aiff_parse_pad_query (GstPad * pad, GstQuery * query)
1478 {
1479   gboolean res = TRUE;
1480   GstAiffParse *aiff = GST_AIFF_PARSE (gst_pad_get_parent (pad));
1481
1482   /* only if we know */
1483   if (aiff->state != AIFF_PARSE_DATA) {
1484     gst_object_unref (aiff);
1485     return FALSE;
1486   }
1487
1488   switch (GST_QUERY_TYPE (query)) {
1489     case GST_QUERY_DURATION:
1490     {
1491       gint64 duration = 0;
1492       GstFormat format;
1493
1494       gst_query_parse_duration (query, &format, NULL);
1495
1496       switch (format) {
1497         case GST_FORMAT_TIME:{
1498           if ((res = gst_aiff_parse_calculate_duration (aiff))) {
1499             duration = aiff->duration;
1500           }
1501           break;
1502         }
1503         default:
1504           format = GST_FORMAT_BYTES;
1505           duration = aiff->datasize;
1506           break;
1507       }
1508       gst_query_set_duration (query, format, duration);
1509       break;
1510     }
1511     case GST_QUERY_CONVERT:
1512     {
1513       gint64 srcvalue, dstvalue;
1514       GstFormat srcformat, dstformat;
1515
1516       gst_query_parse_convert (query, &srcformat, &srcvalue,
1517           &dstformat, &dstvalue);
1518       res = gst_aiff_parse_pad_convert (pad, srcformat, srcvalue,
1519           &dstformat, &dstvalue);
1520       if (res)
1521         gst_query_set_convert (query, srcformat, srcvalue, dstformat, dstvalue);
1522       break;
1523     }
1524     case GST_QUERY_SEEKING:{
1525       GstFormat fmt;
1526
1527       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1528       if (fmt == GST_FORMAT_TIME) {
1529         gboolean seekable = TRUE;
1530
1531         if (!gst_aiff_parse_calculate_duration (aiff)) {
1532           seekable = FALSE;
1533         }
1534         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1535             0, aiff->duration);
1536         res = TRUE;
1537       }
1538       break;
1539     }
1540     default:
1541       res = gst_pad_query_default (pad, query);
1542       break;
1543   }
1544   gst_object_unref (aiff);
1545   return res;
1546 }
1547
1548 static gboolean
1549 gst_aiff_parse_srcpad_event (GstPad * pad, GstEvent * event)
1550 {
1551   GstAiffParse *aiffparse = GST_AIFF_PARSE (gst_pad_get_parent (pad));
1552   gboolean res = FALSE;
1553
1554   GST_DEBUG_OBJECT (aiffparse, "%s event", GST_EVENT_TYPE_NAME (event));
1555
1556   switch (GST_EVENT_TYPE (event)) {
1557     case GST_EVENT_SEEK:
1558       /* can only handle events when we are in the data state */
1559       if (aiffparse->state == AIFF_PARSE_DATA) {
1560         res = gst_aiff_parse_perform_seek (aiffparse, event);
1561       }
1562       gst_event_unref (event);
1563       break;
1564     default:
1565       res = gst_pad_push_event (aiffparse->sinkpad, event);
1566       break;
1567   }
1568   gst_object_unref (aiffparse);
1569   return res;
1570 }
1571
1572 static gboolean
1573 gst_aiff_parse_sink_activate (GstPad * sinkpad)
1574 {
1575   GstAiffParse *aiff = GST_AIFF_PARSE (gst_pad_get_parent (sinkpad));
1576   gboolean res;
1577
1578   if (aiff->adapter)
1579     g_object_unref (aiff->adapter);
1580
1581   if (gst_pad_check_pull_range (sinkpad)) {
1582     GST_DEBUG ("going to pull mode");
1583     aiff->streaming = FALSE;
1584     aiff->adapter = NULL;
1585     res = gst_pad_activate_pull (sinkpad, TRUE);
1586   } else {
1587     GST_DEBUG ("going to push (streaming) mode");
1588     aiff->streaming = TRUE;
1589     aiff->adapter = gst_adapter_new ();
1590     res = gst_pad_activate_push (sinkpad, TRUE);
1591   }
1592   gst_object_unref (aiff);
1593   return res;
1594 }
1595
1596
1597 static gboolean
1598 gst_aiff_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
1599 {
1600   GstAiffParse *aiff = GST_AIFF_PARSE (GST_OBJECT_PARENT (sinkpad));
1601
1602   if (active) {
1603     aiff->segment_running = TRUE;
1604     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_aiff_parse_loop,
1605         sinkpad, NULL);
1606   } else {
1607     aiff->segment_running = FALSE;
1608     return gst_pad_stop_task (sinkpad);
1609   }
1610 };
1611
1612 static GstStateChangeReturn
1613 gst_aiff_parse_change_state (GstElement * element, GstStateChange transition)
1614 {
1615   GstStateChangeReturn ret;
1616   GstAiffParse *aiff = GST_AIFF_PARSE (element);
1617
1618   switch (transition) {
1619     case GST_STATE_CHANGE_NULL_TO_READY:
1620       break;
1621     case GST_STATE_CHANGE_READY_TO_PAUSED:
1622       gst_aiff_parse_reset (aiff);
1623       break;
1624     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1625       break;
1626     default:
1627       break;
1628   }
1629
1630   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1631
1632   switch (transition) {
1633     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1634       break;
1635     case GST_STATE_CHANGE_PAUSED_TO_READY:
1636       gst_aiff_parse_reset (aiff);
1637       break;
1638     case GST_STATE_CHANGE_READY_TO_NULL:
1639       break;
1640     default:
1641       break;
1642   }
1643   return ret;
1644 }