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