configure.ac: Check for wavpack version and define WAVPACK_OLD_API if necessary.
[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 #include <gst/gst.h>
25
26 #include <math.h>
27 #include <string.h>
28
29 #include <wavpack/wavpack.h>
30 #include "gstwavpackparse.h"
31 #include "gstwavpackstreamreader.h"
32 #include "gstwavpackcommon.h"
33
34 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_parse_debug);
35 #define GST_CAT_DEFAULT gst_wavpack_parse_debug
36
37 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
38     GST_PAD_SINK,
39     GST_PAD_ALWAYS,
40     GST_STATIC_CAPS ("audio/x-wavpack, "
41         "framed = (boolean) false; "
42         "audio/x-wavpack-correction, " "framed = (boolean) false")
43     );
44
45 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
46     GST_PAD_SRC,
47     GST_PAD_SOMETIMES,
48     GST_STATIC_CAPS ("audio/x-wavpack, "
49         "width = (int) { 8, 16, 24, 32 }, "
50         "channels = (int) [ 1, 2 ], "
51         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) true")
52     );
53
54 static GstStaticPadTemplate wvc_src_factory = GST_STATIC_PAD_TEMPLATE ("wvcsrc",
55     GST_PAD_SRC,
56     GST_PAD_SOMETIMES,
57     GST_STATIC_CAPS ("audio/x-wavpack-correction, " "framed = (boolean) true")
58     );
59
60 static gboolean gst_wavepack_parse_sink_activate (GstPad * sinkpad);
61 static gboolean
62 gst_wavepack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active);
63
64 static void gst_wavpack_parse_loop (GstElement * element);
65 static GstStateChangeReturn gst_wavpack_parse_change_state (GstElement *
66     element, GstStateChange transition);
67 static void gst_wavpack_parse_reset (GstWavpackParse * wavpackparse);
68 static gint64 gst_wavpack_parse_get_upstream_length (GstWavpackParse * wvparse);
69 static GstBuffer *gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse,
70     gint64 offset, guint size, GstFlowReturn * flow);
71
72 GST_BOILERPLATE (GstWavpackParse, gst_wavpack_parse, GstElement,
73     GST_TYPE_ELEMENT);
74
75 static void
76 gst_wavpack_parse_base_init (gpointer klass)
77 {
78   static const GstElementDetails plugin_details =
79       GST_ELEMENT_DETAILS ("WavePack parser",
80       "Codec/Demuxer/Audio",
81       "Parses Wavpack files",
82       "Sebastian Dröge <slomo@circular-chaos.org>");
83   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
84
85   gst_element_class_add_pad_template (element_class,
86       gst_static_pad_template_get (&src_factory));
87   gst_element_class_add_pad_template (element_class,
88       gst_static_pad_template_get (&wvc_src_factory));
89   gst_element_class_add_pad_template (element_class,
90       gst_static_pad_template_get (&sink_factory));
91   gst_element_class_set_details (element_class, &plugin_details);
92 }
93
94 static void
95 gst_wavpack_parse_finalize (GObject * object)
96 {
97   gst_wavpack_parse_reset (GST_WAVPACK_PARSE (object));
98
99   G_OBJECT_CLASS (parent_class)->finalize (object);
100 }
101
102 static void
103 gst_wavpack_parse_class_init (GstWavpackParseClass * klass)
104 {
105   GObjectClass *gobject_class;
106   GstElementClass *gstelement_class;
107
108   gobject_class = (GObjectClass *) klass;
109   gstelement_class = (GstElementClass *) klass;
110
111   gobject_class->finalize = gst_wavpack_parse_finalize;
112   gstelement_class->change_state =
113       GST_DEBUG_FUNCPTR (gst_wavpack_parse_change_state);
114 }
115
116 static GstWavpackParseIndexEntry *
117 gst_wavpack_parse_index_get_last_entry (GstWavpackParse * wvparse)
118 {
119   gint last;
120
121   g_assert (wvparse->entries != NULL);
122   g_assert (wvparse->entries->len > 0);
123
124   last = wvparse->entries->len - 1;
125   return &g_array_index (wvparse->entries, GstWavpackParseIndexEntry, last);
126 }
127
128 static GstWavpackParseIndexEntry *
129 gst_wavpack_parse_index_get_entry_from_sample (GstWavpackParse * wvparse,
130     gint64 sample_offset)
131 {
132   gint i;
133
134   if (wvparse->entries == NULL || wvparse->entries->len == 0)
135     return NULL;
136
137   for (i = wvparse->entries->len - 1; i >= 0; --i) {
138     GstWavpackParseIndexEntry *entry;
139
140     entry = &g_array_index (wvparse->entries, GstWavpackParseIndexEntry, i);
141
142     GST_LOG_OBJECT (wvparse, "Index entry %03u: sample %" G_GINT64_FORMAT " @"
143         " byte %" G_GINT64_FORMAT, i, entry->sample_offset, entry->byte_offset);
144
145     if (entry->sample_offset <= sample_offset &&
146         sample_offset < entry->sample_offset_end) {
147       GST_LOG_OBJECT (wvparse, "found match");
148       return entry;
149     }
150
151     /* as the list is sorted and we first look at the latest entry
152      * we can abort searching for an entry if the sample we want is
153      * after the latest one */
154     if (sample_offset >= entry->sample_offset_end)
155       break;
156   }
157   GST_LOG_OBJECT (wvparse, "no match in index");
158   return NULL;
159 }
160
161 static void
162 gst_wavpack_parse_index_append_entry (GstWavpackParse * wvparse,
163     gint64 byte_offset, gint64 sample_offset, gint64 num_samples)
164 {
165   GstWavpackParseIndexEntry entry;
166
167   if (wvparse->entries == NULL) {
168     wvparse->entries = g_array_new (FALSE, TRUE,
169         sizeof (GstWavpackParseIndexEntry));
170   } else {
171     /* do we have this one already? */
172     entry = *gst_wavpack_parse_index_get_last_entry (wvparse);
173     if (entry.byte_offset >= byte_offset)
174       return;
175   }
176
177   GST_LOG_OBJECT (wvparse, "Adding index entry %8" G_GINT64_FORMAT " - %"
178       GST_TIME_FORMAT " @ offset 0x%08" G_GINT64_MODIFIER "x", sample_offset,
179       GST_TIME_ARGS (gst_util_uint64_scale_int (sample_offset,
180               GST_SECOND, wvparse->samplerate)), byte_offset);
181
182   entry.byte_offset = byte_offset;
183   entry.sample_offset = sample_offset;
184   entry.sample_offset_end = sample_offset + num_samples;
185   g_array_append_val (wvparse->entries, entry);
186 }
187
188 static void
189 gst_wavpack_parse_reset (GstWavpackParse * wavpackparse)
190 {
191   wavpackparse->total_samples = 0;
192   wavpackparse->samplerate = 0;
193   wavpackparse->channels = 0;
194
195   gst_segment_init (&wavpackparse->segment, GST_FORMAT_UNDEFINED);
196
197   wavpackparse->current_offset = 0;
198   wavpackparse->need_newsegment = TRUE;
199   wavpackparse->upstream_length = -1;
200
201   if (wavpackparse->entries) {
202     g_array_free (wavpackparse->entries, TRUE);
203     wavpackparse->entries = NULL;
204   }
205
206   if (wavpackparse->srcpad != NULL) {
207     gboolean res;
208
209     GST_DEBUG_OBJECT (wavpackparse, "Removing src pad");
210     res = gst_element_remove_pad (GST_ELEMENT (wavpackparse),
211         wavpackparse->srcpad);
212     g_return_if_fail (res != FALSE);
213     gst_object_unref (wavpackparse->srcpad);
214     wavpackparse->srcpad = NULL;
215   }
216 }
217
218 static gboolean
219 gst_wavpack_parse_src_query (GstPad * pad, GstQuery * query)
220 {
221   GstWavpackParse *wavpackparse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
222   GstFormat format;
223   gboolean ret = FALSE;
224
225   switch (GST_QUERY_TYPE (query)) {
226     case GST_QUERY_POSITION:{
227       gint64 cur, len;
228       guint rate;
229
230       GST_OBJECT_LOCK (wavpackparse);
231       cur = wavpackparse->segment.last_stop;
232       len = wavpackparse->total_samples;
233       rate = wavpackparse->samplerate;
234       GST_OBJECT_UNLOCK (wavpackparse);
235
236       if (len <= 0 || rate == 0) {
237         GST_DEBUG_OBJECT (wavpackparse, "haven't read header yet");
238         break;
239       }
240
241       gst_query_parse_position (query, &format, NULL);
242
243       switch (format) {
244         case GST_FORMAT_TIME:
245           cur = gst_util_uint64_scale_int (cur, GST_SECOND, rate);
246           gst_query_set_position (query, GST_FORMAT_TIME, cur);
247           ret = TRUE;
248           break;
249         case GST_FORMAT_DEFAULT:
250           gst_query_set_position (query, GST_FORMAT_DEFAULT, cur);
251           ret = TRUE;
252           break;
253         default:
254           GST_DEBUG_OBJECT (wavpackparse, "cannot handle position query in "
255               "%s format", gst_format_get_name (format));
256           break;
257       }
258       break;
259     }
260     case GST_QUERY_DURATION:{
261       gint64 len;
262       guint rate;
263
264       GST_OBJECT_LOCK (wavpackparse);
265       rate = wavpackparse->samplerate;
266       len = wavpackparse->total_samples;
267       GST_OBJECT_UNLOCK (wavpackparse);
268
269       if (len <= 0 || rate == 0) {
270         GST_DEBUG_OBJECT (wavpackparse, "haven't read header yet");
271         break;
272       }
273
274       gst_query_parse_duration (query, &format, NULL);
275
276       switch (format) {
277         case GST_FORMAT_TIME:
278           len = gst_util_uint64_scale_int (len, GST_SECOND, rate);
279           gst_query_set_duration (query, GST_FORMAT_TIME, len);
280           ret = TRUE;
281           break;
282         case GST_FORMAT_DEFAULT:
283           gst_query_set_duration (query, GST_FORMAT_DEFAULT, len);
284           ret = TRUE;
285           break;
286         default:
287           GST_DEBUG_OBJECT (wavpackparse, "cannot handle duration query in "
288               "%s format", gst_format_get_name (format));
289           break;
290       }
291       break;
292     }
293     default:{
294       ret = gst_pad_query_default (pad, query);
295       break;
296     }
297   }
298
299   gst_object_unref (wavpackparse);
300   return ret;
301
302 }
303
304 /* returns TRUE on success, with byte_offset set to the offset of the
305  * wavpack chunk containing the sample requested. start_sample will be
306  * set to the first sample in the chunk starting at byte_offset.
307  * Scanning from the last known header offset to the wanted position
308  * when seeking forward isn't very clever, but seems fast enough in
309  * practice and has the nice side effect of populating our index
310  * table */
311 static gboolean
312 gst_wavpack_parse_scan_to_find_sample (GstWavpackParse * parse,
313     gint64 sample, gint64 * byte_offset, gint64 * start_sample)
314 {
315   GstWavpackParseIndexEntry *entry;
316   GstFlowReturn ret;
317   gint64 off = 0;
318
319   /* first, check if we have to scan at all */
320   entry = gst_wavpack_parse_index_get_entry_from_sample (parse, sample);
321   if (entry) {
322     *byte_offset = entry->byte_offset;
323     *start_sample = entry->sample_offset;
324     GST_LOG_OBJECT (parse, "Found index entry: sample %" G_GINT64_FORMAT
325         " @ offset %" G_GINT64_FORMAT, entry->sample_offset,
326         entry->byte_offset);
327     return TRUE;
328   }
329
330   GST_LOG_OBJECT (parse, "No matching entry in index, scanning file ...");
331
332   /* if we have an index, we can start scanning from the last known offset
333    * in there, after all we know our wanted sample is not in the index */
334   if (parse->entries && parse->entries->len > 0) {
335     GstWavpackParseIndexEntry *entry;
336
337     entry = gst_wavpack_parse_index_get_last_entry (parse);
338     off = entry->byte_offset;
339   }
340
341   /* now scan forward until we find the chunk we're looking for or hit EOS */
342   do {
343     WavpackHeader header;
344     GstBuffer *buf;
345
346     buf = gst_wavpack_parse_pull_buffer (parse, off, sizeof (WavpackHeader),
347         &ret);
348
349     if (buf == NULL)
350       break;
351
352     gst_wavpack_read_header (&header, GST_BUFFER_DATA (buf));
353     gst_buffer_unref (buf);
354
355     gst_wavpack_parse_index_append_entry (parse, off, header.block_index,
356         header.block_samples);
357
358     if (header.block_index <= sample &&
359         sample < (header.block_index + header.block_samples)) {
360       *byte_offset = off;
361       *start_sample = header.block_index;
362       return TRUE;
363     }
364
365     off += header.ckSize + 8;
366   } while (1);
367
368   GST_DEBUG_OBJECT (parse, "scan failed: %s (off=0x%08" G_GINT64_MODIFIER "x)",
369       gst_flow_get_name (ret), off);
370
371   return FALSE;
372 }
373
374 static gboolean
375 gst_wavpack_parse_send_newsegment (GstWavpackParse * wvparse, gboolean update)
376 {
377   GstSegment *s = &wvparse->segment;
378   gboolean ret;
379   gint64 stop_time = -1;
380   gint64 start_time = 0;
381   gint64 cur_pos_time;
382   gint64 diff;
383
384   /* segment is in DEFAULT format, but we want to send a TIME newsegment */
385   start_time = gst_util_uint64_scale_int (s->start, GST_SECOND,
386       wvparse->samplerate);
387
388   if (s->stop != -1) {
389     stop_time = gst_util_uint64_scale_int (s->stop, GST_SECOND,
390         wvparse->samplerate);
391   }
392
393   GST_DEBUG_OBJECT (wvparse, "sending newsegment from %" GST_TIME_FORMAT
394       " to %" GST_TIME_FORMAT, GST_TIME_ARGS (start_time),
395       GST_TIME_ARGS (stop_time));
396
397   /* after a seek, s->last_stop will point to a chunk boundary, ie. from
398    * which sample we will start sending data again, while s->start will
399    * point to the sample we actually want to seek to and want to start
400    * playing right after the seek. Adjust clock-time for the difference
401    * so we start playing from start_time */
402   cur_pos_time = gst_util_uint64_scale_int (s->last_stop, GST_SECOND,
403       wvparse->samplerate);
404   diff = start_time - cur_pos_time;
405
406   ret = gst_pad_push_event (wvparse->srcpad,
407       gst_event_new_new_segment (update, s->rate, GST_FORMAT_TIME,
408           start_time, stop_time, start_time - diff));
409
410   return ret;
411 }
412
413 static gboolean
414 gst_wavpack_parse_handle_seek_event (GstWavpackParse * wvparse,
415     GstEvent * event)
416 {
417   GstSeekFlags seek_flags;
418   GstSeekType start_type;
419   GstSeekType stop_type;
420   GstSegment segment;
421   GstFormat format;
422   gboolean only_update;
423   gboolean flush, ret;
424   gdouble speed;
425   gint64 stop;
426   gint64 start;                 /* sample we want to seek to                  */
427   gint64 byte_offset;           /* byte offset the chunk we seek to starts at */
428   gint64 chunk_start;           /* first sample in chunk we seek to           */
429   guint rate;
430
431   gst_event_parse_seek (event, &speed, &format, &seek_flags, &start_type,
432       &start, &stop_type, &stop);
433
434   if (format != GST_FORMAT_DEFAULT && format != GST_FORMAT_TIME) {
435     GST_DEBUG ("seeking is only supported in TIME or DEFAULT format");
436     return FALSE;
437   }
438
439   if (speed < 0.0) {
440     GST_DEBUG ("only forward playback supported, rate %f not allowed", speed);
441     return FALSE;
442   }
443
444   GST_OBJECT_LOCK (wvparse);
445
446   rate = wvparse->samplerate;
447   if (rate == 0) {
448     GST_OBJECT_UNLOCK (wvparse);
449     GST_DEBUG ("haven't read header yet");
450     return FALSE;
451   }
452
453   /* convert from time to samples if necessary */
454   if (format == GST_FORMAT_TIME) {
455     if (start_type != GST_SEEK_TYPE_NONE)
456       start = gst_util_uint64_scale_int (start, rate, GST_SECOND);
457     if (stop_type != GST_SEEK_TYPE_NONE)
458       stop = gst_util_uint64_scale_int (stop, rate, GST_SECOND);
459   }
460
461   /* if seek is to something after the end of the stream seek only
462    * to the end. this can be caused by rounding errors */
463   if (start >= wvparse->total_samples)
464     start = wvparse->total_samples;
465
466   flush = ((seek_flags & GST_SEEK_FLAG_FLUSH) != 0);
467
468   if (start < 0) {
469     GST_OBJECT_UNLOCK (wvparse);
470     GST_DEBUG_OBJECT (wvparse, "Invalid start sample %" G_GINT64_FORMAT, start);
471     return FALSE;
472   }
473
474   /* operate on segment copy until we know the seek worked */
475   segment = wvparse->segment;
476
477   gst_segment_set_seek (&segment, speed, GST_FORMAT_DEFAULT,
478       seek_flags, start_type, start, stop_type, stop, &only_update);
479
480 #if 0
481   if (only_update) {
482     wvparse->segment = segment;
483     gst_wavpack_parse_send_newsegment (wvparse, TRUE);
484     goto done;
485   }
486 #endif
487
488   gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_start ());
489
490   if (flush) {
491     gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_start ());
492   } else {
493     gst_pad_stop_task (wvparse->sinkpad);
494   }
495
496   GST_PAD_STREAM_LOCK (wvparse->sinkpad);
497
498   gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_stop ());
499
500   if (flush) {
501     gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_stop ());
502   }
503
504   GST_DEBUG_OBJECT (wvparse, "Performing seek to %" GST_TIME_FORMAT " sample %"
505       G_GINT64_FORMAT, GST_TIME_ARGS (segment.start * GST_SECOND / rate),
506       start);
507
508   ret = gst_wavpack_parse_scan_to_find_sample (wvparse, segment.start,
509       &byte_offset, &chunk_start);
510
511   if (ret) {
512     GST_DEBUG_OBJECT (wvparse, "new offset: %" G_GINT64_FORMAT, byte_offset);
513     wvparse->current_offset = byte_offset;
514     /* we want to send a newsegment event with the actual seek position
515      * as start, even though our first buffer might start before the
516      * configured segment. We leave it up to the decoder or sink to crop
517      * the output buffers accordingly */
518     wvparse->segment = segment;
519     wvparse->segment.last_stop = chunk_start;
520     gst_wavpack_parse_send_newsegment (wvparse, FALSE);
521   } else {
522     GST_DEBUG_OBJECT (wvparse, "seek failed: don't know where to seek to");
523   }
524
525   GST_PAD_STREAM_UNLOCK (wvparse->sinkpad);
526   GST_OBJECT_UNLOCK (wvparse);
527
528   gst_pad_start_task (wvparse->sinkpad,
529       (GstTaskFunction) gst_wavpack_parse_loop, wvparse);
530
531   return ret;
532 }
533
534 static gboolean
535 gst_wavpack_parse_src_event (GstPad * pad, GstEvent * event)
536 {
537   GstWavpackParse *wavpackparse;
538   gboolean ret;
539
540   wavpackparse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
541
542   switch (GST_EVENT_TYPE (event)) {
543     case GST_EVENT_SEEK:
544       ret = gst_wavpack_parse_handle_seek_event (wavpackparse, event);
545       break;
546     default:
547       ret = gst_pad_event_default (pad, event);
548       break;
549   }
550
551   gst_object_unref (wavpackparse);
552   return ret;
553 }
554
555 static void
556 gst_wavpack_parse_init (GstWavpackParse * wavpackparse,
557     GstWavpackParseClass * gclass)
558 {
559   GstElementClass *klass = GST_ELEMENT_GET_CLASS (wavpackparse);
560   GstPadTemplate *tmpl;
561
562   tmpl = gst_element_class_get_pad_template (klass, "sink");
563   wavpackparse->sinkpad = gst_pad_new_from_template (tmpl, "sink");
564
565   gst_pad_set_activate_function (wavpackparse->sinkpad,
566       GST_DEBUG_FUNCPTR (gst_wavepack_parse_sink_activate));
567
568   gst_pad_set_activatepull_function (wavpackparse->sinkpad,
569       GST_DEBUG_FUNCPTR (gst_wavepack_parse_sink_activate_pull));
570
571   gst_element_add_pad (GST_ELEMENT (wavpackparse), wavpackparse->sinkpad);
572
573   wavpackparse->srcpad = NULL;
574   gst_wavpack_parse_reset (wavpackparse);
575 }
576
577 static gint64
578 gst_wavpack_parse_get_upstream_length (GstWavpackParse * wavpackparse)
579 {
580   GstPad *peer;
581   gint64 length = -1;
582
583   peer = gst_pad_get_peer (wavpackparse->sinkpad);
584   if (peer) {
585     GstFormat format = GST_FORMAT_BYTES;
586
587     if (!gst_pad_query_duration (peer, &format, &length)) {
588       length = -1;
589     } else {
590       GST_DEBUG ("upstream length: %" G_GINT64_FORMAT, length);
591     }
592     gst_object_unref (peer);
593   } else {
594     GST_DEBUG ("no peer!");
595   }
596
597   return length;
598 }
599
600 static GstBuffer *
601 gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse, gint64 offset,
602     guint size, GstFlowReturn * flow)
603 {
604   GstFlowReturn flow_ret;
605   GstBuffer *buf = NULL;
606
607   if (offset + size >= wvparse->upstream_length) {
608     wvparse->upstream_length = gst_wavpack_parse_get_upstream_length (wvparse);
609     if (offset + size >= wvparse->upstream_length) {
610       GST_DEBUG_OBJECT (wvparse, "EOS: %" G_GINT64_FORMAT " + %u > %"
611           G_GINT64_FORMAT, offset, size, wvparse->upstream_length);
612       flow_ret = GST_FLOW_UNEXPECTED;
613       goto done;
614     }
615   }
616
617   flow_ret = gst_pad_pull_range (wvparse->sinkpad, offset, size, &buf);
618
619   if (flow_ret != GST_FLOW_OK) {
620     GST_DEBUG_OBJECT (wvparse, "pull_range (%" G_GINT64_FORMAT ", %u) "
621         "failed, flow: %s", offset, size, gst_flow_get_name (flow_ret));
622     return NULL;
623   }
624
625   if (GST_BUFFER_SIZE (buf) < size) {
626     GST_DEBUG_OBJECT (wvparse, "Short read at offset %" G_GINT64_FORMAT
627         ", got only %u of %u bytes", offset, GST_BUFFER_SIZE (buf), size);
628     gst_buffer_unref (buf);
629     buf = NULL;
630     flow_ret = GST_FLOW_UNEXPECTED;
631   }
632
633 done:
634   if (flow)
635     *flow = flow_ret;
636   return buf;
637 }
638
639 static gboolean
640 gst_wavpack_parse_create_src_pad (GstWavpackParse * wvparse, GstBuffer * buf,
641     WavpackHeader * header)
642 {
643   GstWavpackMetadata meta;
644   GstCaps *caps = NULL;
645   guchar *bufptr;
646
647   g_assert (wvparse->srcpad == NULL);
648
649   bufptr = GST_BUFFER_DATA (buf) + sizeof (WavpackHeader);
650
651   while (gst_wavpack_read_metadata (&meta, GST_BUFFER_DATA (buf), &bufptr)) {
652     switch (meta.id) {
653       case ID_WVC_BITSTREAM:{
654         caps = gst_caps_new_simple ("audio/x-wavpack-correction",
655             "framed", G_TYPE_BOOLEAN, TRUE, NULL);
656         wvparse->srcpad =
657             gst_pad_new_from_template (gst_element_class_get_pad_template
658             (GST_ELEMENT_GET_CLASS (wvparse), "wvcsrc"), "wvcsrc");
659         break;
660       }
661       case ID_WV_BITSTREAM:
662       case ID_WVX_BITSTREAM:{
663         WavpackStreamReader *stream_reader = gst_wavpack_stream_reader_new ();
664         WavpackContext *wpc;
665         gchar error_msg[80];
666         read_id rid;
667
668         rid.buffer = GST_BUFFER_DATA (buf);
669         rid.length = GST_BUFFER_SIZE (buf);
670         rid.position = 0;
671
672         wpc =
673             WavpackOpenFileInputEx (stream_reader, &rid, NULL, error_msg, 0, 0);
674
675         if (!wpc)
676           return FALSE;
677
678         wvparse->samplerate = WavpackGetSampleRate (wpc);
679         wvparse->channels = WavpackGetNumChannels (wpc);
680         wvparse->total_samples = header->total_samples;
681         if (wvparse->total_samples == (int32_t) - 1)
682           wvparse->total_samples = 0;
683         else
684           wvparse->total_samples--;
685
686         caps = gst_caps_new_simple ("audio/x-wavpack",
687             "width", G_TYPE_INT, WavpackGetBitsPerSample (wpc),
688             "channels", G_TYPE_INT, wvparse->channels,
689             "rate", G_TYPE_INT, wvparse->samplerate,
690             "framed", G_TYPE_BOOLEAN, TRUE, NULL);
691         wvparse->srcpad =
692             gst_pad_new_from_template (gst_element_class_get_pad_template
693             (GST_ELEMENT_GET_CLASS (wvparse), "src"), "src");
694         WavpackCloseFile (wpc);
695         g_free (stream_reader);
696         break;
697       }
698       default:{
699         GST_WARNING_OBJECT (wvparse, "unhandled ID: 0x%02x", meta.id);
700         break;
701       }
702     }
703     if (caps != NULL)
704       break;
705   }
706
707   if (caps == NULL || wvparse->srcpad == NULL)
708     return FALSE;
709
710   GST_DEBUG_OBJECT (wvparse, "Added src pad with caps %" GST_PTR_FORMAT, caps);
711
712   gst_pad_set_query_function (wvparse->srcpad,
713       GST_DEBUG_FUNCPTR (gst_wavpack_parse_src_query));
714   gst_pad_set_event_function (wvparse->srcpad,
715       GST_DEBUG_FUNCPTR (gst_wavpack_parse_src_event));
716
717   gst_pad_set_caps (wvparse->srcpad, caps);
718   gst_caps_unref (caps);
719   gst_pad_use_fixed_caps (wvparse->srcpad);
720
721   gst_object_ref (wvparse->srcpad);
722   gst_element_add_pad (GST_ELEMENT (wvparse), wvparse->srcpad);
723   gst_element_no_more_pads (GST_ELEMENT (wvparse));
724
725   return TRUE;
726 }
727
728 static void
729 gst_wavpack_parse_loop (GstElement * element)
730 {
731   GstWavpackParse *wavpackparse = GST_WAVPACK_PARSE (element);
732   GstFlowReturn flow_ret;
733   WavpackHeader header = { {0,}, 0, };
734   GstBuffer *buf = NULL;
735
736   GST_LOG_OBJECT (wavpackparse, "Current offset: %" G_GINT64_FORMAT,
737       wavpackparse->current_offset);
738
739   buf = gst_wavpack_parse_pull_buffer (wavpackparse,
740       wavpackparse->current_offset, sizeof (WavpackHeader), &flow_ret);
741
742   if (buf == NULL && flow_ret == GST_FLOW_UNEXPECTED) {
743     goto eos;
744   } else if (buf == NULL) {
745     goto pause;
746   }
747
748   gst_wavpack_read_header (&header, GST_BUFFER_DATA (buf));
749   gst_buffer_unref (buf);
750
751   GST_LOG_OBJECT (wavpackparse, "Read header at offset %" G_GINT64_FORMAT
752       ": chunk size = %u+8", wavpackparse->current_offset, header.ckSize);
753
754   buf = gst_wavpack_parse_pull_buffer (wavpackparse,
755       wavpackparse->current_offset, header.ckSize + 8, &flow_ret);
756
757   if (buf == NULL && flow_ret == GST_FLOW_UNEXPECTED) {
758     goto eos;
759   } else if (buf == NULL) {
760     goto pause;
761   }
762
763   if (wavpackparse->srcpad == NULL) {
764     if (!gst_wavpack_parse_create_src_pad (wavpackparse, buf, &header)) {
765       GST_ELEMENT_ERROR (wavpackparse, STREAM, DECODE, (NULL), (NULL));
766       goto pause;
767     }
768   }
769
770   gst_wavpack_parse_index_append_entry (wavpackparse,
771       wavpackparse->current_offset, header.block_index, header.block_samples);
772
773   wavpackparse->current_offset += header.ckSize + 8;
774
775   wavpackparse->segment.last_stop = header.block_index;
776
777   if (wavpackparse->need_newsegment) {
778     if (gst_wavpack_parse_send_newsegment (wavpackparse, FALSE))
779       wavpackparse->need_newsegment = FALSE;
780   }
781
782   GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (header.block_index,
783       GST_SECOND, wavpackparse->samplerate);
784   GST_BUFFER_DURATION (buf) = gst_util_uint64_scale_int (header.block_samples,
785       GST_SECOND, wavpackparse->samplerate);
786   GST_BUFFER_OFFSET (buf) = header.block_index;
787   gst_buffer_set_caps (buf, GST_PAD_CAPS (wavpackparse->srcpad));
788
789   GST_LOG_OBJECT (wavpackparse, "Pushing buffer with time %" GST_TIME_FORMAT,
790       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
791
792   flow_ret = gst_pad_push (wavpackparse->srcpad, buf);
793   if (flow_ret != GST_FLOW_OK) {
794     GST_DEBUG_OBJECT (wavpackparse, "Push failed, flow: %s",
795         gst_flow_get_name (flow_ret));
796     goto pause;
797   }
798
799   return;
800
801 eos:
802   {
803     GST_DEBUG_OBJECT (wavpackparse, "sending EOS");
804     if (wavpackparse->srcpad) {
805       gst_pad_push_event (wavpackparse->srcpad, gst_event_new_eos ());
806     }
807     /* fall through and pause task */
808   }
809 pause:
810   {
811     GST_DEBUG_OBJECT (wavpackparse, "Pausing task");
812     gst_pad_pause_task (wavpackparse->sinkpad);
813     return;
814   }
815 }
816
817 static GstStateChangeReturn
818 gst_wavpack_parse_change_state (GstElement * element, GstStateChange transition)
819 {
820   GstWavpackParse *wvparse = GST_WAVPACK_PARSE (element);
821   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
822
823   switch (transition) {
824     case GST_STATE_CHANGE_READY_TO_PAUSED:
825       gst_segment_init (&wvparse->segment, GST_FORMAT_DEFAULT);
826       wvparse->segment.last_stop = 0;
827     default:
828       break;
829   }
830
831   if (GST_ELEMENT_CLASS (parent_class)->change_state)
832     ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
833
834   switch (transition) {
835     case GST_STATE_CHANGE_PAUSED_TO_READY:
836       gst_wavpack_parse_reset (wvparse);
837       break;
838     default:
839       break;
840   }
841
842   return ret;
843 }
844
845
846 static gboolean
847 gst_wavepack_parse_sink_activate (GstPad * sinkpad)
848 {
849   if (gst_pad_check_pull_range (sinkpad)) {
850     return gst_pad_activate_pull (sinkpad, TRUE);
851   } else {
852     return FALSE;
853   }
854 }
855
856 static gboolean
857 gst_wavepack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
858 {
859   gboolean result;
860
861   if (active) {
862     result = gst_pad_start_task (sinkpad,
863         (GstTaskFunction) gst_wavpack_parse_loop, GST_PAD_PARENT (sinkpad));
864   } else {
865     result = gst_pad_stop_task (sinkpad);
866   }
867
868   return result;
869 }
870
871 gboolean
872 gst_wavpack_parse_plugin_init (GstPlugin * plugin)
873 {
874   if (!gst_element_register (plugin, "wavpackparse",
875           GST_RANK_PRIMARY, GST_TYPE_WAVPACK_PARSE)) {
876     return FALSE;
877   }
878
879   GST_DEBUG_CATEGORY_INIT (gst_wavpack_parse_debug, "wavpackparse", 0,
880       "wavpack file parser");
881
882   return TRUE;
883 }