ext/wavpack/gstwavpackparse.c: Always use GSlice as we actually depend on GLib 2...
[platform/upstream/gst-plugins-good.git] / ext / wavpack / gstwavpackparse.c
1 /* GStreamer wavpack plugin
2  * Copyright (c) 2005 Arwed v. Merkatz <v.merkatz@gmx.net>
3  * Copyright (c) 2006 Tim-Philipp Müller <tim centricular net>
4  * Copyright (c) 2006 Sebastian Dröge <slomo@circular-chaos.org>
5  *
6  * gstwavpackparse.c: wavpack file parser
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-wavpackparse
26  *
27  * <refsect2>
28  * WavpackParse takes raw, unframed Wavpack streams and splits them into
29  * single Wavpack chunks with information like bit depth and the position
30  * in the stream.
31  * <ulink url="http://www.wavpack.com/">Wavpack</ulink> is an open-source
32  * audio codec that features both lossless and lossy encoding.
33  * <title>Example launch line</title>
34  * <para>
35  * <programlisting>
36  * gst-launch filesrc location=test.wv ! wavpackparse ! wavpackdec ! fakesink
37  * </programlisting>
38  * This pipeline decodes the Wavpack file test.wv into raw audio buffers.
39  * </para>
40  * </refsect2>
41  */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif
46 #include <gst/gst.h>
47 #include <gst/gst-i18n-plugin.h>
48
49 #include <math.h>
50 #include <string.h>
51
52 #include <wavpack/wavpack.h>
53 #include "gstwavpackparse.h"
54 #include "gstwavpackstreamreader.h"
55 #include "gstwavpackcommon.h"
56
57 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_parse_debug);
58 #define GST_CAT_DEFAULT gst_wavpack_parse_debug
59
60 static inline GstWavpackParseIndexEntry *
61 gst_wavpack_parse_index_entry_new ()
62 {
63   return g_slice_new (GstWavpackParseIndexEntry);
64 }
65
66 static inline void
67 gst_wavpack_parse_index_entry_free (GstWavpackParseIndexEntry * entry)
68 {
69   g_slice_free (GstWavpackParseIndexEntry, entry);
70 }
71
72 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
73     GST_PAD_SINK,
74     GST_PAD_ALWAYS,
75     GST_STATIC_CAPS ("audio/x-wavpack, "
76         "framed = (boolean) false; "
77         "audio/x-wavpack-correction, " "framed = (boolean) false")
78     );
79
80 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
81     GST_PAD_SRC,
82     GST_PAD_SOMETIMES,
83     GST_STATIC_CAPS ("audio/x-wavpack, "
84         "width = (int) [ 1, 32 ], "
85         "channels = (int) [ 1, 8 ], "
86         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) true")
87     );
88
89 static GstStaticPadTemplate wvc_src_factory = GST_STATIC_PAD_TEMPLATE ("wvcsrc",
90     GST_PAD_SRC,
91     GST_PAD_SOMETIMES,
92     GST_STATIC_CAPS ("audio/x-wavpack-correction, " "framed = (boolean) true")
93     );
94
95 static gboolean gst_wavpack_parse_sink_activate (GstPad * sinkpad);
96 static gboolean
97 gst_wavpack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active);
98
99 static void gst_wavpack_parse_loop (GstElement * element);
100 static GstStateChangeReturn gst_wavpack_parse_change_state (GstElement *
101     element, GstStateChange transition);
102 static void gst_wavpack_parse_reset (GstWavpackParse * parse);
103 static gint64 gst_wavpack_parse_get_upstream_length (GstWavpackParse * wvparse);
104 static GstBuffer *gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse,
105     gint64 offset, guint size, GstFlowReturn * flow);
106 static GstFlowReturn gst_wavpack_parse_chain (GstPad * pad, GstBuffer * buf);
107
108 GST_BOILERPLATE (GstWavpackParse, gst_wavpack_parse, GstElement,
109     GST_TYPE_ELEMENT);
110
111 static void
112 gst_wavpack_parse_base_init (gpointer klass)
113 {
114   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
115
116   gst_element_class_add_pad_template (element_class,
117       gst_static_pad_template_get (&src_factory));
118   gst_element_class_add_pad_template (element_class,
119       gst_static_pad_template_get (&wvc_src_factory));
120   gst_element_class_add_pad_template (element_class,
121       gst_static_pad_template_get (&sink_factory));
122
123   gst_element_class_set_details_simple (element_class, "Wavpack parser",
124       "Codec/Demuxer/Audio",
125       "Parses Wavpack files",
126       "Arwed v. Merkatz <v.merkatz@gmx.net>, "
127       "Sebastian Dröge <slomo@circular-chaos.org>");
128 }
129
130 static void
131 gst_wavpack_parse_finalize (GObject * object)
132 {
133   gst_wavpack_parse_reset (GST_WAVPACK_PARSE (object));
134
135   G_OBJECT_CLASS (parent_class)->finalize (object);
136 }
137
138 static void
139 gst_wavpack_parse_class_init (GstWavpackParseClass * klass)
140 {
141   GObjectClass *gobject_class;
142   GstElementClass *gstelement_class;
143
144   gobject_class = (GObjectClass *) klass;
145   gstelement_class = (GstElementClass *) klass;
146
147   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_wavpack_parse_finalize);
148   gstelement_class->change_state =
149       GST_DEBUG_FUNCPTR (gst_wavpack_parse_change_state);
150 }
151
152 static GstWavpackParseIndexEntry *
153 gst_wavpack_parse_index_get_last_entry (GstWavpackParse * wvparse)
154 {
155   g_assert (wvparse->entries != NULL);
156
157   return wvparse->entries->data;
158 }
159
160 static GstWavpackParseIndexEntry *
161 gst_wavpack_parse_index_get_entry_from_sample (GstWavpackParse * wvparse,
162     gint64 sample_offset)
163 {
164   gint i;
165   GSList *node;
166
167   if (wvparse->entries == NULL)
168     return NULL;
169
170   for (node = wvparse->entries, i = 0; node; node = node->next, i++) {
171     GstWavpackParseIndexEntry *entry;
172
173     entry = node->data;
174
175     GST_LOG_OBJECT (wvparse, "Index entry %03u: sample %" G_GINT64_FORMAT " @"
176         " byte %" G_GINT64_FORMAT, i, entry->sample_offset, entry->byte_offset);
177
178     if (entry->sample_offset <= sample_offset &&
179         sample_offset < entry->sample_offset_end) {
180       GST_LOG_OBJECT (wvparse, "found match");
181       return entry;
182     }
183
184     /* as the list is sorted and we first look at the latest entry
185      * we can abort searching for an entry if the sample we want is
186      * after the latest one */
187     if (sample_offset >= entry->sample_offset_end)
188       break;
189   }
190   GST_LOG_OBJECT (wvparse, "no match in index");
191   return NULL;
192 }
193
194 static void
195 gst_wavpack_parse_index_append_entry (GstWavpackParse * wvparse,
196     gint64 byte_offset, gint64 sample_offset, gint64 num_samples)
197 {
198   GstWavpackParseIndexEntry *entry;
199
200   /* do we have this one already? */
201   if (wvparse->entries) {
202     entry = gst_wavpack_parse_index_get_last_entry (wvparse);
203     if (entry->byte_offset >= byte_offset
204         || entry->sample_offset >= sample_offset)
205       return;
206   }
207
208   GST_LOG_OBJECT (wvparse, "Adding index entry %8" G_GINT64_FORMAT " - %"
209       GST_TIME_FORMAT " @ offset 0x%08" G_GINT64_MODIFIER "x", sample_offset,
210       GST_TIME_ARGS (gst_util_uint64_scale_int (sample_offset,
211               GST_SECOND, wvparse->samplerate)), byte_offset);
212
213   entry = gst_wavpack_parse_index_entry_new ();
214   entry->byte_offset = byte_offset;
215   entry->sample_offset = sample_offset;
216   entry->sample_offset_end = sample_offset + num_samples;
217   wvparse->entries = g_slist_prepend (wvparse->entries, entry);
218 }
219
220 static void
221 gst_wavpack_parse_reset (GstWavpackParse * parse)
222 {
223   parse->total_samples = -1;
224   parse->samplerate = 0;
225   parse->channels = 0;
226
227   gst_segment_init (&parse->segment, GST_FORMAT_UNDEFINED);
228   parse->next_block_index = 0;
229
230   parse->current_offset = 0;
231   parse->need_newsegment = TRUE;
232   parse->discont = TRUE;
233   parse->upstream_length = -1;
234
235   if (parse->entries) {
236     g_slist_foreach (parse->entries, (GFunc) gst_wavpack_parse_index_entry_free,
237         NULL);
238     g_slist_free (parse->entries);
239     parse->entries = NULL;
240   }
241
242   if (parse->adapter) {
243     gst_adapter_clear (parse->adapter);
244     g_object_unref (parse->adapter);
245     parse->adapter = NULL;
246   }
247
248   if (parse->srcpad != NULL) {
249     gboolean res;
250
251     GST_DEBUG_OBJECT (parse, "Removing src pad");
252     res = gst_element_remove_pad (GST_ELEMENT (parse), parse->srcpad);
253     g_return_if_fail (res != FALSE);
254     gst_object_unref (parse->srcpad);
255     parse->srcpad = NULL;
256   }
257
258   g_list_foreach (parse->queued_events, (GFunc) gst_mini_object_unref, NULL);
259   g_list_free (parse->queued_events);
260   parse->queued_events = NULL;
261
262   if (parse->pending_buffer)
263     gst_buffer_unref (parse->pending_buffer);
264
265   parse->pending_buffer = NULL;
266 }
267
268 static const GstQueryType *
269 gst_wavpack_parse_get_src_query_types (GstPad * pad)
270 {
271   static const GstQueryType types[] = {
272     GST_QUERY_POSITION,
273     GST_QUERY_DURATION,
274     GST_QUERY_SEEKING,
275     0
276   };
277
278   return types;
279 }
280
281 static gboolean
282 gst_wavpack_parse_src_query (GstPad * pad, GstQuery * query)
283 {
284   GstWavpackParse *parse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
285   GstFormat format;
286   gboolean ret = FALSE;
287
288   switch (GST_QUERY_TYPE (query)) {
289     case GST_QUERY_POSITION:{
290       gint64 cur;
291       guint rate;
292
293       GST_OBJECT_LOCK (parse);
294       cur = parse->segment.last_stop;
295       rate = parse->samplerate;
296       GST_OBJECT_UNLOCK (parse);
297
298       if (rate == 0) {
299         GST_DEBUG_OBJECT (parse, "haven't read header yet");
300         break;
301       }
302
303       gst_query_parse_position (query, &format, NULL);
304
305       switch (format) {
306         case GST_FORMAT_TIME:
307           cur = gst_util_uint64_scale_int (cur, GST_SECOND, rate);
308           gst_query_set_position (query, GST_FORMAT_TIME, cur);
309           ret = TRUE;
310           break;
311         case GST_FORMAT_DEFAULT:
312           gst_query_set_position (query, GST_FORMAT_DEFAULT, cur);
313           ret = TRUE;
314           break;
315         default:
316           GST_DEBUG_OBJECT (parse, "cannot handle position query in "
317               "%s format. Forwarding upstream.", gst_format_get_name (format));
318           ret = gst_pad_query_default (pad, query);
319           break;
320       }
321       break;
322     }
323     case GST_QUERY_DURATION:{
324       gint64 len;
325       guint rate;
326
327       GST_OBJECT_LOCK (parse);
328       rate = parse->samplerate;
329       len = parse->total_samples;
330       GST_OBJECT_UNLOCK (parse);
331
332       if (rate == 0) {
333         GST_DEBUG_OBJECT (parse, "haven't read header yet");
334         break;
335       }
336
337       gst_query_parse_duration (query, &format, NULL);
338
339       switch (format) {
340         case GST_FORMAT_TIME:
341           if (len != -1)
342             len = gst_util_uint64_scale_int (len, GST_SECOND, rate);
343           gst_query_set_duration (query, GST_FORMAT_TIME, len);
344           ret = TRUE;
345           break;
346         case GST_FORMAT_DEFAULT:
347           gst_query_set_duration (query, GST_FORMAT_DEFAULT, len);
348           ret = TRUE;
349           break;
350         default:
351           GST_DEBUG_OBJECT (parse, "cannot handle duration query in "
352               "%s format. Forwarding upstream.", gst_format_get_name (format));
353           ret = gst_pad_query_default (pad, query);
354           break;
355       }
356       break;
357     }
358     case GST_QUERY_SEEKING:{
359       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
360       if (format == GST_FORMAT_TIME || format == GST_FORMAT_DEFAULT) {
361         gboolean seekable;
362         gint64 duration = -1;
363
364         /* only fails if we didn't read the headers yet and can't say
365          * anything about our seeking capabilities */
366         if (!gst_pad_query_duration (pad, &format, &duration))
367           break;
368
369         /* can't seek in streaming mode yet */
370         GST_OBJECT_LOCK (parse);
371         seekable = (parse->adapter == NULL);
372         GST_OBJECT_UNLOCK (parse);
373
374         gst_query_set_seeking (query, format, seekable, 0, duration);
375         ret = TRUE;
376       }
377       break;
378     }
379     default:{
380       ret = gst_pad_query_default (pad, query);
381       break;
382     }
383   }
384
385   gst_object_unref (parse);
386   return ret;
387
388 }
389
390 /* returns TRUE on success, with byte_offset set to the offset of the
391  * wavpack chunk containing the sample requested. start_sample will be
392  * set to the first sample in the chunk starting at byte_offset.
393  * Scanning from the last known header offset to the wanted position
394  * when seeking forward isn't very clever, but seems fast enough in
395  * practice and has the nice side effect of populating our index
396  * table */
397 static gboolean
398 gst_wavpack_parse_scan_to_find_sample (GstWavpackParse * parse,
399     gint64 sample, gint64 * byte_offset, gint64 * start_sample)
400 {
401   GstWavpackParseIndexEntry *entry;
402   GstFlowReturn ret;
403   gint64 off = 0;
404
405   /* first, check if we have to scan at all */
406   entry = gst_wavpack_parse_index_get_entry_from_sample (parse, sample);
407   if (entry) {
408     *byte_offset = entry->byte_offset;
409     *start_sample = entry->sample_offset;
410     GST_LOG_OBJECT (parse, "Found index entry: sample %" G_GINT64_FORMAT
411         " @ offset %" G_GINT64_FORMAT, entry->sample_offset,
412         entry->byte_offset);
413     return TRUE;
414   }
415
416   GST_LOG_OBJECT (parse, "No matching entry in index, scanning file ...");
417
418   /* if we have an index, we can start scanning from the last known offset
419    * in there, after all we know our wanted sample is not in the index */
420   if (parse->entries) {
421     GstWavpackParseIndexEntry *entry;
422
423     entry = gst_wavpack_parse_index_get_last_entry (parse);
424     off = entry->byte_offset;
425   }
426
427   /* now scan forward until we find the chunk we're looking for or hit EOS */
428   do {
429     WavpackHeader header;
430     GstBuffer *buf;
431
432     buf = gst_wavpack_parse_pull_buffer (parse, off, sizeof (WavpackHeader),
433         &ret);
434
435     if (buf == NULL)
436       break;
437
438     gst_wavpack_read_header (&header, GST_BUFFER_DATA (buf));
439     gst_buffer_unref (buf);
440
441     if (header.flags & INITIAL_BLOCK)
442       gst_wavpack_parse_index_append_entry (parse, off, header.block_index,
443           header.block_samples);
444     else
445       continue;
446
447     if (header.block_index <= sample &&
448         sample < (header.block_index + header.block_samples)) {
449       *byte_offset = off;
450       *start_sample = header.block_index;
451       return TRUE;
452     }
453
454     off += header.ckSize + 8;
455   } while (1);
456
457   GST_DEBUG_OBJECT (parse, "scan failed: %s (off=0x%08" G_GINT64_MODIFIER "x)",
458       gst_flow_get_name (ret), off);
459
460   return FALSE;
461 }
462
463 static gboolean
464 gst_wavpack_parse_send_newsegment (GstWavpackParse * wvparse, gboolean update)
465 {
466   GstSegment *s = &wvparse->segment;
467   gboolean ret;
468   gint64 stop_time = -1;
469   gint64 start_time = 0;
470   gint64 cur_pos_time;
471   gint64 diff;
472
473   /* segment is in DEFAULT format, but we want to send a TIME newsegment */
474   start_time = gst_util_uint64_scale_int (s->start, GST_SECOND,
475       wvparse->samplerate);
476
477   if (s->stop != -1) {
478     stop_time = gst_util_uint64_scale_int (s->stop, GST_SECOND,
479         wvparse->samplerate);
480   }
481
482   GST_DEBUG_OBJECT (wvparse, "sending newsegment from %" GST_TIME_FORMAT
483       " to %" GST_TIME_FORMAT, GST_TIME_ARGS (start_time),
484       GST_TIME_ARGS (stop_time));
485
486   /* after a seek, s->last_stop will point to a chunk boundary, ie. from
487    * which sample we will start sending data again, while s->start will
488    * point to the sample we actually want to seek to and want to start
489    * playing right after the seek. Adjust clock-time for the difference
490    * so we start playing from start_time */
491   cur_pos_time = gst_util_uint64_scale_int (s->last_stop, GST_SECOND,
492       wvparse->samplerate);
493   diff = start_time - cur_pos_time;
494
495   ret = gst_pad_push_event (wvparse->srcpad,
496       gst_event_new_new_segment (update, s->rate, GST_FORMAT_TIME,
497           start_time, stop_time, start_time - diff));
498
499   return ret;
500 }
501
502 static gboolean
503 gst_wavpack_parse_handle_seek_event (GstWavpackParse * wvparse,
504     GstEvent * event)
505 {
506   GstSeekFlags seek_flags;
507   GstSeekType start_type;
508   GstSeekType stop_type;
509   GstSegment segment;
510   GstFormat format;
511   gboolean only_update;
512   gboolean flush, ret;
513   gdouble speed;
514   gint64 stop;
515   gint64 start;                 /* sample we want to seek to                  */
516   gint64 byte_offset;           /* byte offset the chunk we seek to starts at */
517   gint64 chunk_start;           /* first sample in chunk we seek to           */
518   guint rate;
519   gint64 last_stop;
520
521   if (wvparse->adapter) {
522     GST_DEBUG_OBJECT (wvparse, "seeking in streaming mode not implemented yet");
523     return FALSE;
524   }
525
526   gst_event_parse_seek (event, &speed, &format, &seek_flags, &start_type,
527       &start, &stop_type, &stop);
528
529   if (format != GST_FORMAT_DEFAULT && format != GST_FORMAT_TIME) {
530     GST_DEBUG ("seeking is only supported in TIME or DEFAULT format");
531     return FALSE;
532   }
533
534   if (speed < 0.0) {
535     GST_DEBUG ("only forward playback supported, rate %f not allowed", speed);
536     return FALSE;
537   }
538
539   GST_OBJECT_LOCK (wvparse);
540
541   rate = wvparse->samplerate;
542   if (rate == 0) {
543     GST_OBJECT_UNLOCK (wvparse);
544     GST_DEBUG ("haven't read header yet");
545     return FALSE;
546   }
547
548   /* figure out the last position we need to play. If it's configured (stop !=
549    * -1), use that, else we play until the total duration of the file */
550   if (stop == -1)
551     stop = wvparse->segment.duration;
552
553   /* convert from time to samples if necessary */
554   if (format == GST_FORMAT_TIME) {
555     if (start_type != GST_SEEK_TYPE_NONE)
556       start = gst_util_uint64_scale_int (start, rate, GST_SECOND);
557     if (stop_type != GST_SEEK_TYPE_NONE)
558       stop = gst_util_uint64_scale_int (stop, rate, GST_SECOND);
559   }
560
561   if (start < 0) {
562     GST_OBJECT_UNLOCK (wvparse);
563     GST_DEBUG_OBJECT (wvparse, "Invalid start sample %" G_GINT64_FORMAT, start);
564     return FALSE;
565   }
566
567   flush = ((seek_flags & GST_SEEK_FLAG_FLUSH) != 0);
568
569   /* operate on segment copy until we know the seek worked */
570   segment = wvparse->segment;
571
572   gst_segment_set_seek (&segment, speed, GST_FORMAT_DEFAULT,
573       seek_flags, start_type, start, stop_type, stop, &only_update);
574
575 #if 0
576   if (only_update) {
577     wvparse->segment = segment;
578     gst_wavpack_parse_send_newsegment (wvparse, TRUE);
579     goto done;
580   }
581 #endif
582
583   gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_start ());
584
585   if (flush) {
586     gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_start ());
587   } else {
588     gst_pad_pause_task (wvparse->sinkpad);
589   }
590
591   GST_PAD_STREAM_LOCK (wvparse->sinkpad);
592
593   /* Save current position */
594   last_stop = wvparse->segment.last_stop;
595
596   gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_stop ());
597
598   if (flush) {
599     gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_stop ());
600   }
601
602   GST_DEBUG_OBJECT (wvparse, "Performing seek to %" GST_TIME_FORMAT " sample %"
603       G_GINT64_FORMAT, GST_TIME_ARGS (segment.start * GST_SECOND / rate),
604       start);
605
606   ret = gst_wavpack_parse_scan_to_find_sample (wvparse, segment.start,
607       &byte_offset, &chunk_start);
608
609   if (ret) {
610     GST_DEBUG_OBJECT (wvparse, "new offset: %" G_GINT64_FORMAT, byte_offset);
611     wvparse->current_offset = byte_offset;
612     /* we want to send a newsegment event with the actual seek position
613      * as start, even though our first buffer might start before the
614      * configured segment. We leave it up to the decoder or sink to crop
615      * the output buffers accordingly */
616     wvparse->segment = segment;
617     wvparse->segment.last_stop = chunk_start;
618     wvparse->need_newsegment = TRUE;
619     wvparse->discont = (last_stop != chunk_start) ? TRUE : FALSE;
620
621     /* if we're doing a segment seek, post a SEGMENT_START message */
622     if (wvparse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
623       gst_element_post_message (GST_ELEMENT_CAST (wvparse),
624           gst_message_new_segment_start (GST_OBJECT_CAST (wvparse),
625               wvparse->segment.format, wvparse->segment.last_stop));
626     }
627   } else {
628     GST_DEBUG_OBJECT (wvparse, "seek failed: don't know where to seek to");
629   }
630
631   GST_PAD_STREAM_UNLOCK (wvparse->sinkpad);
632   GST_OBJECT_UNLOCK (wvparse);
633
634   gst_pad_start_task (wvparse->sinkpad,
635       (GstTaskFunction) gst_wavpack_parse_loop, wvparse);
636
637   return ret;
638 }
639
640 static gboolean
641 gst_wavpack_parse_sink_event (GstPad * pad, GstEvent * event)
642 {
643   GstWavpackParse *parse;
644   gboolean ret = TRUE;
645
646   parse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
647
648   switch (GST_EVENT_TYPE (event)) {
649     case GST_EVENT_FLUSH_STOP:{
650       if (parse->adapter) {
651         gst_adapter_clear (parse->adapter);
652       }
653       if (parse->pending_buffer) {
654         gst_buffer_unref (parse->pending_buffer);
655         parse->pending_buffer = NULL;
656         parse->pending_offset = 0;
657       }
658       ret = gst_pad_push_event (parse->srcpad, event);
659       break;
660     }
661     case GST_EVENT_NEWSEGMENT:{
662       parse->need_newsegment = TRUE;
663       gst_event_unref (event);
664       ret = TRUE;
665       break;
666     }
667     case GST_EVENT_EOS:{
668       if (parse->adapter) {
669         /* remove all bytes that are left in the adapter after EOS. They can't
670          * be a complete Wavpack block and we can't do anything with them */
671         gst_adapter_clear (parse->adapter);
672       }
673       if (parse->pending_buffer) {
674         gst_buffer_unref (parse->pending_buffer);
675         parse->pending_buffer = NULL;
676         parse->pending_offset = 0;
677       }
678       ret = gst_pad_push_event (parse->srcpad, event);
679       break;
680     }
681     default:{
682       /* stream lock is recursive, should be fine for all events */
683       GST_PAD_STREAM_LOCK (pad);
684       if (parse->srcpad == NULL) {
685         parse->queued_events = g_list_append (parse->queued_events, event);
686       } else {
687         ret = gst_pad_push_event (parse->srcpad, event);
688       }
689       GST_PAD_STREAM_UNLOCK (pad);
690     }
691   }
692
693
694   gst_object_unref (parse);
695   return ret;
696 }
697
698 static gboolean
699 gst_wavpack_parse_src_event (GstPad * pad, GstEvent * event)
700 {
701   GstWavpackParse *parse;
702   gboolean ret;
703
704   parse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
705
706   switch (GST_EVENT_TYPE (event)) {
707     case GST_EVENT_SEEK:
708       ret = gst_wavpack_parse_handle_seek_event (parse, event);
709       break;
710     default:
711       ret = gst_pad_event_default (pad, event);
712       break;
713   }
714
715   gst_object_unref (parse);
716   return ret;
717 }
718
719 static void
720 gst_wavpack_parse_init (GstWavpackParse * parse, GstWavpackParseClass * gclass)
721 {
722   GstElementClass *klass = GST_ELEMENT_GET_CLASS (parse);
723   GstPadTemplate *tmpl;
724
725   tmpl = gst_element_class_get_pad_template (klass, "sink");
726   parse->sinkpad = gst_pad_new_from_template (tmpl, "sink");
727
728   gst_pad_set_activate_function (parse->sinkpad,
729       GST_DEBUG_FUNCPTR (gst_wavpack_parse_sink_activate));
730   gst_pad_set_activatepull_function (parse->sinkpad,
731       GST_DEBUG_FUNCPTR (gst_wavpack_parse_sink_activate_pull));
732   gst_pad_set_event_function (parse->sinkpad,
733       GST_DEBUG_FUNCPTR (gst_wavpack_parse_sink_event));
734   gst_pad_set_chain_function (parse->sinkpad,
735       GST_DEBUG_FUNCPTR (gst_wavpack_parse_chain));
736
737   gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
738
739   parse->srcpad = NULL;
740   gst_wavpack_parse_reset (parse);
741 }
742
743 static gint64
744 gst_wavpack_parse_get_upstream_length (GstWavpackParse * parse)
745 {
746   gint64 length = -1;
747
748   GstFormat format = GST_FORMAT_BYTES;
749
750   if (!gst_pad_query_peer_duration (parse->sinkpad, &format, &length)) {
751     length = -1;
752   } else {
753     GST_DEBUG ("upstream length: %" G_GINT64_FORMAT, length);
754   }
755   return length;
756 }
757
758 static GstBuffer *
759 gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse, gint64 offset,
760     guint size, GstFlowReturn * flow)
761 {
762   GstFlowReturn flow_ret;
763   GstBuffer *buf = NULL;
764
765   if (offset + size >= wvparse->upstream_length) {
766     wvparse->upstream_length = gst_wavpack_parse_get_upstream_length (wvparse);
767     if (offset + size >= wvparse->upstream_length) {
768       GST_DEBUG_OBJECT (wvparse, "EOS: %" G_GINT64_FORMAT " + %u > %"
769           G_GINT64_FORMAT, offset, size, wvparse->upstream_length);
770       flow_ret = GST_FLOW_UNEXPECTED;
771       goto done;
772     }
773   }
774
775   flow_ret = gst_pad_pull_range (wvparse->sinkpad, offset, size, &buf);
776
777   if (flow_ret != GST_FLOW_OK) {
778     GST_DEBUG_OBJECT (wvparse, "pull_range (%" G_GINT64_FORMAT ", %u) "
779         "failed, flow: %s", offset, size, gst_flow_get_name (flow_ret));
780     buf = NULL;
781     goto done;
782   }
783
784   if (GST_BUFFER_SIZE (buf) < size) {
785     GST_DEBUG_OBJECT (wvparse, "Short read at offset %" G_GINT64_FORMAT
786         ", got only %u of %u bytes", offset, GST_BUFFER_SIZE (buf), size);
787     gst_buffer_unref (buf);
788     buf = NULL;
789     flow_ret = GST_FLOW_UNEXPECTED;
790   }
791
792 done:
793   if (flow)
794     *flow = flow_ret;
795   return buf;
796 }
797
798 static gboolean
799 gst_wavpack_parse_create_src_pad (GstWavpackParse * wvparse, GstBuffer * buf,
800     WavpackHeader * header)
801 {
802   GstWavpackMetadata meta;
803   GstCaps *caps = NULL;
804   guchar *bufptr;
805
806   g_assert (wvparse->srcpad == NULL);
807
808   bufptr = GST_BUFFER_DATA (buf) + sizeof (WavpackHeader);
809
810   while (gst_wavpack_read_metadata (&meta, GST_BUFFER_DATA (buf), &bufptr)) {
811     switch (meta.id) {
812       case ID_WVC_BITSTREAM:{
813         caps = gst_caps_new_simple ("audio/x-wavpack-correction",
814             "framed", G_TYPE_BOOLEAN, TRUE, NULL);
815         wvparse->srcpad =
816             gst_pad_new_from_template (gst_element_class_get_pad_template
817             (GST_ELEMENT_GET_CLASS (wvparse), "wvcsrc"), "wvcsrc");
818         break;
819       }
820       case ID_WV_BITSTREAM:
821       case ID_WVX_BITSTREAM:{
822         WavpackStreamReader *stream_reader = gst_wavpack_stream_reader_new ();
823         WavpackContext *wpc;
824         gchar error_msg[80];
825         read_id rid;
826         gint channel_mask;
827
828         rid.buffer = GST_BUFFER_DATA (buf);
829         rid.length = GST_BUFFER_SIZE (buf);
830         rid.position = 0;
831
832         wpc =
833             WavpackOpenFileInputEx (stream_reader, &rid, NULL, error_msg, 0, 0);
834
835         if (!wpc)
836           return FALSE;
837
838         wvparse->samplerate = WavpackGetSampleRate (wpc);
839         wvparse->channels = WavpackGetNumChannels (wpc);
840         wvparse->total_samples = (header->total_samples == (int32_t) - 1) ?
841             -1 : header->total_samples;
842
843         caps = gst_caps_new_simple ("audio/x-wavpack",
844             "width", G_TYPE_INT, WavpackGetBitsPerSample (wpc),
845             "channels", G_TYPE_INT, wvparse->channels,
846             "rate", G_TYPE_INT, wvparse->samplerate,
847             "framed", G_TYPE_BOOLEAN, TRUE, NULL);
848 #ifdef WAVPACK_OLD_API
849         channel_mask = wpc->config.channel_mask;
850 #else
851         channel_mask = WavpackGetChannelMask (wpc);
852 #endif
853         if (channel_mask == 0)
854           channel_mask =
855               gst_wavpack_get_default_channel_mask (wvparse->channels);
856
857         if (channel_mask != 0) {
858           if (!gst_wavpack_set_channel_layout (caps, channel_mask)) {
859             GST_WARNING_OBJECT (wvparse, "Failed to set channel layout");
860             gst_caps_unref (caps);
861             caps = NULL;
862             WavpackCloseFile (wpc);
863             g_free (stream_reader);
864             break;
865           }
866         }
867
868         wvparse->srcpad =
869             gst_pad_new_from_template (gst_element_class_get_pad_template
870             (GST_ELEMENT_GET_CLASS (wvparse), "src"), "src");
871         WavpackCloseFile (wpc);
872         g_free (stream_reader);
873         break;
874       }
875       default:{
876         GST_LOG_OBJECT (wvparse, "unhandled ID: 0x%02x", meta.id);
877         break;
878       }
879     }
880     if (caps != NULL)
881       break;
882   }
883
884   if (caps == NULL || wvparse->srcpad == NULL)
885     return FALSE;
886
887   GST_DEBUG_OBJECT (wvparse, "Added src pad with caps %" GST_PTR_FORMAT, caps);
888
889   gst_pad_set_query_function (wvparse->srcpad,
890       GST_DEBUG_FUNCPTR (gst_wavpack_parse_src_query));
891   gst_pad_set_query_type_function (wvparse->srcpad,
892       GST_DEBUG_FUNCPTR (gst_wavpack_parse_get_src_query_types));
893   gst_pad_set_event_function (wvparse->srcpad,
894       GST_DEBUG_FUNCPTR (gst_wavpack_parse_src_event));
895
896   gst_pad_set_caps (wvparse->srcpad, caps);
897   gst_caps_unref (caps);
898   gst_pad_use_fixed_caps (wvparse->srcpad);
899
900   gst_object_ref (wvparse->srcpad);
901   gst_pad_set_active (wvparse->srcpad, TRUE);
902   gst_element_add_pad (GST_ELEMENT (wvparse), wvparse->srcpad);
903   gst_element_no_more_pads (GST_ELEMENT (wvparse));
904
905   return TRUE;
906 }
907
908 static GstFlowReturn
909 gst_wavpack_parse_push_buffer (GstWavpackParse * wvparse, GstBuffer * buf,
910     WavpackHeader * header)
911 {
912   wvparse->current_offset += header->ckSize + 8;
913
914   wvparse->segment.last_stop = header->block_index;
915
916   if (wvparse->need_newsegment) {
917     if (gst_wavpack_parse_send_newsegment (wvparse, FALSE))
918       wvparse->need_newsegment = FALSE;
919   }
920
921   /* send any queued events */
922   if (wvparse->queued_events) {
923     GList *l;
924
925     for (l = wvparse->queued_events; l != NULL; l = l->next) {
926       gst_pad_push_event (wvparse->srcpad, GST_EVENT (l->data));
927     }
928     g_list_free (wvparse->queued_events);
929     wvparse->queued_events = NULL;
930   }
931
932   if (wvparse->pending_buffer == NULL) {
933     wvparse->pending_buffer = buf;
934     wvparse->pending_offset = header->block_index;
935   } else if (wvparse->pending_offset == header->block_index) {
936     wvparse->pending_buffer = gst_buffer_join (wvparse->pending_buffer, buf);
937   } else {
938     GST_ERROR ("Got incomplete block, dropping");
939     gst_buffer_unref (wvparse->pending_buffer);
940     wvparse->pending_buffer = buf;
941     wvparse->pending_offset = header->block_index;
942   }
943
944   if (!(header->flags & FINAL_BLOCK))
945     return GST_FLOW_OK;
946
947   buf = wvparse->pending_buffer;
948   wvparse->pending_buffer = NULL;
949
950   GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (header->block_index,
951       GST_SECOND, wvparse->samplerate);
952   GST_BUFFER_DURATION (buf) = gst_util_uint64_scale_int (header->block_samples,
953       GST_SECOND, wvparse->samplerate);
954   GST_BUFFER_OFFSET (buf) = header->block_index;
955   GST_BUFFER_OFFSET_END (buf) = header->block_index + header->block_samples;
956
957   if (wvparse->discont || wvparse->next_block_index != header->block_index) {
958     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
959     wvparse->discont = FALSE;
960   }
961
962   wvparse->next_block_index = header->block_index + header->block_samples;
963
964   gst_buffer_set_caps (buf, GST_PAD_CAPS (wvparse->srcpad));
965
966   GST_LOG_OBJECT (wvparse, "Pushing buffer with time %" GST_TIME_FORMAT,
967       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
968
969   return gst_pad_push (wvparse->srcpad, buf);
970 }
971
972 static guint8 *
973 gst_wavpack_parse_find_marker (guint8 * buf, guint size)
974 {
975   int i;
976   guint8 *ret = NULL;
977
978   if (G_UNLIKELY (size < 4))
979     return NULL;
980
981   for (i = 0; i < size - 4; i++) {
982     if (memcmp (buf + i, "wvpk", 4) == 0) {
983       ret = buf + i;
984       break;
985     }
986   }
987   return ret;
988 }
989
990 static GstFlowReturn
991 gst_wavpack_parse_resync_loop (GstWavpackParse * parse, WavpackHeader * header)
992 {
993   GstFlowReturn flow_ret = GST_FLOW_UNEXPECTED;
994   GstBuffer *buf = NULL;
995
996   /* loop until we have a frame header or reach the end of the stream */
997   while (1) {
998     guint8 *data, *marker;
999     guint len, size;
1000
1001     if (buf) {
1002       gst_buffer_unref (buf);
1003       buf = NULL;
1004     }
1005
1006     if (parse->upstream_length == 0 ||
1007         parse->upstream_length <= parse->current_offset) {
1008       parse->upstream_length = gst_wavpack_parse_get_upstream_length (parse);
1009       if (parse->upstream_length == 0 ||
1010           parse->upstream_length <= parse->current_offset) {
1011         break;
1012       }
1013     }
1014
1015     len = MIN (parse->upstream_length - parse->current_offset, 2048);
1016
1017     GST_LOG_OBJECT (parse, "offset: %" G_GINT64_FORMAT, parse->current_offset);
1018
1019     buf = gst_wavpack_parse_pull_buffer (parse, parse->current_offset,
1020         len, &flow_ret);
1021
1022     /* whatever the problem is, there's nothing more for us to do for now */
1023     if (flow_ret != GST_FLOW_OK)
1024       break;
1025
1026     data = GST_BUFFER_DATA (buf);
1027     size = GST_BUFFER_SIZE (buf);
1028
1029     /* not enough data for a header? */
1030     if (size < sizeof (WavpackHeader))
1031       break;
1032
1033     /* got a header right where we are at now? */
1034     if (gst_wavpack_read_header (header, data))
1035       break;
1036
1037     /* nope, let's see if we can find one */
1038     marker = gst_wavpack_parse_find_marker (data + 1, size - 1);
1039
1040     if (marker) {
1041       parse->current_offset += marker - data;
1042       /* do one more loop iteration to make sure we pull enough
1043        * data for a full header, we'll bail out then */
1044     } else {
1045       parse->current_offset += len - 4;
1046     }
1047   }
1048
1049   if (buf)
1050     gst_buffer_unref (buf);
1051
1052   return flow_ret;
1053 }
1054
1055 static void
1056 gst_wavpack_parse_loop (GstElement * element)
1057 {
1058   GstWavpackParse *parse = GST_WAVPACK_PARSE (element);
1059   GstFlowReturn flow_ret;
1060   WavpackHeader header = { {0,}, 0, };
1061   GstBuffer *buf = NULL;
1062
1063   flow_ret = gst_wavpack_parse_resync_loop (parse, &header);
1064
1065   if (flow_ret != GST_FLOW_OK)
1066     goto pause;
1067
1068   GST_LOG_OBJECT (parse, "Read header at offset %" G_GINT64_FORMAT
1069       ": chunk size = %u+8", parse->current_offset, header.ckSize);
1070
1071   buf = gst_wavpack_parse_pull_buffer (parse, parse->current_offset,
1072       header.ckSize + 8, &flow_ret);
1073
1074   if (flow_ret != GST_FLOW_OK)
1075     goto pause;
1076
1077   if (parse->srcpad == NULL) {
1078     if (!gst_wavpack_parse_create_src_pad (parse, buf, &header)) {
1079       GST_ERROR_OBJECT (parse, "Failed to create src pad");
1080       flow_ret = GST_FLOW_ERROR;
1081       goto pause;
1082     }
1083   }
1084   if (header.flags & INITIAL_BLOCK)
1085     gst_wavpack_parse_index_append_entry (parse, parse->current_offset,
1086         header.block_index, header.block_samples);
1087
1088   flow_ret = gst_wavpack_parse_push_buffer (parse, buf, &header);
1089   if (flow_ret != GST_FLOW_OK)
1090     goto pause;
1091
1092   return;
1093
1094 pause:
1095   {
1096     const gchar *reason = gst_flow_get_name (flow_ret);
1097
1098     GST_LOG_OBJECT (parse, "pausing task, reason %s", reason);
1099     gst_pad_pause_task (parse->sinkpad);
1100
1101     if (GST_FLOW_IS_FATAL (flow_ret) || flow_ret == GST_FLOW_NOT_LINKED) {
1102       if (flow_ret == GST_FLOW_UNEXPECTED && parse->srcpad) {
1103         if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1104           GstClockTime stop;
1105
1106           GST_LOG_OBJECT (parse, "Sending segment done");
1107
1108           if ((stop = parse->segment.stop) == -1)
1109             stop = parse->segment.duration;
1110
1111           gst_element_post_message (GST_ELEMENT_CAST (parse),
1112               gst_message_new_segment_done (GST_OBJECT_CAST (parse),
1113                   parse->segment.format, stop));
1114         } else {
1115           GST_LOG_OBJECT (parse, "Sending EOS, at end of stream");
1116           gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
1117         }
1118       } else {
1119         GST_ELEMENT_ERROR (parse, STREAM, FAILED,
1120             (_("Internal data stream error.")),
1121             ("stream stopped, reason %s", reason));
1122         if (parse->srcpad)
1123           gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
1124       }
1125     }
1126     return;
1127   }
1128 }
1129
1130 static gboolean
1131 gst_wavpack_parse_resync_adapter (GstAdapter * adapter)
1132 {
1133   const guint8 *buf, *marker;
1134   guint avail = gst_adapter_available (adapter);
1135
1136   if (avail < 4)
1137     return FALSE;
1138
1139   /* if the marker is at the beginning don't do the expensive search */
1140   buf = gst_adapter_peek (adapter, 4);
1141   if (memcmp (buf, "wvpk", 4) == 0)
1142     return TRUE;
1143
1144   if (avail == 4)
1145     return FALSE;
1146
1147   /* search for the marker in the complete content of the adapter */
1148   buf = gst_adapter_peek (adapter, avail);
1149   if (buf && (marker = gst_wavpack_parse_find_marker ((guint8 *) buf, avail))) {
1150     gst_adapter_flush (adapter, marker - buf);
1151     return TRUE;
1152   }
1153
1154   /* flush everything except the last 4 bytes. they could contain
1155    * the start of a new marker */
1156   gst_adapter_flush (adapter, avail - 4);
1157
1158   return FALSE;
1159 }
1160
1161 static GstFlowReturn
1162 gst_wavpack_parse_chain (GstPad * pad, GstBuffer * buf)
1163 {
1164   GstWavpackParse *wvparse = GST_WAVPACK_PARSE (GST_PAD_PARENT (pad));
1165   GstFlowReturn ret = GST_FLOW_OK;
1166   WavpackHeader wph;
1167   const guint8 *tmp_buf;
1168
1169   if (!wvparse->adapter) {
1170     wvparse->adapter = gst_adapter_new ();
1171   }
1172
1173   if (GST_BUFFER_IS_DISCONT (buf)) {
1174     gst_adapter_clear (wvparse->adapter);
1175     wvparse->discont = TRUE;
1176   }
1177
1178   gst_adapter_push (wvparse->adapter, buf);
1179
1180   if (gst_adapter_available (wvparse->adapter) < sizeof (WavpackHeader))
1181     return ret;
1182
1183   if (!gst_wavpack_parse_resync_adapter (wvparse->adapter))
1184     return ret;
1185
1186   tmp_buf = gst_adapter_peek (wvparse->adapter, sizeof (WavpackHeader));
1187   gst_wavpack_read_header (&wph, (guint8 *) tmp_buf);
1188
1189   while (gst_adapter_available (wvparse->adapter) >= wph.ckSize + 4 * 1 + 4) {
1190     GstBuffer *outbuf =
1191         gst_adapter_take_buffer (wvparse->adapter, wph.ckSize + 4 * 1 + 4);
1192
1193     if (!outbuf)
1194       return GST_FLOW_ERROR;
1195
1196     if (wvparse->srcpad == NULL) {
1197       if (!gst_wavpack_parse_create_src_pad (wvparse, outbuf, &wph)) {
1198         GST_ERROR_OBJECT (wvparse, "Failed to create src pad");
1199         ret = GST_FLOW_ERROR;
1200         break;
1201       }
1202     }
1203
1204     ret = gst_wavpack_parse_push_buffer (wvparse, outbuf, &wph);
1205
1206     if (ret != GST_FLOW_OK)
1207       break;
1208
1209     if (gst_adapter_available (wvparse->adapter) >= sizeof (WavpackHeader)) {
1210       tmp_buf = gst_adapter_peek (wvparse->adapter, sizeof (WavpackHeader));
1211
1212       if (!gst_wavpack_parse_resync_adapter (wvparse->adapter))
1213         break;
1214
1215       gst_wavpack_read_header (&wph, (guint8 *) tmp_buf);
1216     }
1217   }
1218
1219   return ret;
1220 }
1221
1222 static GstStateChangeReturn
1223 gst_wavpack_parse_change_state (GstElement * element, GstStateChange transition)
1224 {
1225   GstWavpackParse *wvparse = GST_WAVPACK_PARSE (element);
1226   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1227
1228   switch (transition) {
1229     case GST_STATE_CHANGE_READY_TO_PAUSED:
1230       gst_segment_init (&wvparse->segment, GST_FORMAT_DEFAULT);
1231       wvparse->segment.last_stop = 0;
1232     default:
1233       break;
1234   }
1235
1236   if (GST_ELEMENT_CLASS (parent_class)->change_state)
1237     ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1238
1239   switch (transition) {
1240     case GST_STATE_CHANGE_PAUSED_TO_READY:
1241       gst_wavpack_parse_reset (wvparse);
1242       break;
1243     default:
1244       break;
1245   }
1246
1247   return ret;
1248 }
1249
1250 static gboolean
1251 gst_wavpack_parse_sink_activate (GstPad * sinkpad)
1252 {
1253   if (gst_pad_check_pull_range (sinkpad)) {
1254     return gst_pad_activate_pull (sinkpad, TRUE);
1255   } else {
1256     return gst_pad_activate_push (sinkpad, TRUE);
1257   }
1258 }
1259
1260 static gboolean
1261 gst_wavpack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
1262 {
1263   gboolean result;
1264
1265   if (active) {
1266     result = gst_pad_start_task (sinkpad,
1267         (GstTaskFunction) gst_wavpack_parse_loop, GST_PAD_PARENT (sinkpad));
1268   } else {
1269     result = gst_pad_stop_task (sinkpad);
1270   }
1271
1272   return result;
1273 }
1274
1275 gboolean
1276 gst_wavpack_parse_plugin_init (GstPlugin * plugin)
1277 {
1278   if (!gst_element_register (plugin, "wavpackparse",
1279           GST_RANK_PRIMARY, GST_TYPE_WAVPACK_PARSE)) {
1280     return FALSE;
1281   }
1282
1283   GST_DEBUG_CATEGORY_INIT (gst_wavpack_parse_debug, "wavpack_parse", 0,
1284       "Wavpack file parser");
1285
1286   return TRUE;
1287 }