gstwavpackparse.c 26.2 KB
Newer Older
1
/* GStreamer wavpack plugin
2 3 4
 * Copyright (c) 2005 Arwed v. Merkatz <v.merkatz@gmx.net>
 * Copyright (c) 2006 Tim-Philipp Müller <tim centricular net>
 * Copyright (c) 2006 Sebastian Dröge <slomo@circular-chaos.org>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * gstwavpackparse.c: wavpack file parser
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <gst/gst.h>

#include <math.h>
#include <string.h>

#include <wavpack/wavpack.h>
#include "gstwavpackparse.h"
31
#include "gstwavpackstreamreader.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include "gstwavpackcommon.h"

GST_DEBUG_CATEGORY_STATIC (gst_wavpack_parse_debug);
#define GST_CAT_DEFAULT gst_wavpack_parse_debug

static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-wavpack, "
        "framed = (boolean) false; "
        "audio/x-wavpack-correction, " "framed = (boolean) false")
    );

static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    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 55 56 57 58 59
    );

static GstStaticPadTemplate wvc_src_factory = GST_STATIC_PAD_TEMPLATE ("wvcsrc",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS ("audio/x-wavpack-correction, " "framed = (boolean) true")
    );

60 61 62 63
static gboolean gst_wavepack_parse_sink_activate (GstPad * sinkpad);
static gboolean
gst_wavepack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active);

64
static void gst_wavpack_parse_loop (GstElement * element);
65 66
static GstStateChangeReturn gst_wavpack_parse_change_state (GstElement *
    element, GstStateChange transition);
67 68 69 70
static void gst_wavpack_parse_reset (GstWavpackParse * wavpackparse);
static gint64 gst_wavpack_parse_get_upstream_length (GstWavpackParse * wvparse);
static GstBuffer *gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse,
    gint64 offset, guint size, GstFlowReturn * flow);
71

72
GST_BOILERPLATE (GstWavpackParse, gst_wavpack_parse, GstElement,
73
    GST_TYPE_ELEMENT);
74

75 76
static void
gst_wavpack_parse_base_init (gpointer klass)
77
{
78
  static const GstElementDetails plugin_details =
79 80 81
      GST_ELEMENT_DETAILS ("WavePack parser",
      "Codec/Demuxer/Audio",
      "Parses Wavpack files",
82
      "Sebastian Dröge <slomo@circular-chaos.org>");
83 84 85 86 87 88 89 90 91 92 93 94
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&src_factory));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&wvc_src_factory));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_factory));
  gst_element_class_set_details (element_class, &plugin_details);
}

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 103 104 105 106 107 108 109 110
}

static void
gst_wavpack_parse_class_init (GstWavpackParseClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

111
  gobject_class->finalize = gst_wavpack_parse_finalize;
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_wavpack_parse_change_state);
}

static GstWavpackParseIndexEntry *
gst_wavpack_parse_index_get_last_entry (GstWavpackParse * wvparse)
{
  gint last;

  g_assert (wvparse->entries != NULL);
  g_assert (wvparse->entries->len > 0);

  last = wvparse->entries->len - 1;
  return &g_array_index (wvparse->entries, GstWavpackParseIndexEntry, last);
}

static GstWavpackParseIndexEntry *
gst_wavpack_parse_index_get_entry_from_sample (GstWavpackParse * wvparse,
    gint64 sample_offset)
{
  gint i;

  if (wvparse->entries == NULL || wvparse->entries->len == 0)
    return NULL;

  for (i = wvparse->entries->len - 1; i >= 0; --i) {
    GstWavpackParseIndexEntry *entry;

    entry = &g_array_index (wvparse->entries, GstWavpackParseIndexEntry, i);

    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 146 147 148 149

    if (entry->sample_offset <= sample_offset &&
        sample_offset < entry->sample_offset_end) {
      GST_LOG_OBJECT (wvparse, "found match");
      return entry;
    }
150 151 152 153 154 155

    /* as the list is sorted and we first look at the latest entry
     * we can abort searching for an entry if the sample we want is
     * after the latest one */
    if (sample_offset >= entry->sample_offset_end)
      break;
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  }
  GST_LOG_OBJECT (wvparse, "no match in index");
  return NULL;
}

static void
gst_wavpack_parse_index_append_entry (GstWavpackParse * wvparse,
    gint64 byte_offset, gint64 sample_offset, gint64 num_samples)
{
  GstWavpackParseIndexEntry entry;

  if (wvparse->entries == NULL) {
    wvparse->entries = g_array_new (FALSE, TRUE,
        sizeof (GstWavpackParseIndexEntry));
  } else {
    /* do we have this one already? */
    entry = *gst_wavpack_parse_index_get_last_entry (wvparse);
    if (entry.byte_offset >= byte_offset)
      return;
  }

  GST_LOG_OBJECT (wvparse, "Adding index entry %8" G_GINT64_FORMAT " - %"
      GST_TIME_FORMAT " @ offset 0x%08" G_GINT64_MODIFIER "x", sample_offset,
      GST_TIME_ARGS (gst_util_uint64_scale_int (sample_offset,
              GST_SECOND, wvparse->samplerate)), byte_offset);

  entry.byte_offset = byte_offset;
  entry.sample_offset = sample_offset;
  entry.sample_offset_end = sample_offset + num_samples;
  g_array_append_val (wvparse->entries, entry);
}

static void
gst_wavpack_parse_reset (GstWavpackParse * wavpackparse)
{
  wavpackparse->total_samples = 0;
  wavpackparse->samplerate = 0;
  wavpackparse->channels = 0;

  gst_segment_init (&wavpackparse->segment, GST_FORMAT_UNDEFINED);

  wavpackparse->current_offset = 0;
  wavpackparse->need_newsegment = TRUE;
  wavpackparse->upstream_length = -1;

  if (wavpackparse->entries) {
    g_array_free (wavpackparse->entries, TRUE);
    wavpackparse->entries = NULL;
  }

  if (wavpackparse->srcpad != NULL) {
    gboolean res;

    GST_DEBUG_OBJECT (wavpackparse, "Removing src pad");
    res = gst_element_remove_pad (GST_ELEMENT (wavpackparse),
        wavpackparse->srcpad);
    g_return_if_fail (res != FALSE);
    gst_object_unref (wavpackparse->srcpad);
    wavpackparse->srcpad = NULL;
  }
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 224 225
  gboolean ret = FALSE;

  switch (GST_QUERY_TYPE (query)) {
226 227 228 229 230 231 232 233 234 235 236 237
    case GST_QUERY_POSITION:{
      gint64 cur, len;
      guint rate;

      GST_OBJECT_LOCK (wavpackparse);
      cur = wavpackparse->segment.last_stop;
      len = wavpackparse->total_samples;
      rate = wavpackparse->samplerate;
      GST_OBJECT_UNLOCK (wavpackparse);

      if (len <= 0 || rate == 0) {
        GST_DEBUG_OBJECT (wavpackparse, "haven't read header yet");
238 239
        break;
      }
240 241 242 243 244 245 246 247 248 249 250 251

      gst_query_parse_position (query, &format, NULL);

      switch (format) {
        case GST_FORMAT_TIME:
          cur = gst_util_uint64_scale_int (cur, GST_SECOND, rate);
          gst_query_set_position (query, GST_FORMAT_TIME, cur);
          ret = TRUE;
          break;
        case GST_FORMAT_DEFAULT:
          gst_query_set_position (query, GST_FORMAT_DEFAULT, cur);
          ret = TRUE;
252
          break;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        default:
          GST_DEBUG_OBJECT (wavpackparse, "cannot handle position query in "
              "%s format", gst_format_get_name (format));
          break;
      }
      break;
    }
    case GST_QUERY_DURATION:{
      gint64 len;
      guint rate;

      GST_OBJECT_LOCK (wavpackparse);
      rate = wavpackparse->samplerate;
      len = wavpackparse->total_samples;
      GST_OBJECT_UNLOCK (wavpackparse);

      if (len <= 0 || rate == 0) {
        GST_DEBUG_OBJECT (wavpackparse, "haven't read header yet");
271 272
        break;
      }
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

      gst_query_parse_duration (query, &format, NULL);

      switch (format) {
        case GST_FORMAT_TIME:
          len = gst_util_uint64_scale_int (len, GST_SECOND, rate);
          gst_query_set_duration (query, GST_FORMAT_TIME, len);
          ret = TRUE;
          break;
        case GST_FORMAT_DEFAULT:
          gst_query_set_duration (query, GST_FORMAT_DEFAULT, len);
          ret = TRUE;
          break;
        default:
          GST_DEBUG_OBJECT (wavpackparse, "cannot handle duration query in "
              "%s format", gst_format_get_name (format));
          break;
      }
291
      break;
292 293
    }
    default:{
294 295
      ret = gst_pad_query_default (pad, query);
      break;
296
    }
297
  }
298

299
  gst_object_unref (wavpackparse);
300 301
  return ret;

302 303
}

304 305 306 307 308 309 310
/* returns TRUE on success, with byte_offset set to the offset of the
 * wavpack chunk containing the sample requested. start_sample will be
 * set to the first sample in the chunk starting at byte_offset.
 * Scanning from the last known header offset to the wanted position
 * when seeking forward isn't very clever, but seems fast enough in
 * practice and has the nice side effect of populating our index
 * table */
311
static gboolean
312 313
gst_wavpack_parse_scan_to_find_sample (GstWavpackParse * parse,
    gint64 sample, gint64 * byte_offset, gint64 * start_sample)
314
{
315 316 317 318 319 320 321 322 323 324 325 326 327 328
  GstWavpackParseIndexEntry *entry;
  GstFlowReturn ret;
  gint64 off = 0;

  /* first, check if we have to scan at all */
  entry = gst_wavpack_parse_index_get_entry_from_sample (parse, sample);
  if (entry) {
    *byte_offset = entry->byte_offset;
    *start_sample = entry->sample_offset;
    GST_LOG_OBJECT (parse, "Found index entry: sample %" G_GINT64_FORMAT
        " @ offset %" G_GINT64_FORMAT, entry->sample_offset,
        entry->byte_offset);
    return TRUE;
  }
329

330
  GST_LOG_OBJECT (parse, "No matching entry in index, scanning file ...");
331

332 333 334 335
  /* if we have an index, we can start scanning from the last known offset
   * in there, after all we know our wanted sample is not in the index */
  if (parse->entries && parse->entries->len > 0) {
    GstWavpackParseIndexEntry *entry;
336

337 338
    entry = gst_wavpack_parse_index_get_last_entry (parse);
    off = entry->byte_offset;
339 340
  }

341 342
  /* now scan forward until we find the chunk we're looking for or hit EOS */
  do {
343
    WavpackHeader header;
344
    GstBuffer *buf;
345

346 347
    buf = gst_wavpack_parse_pull_buffer (parse, off, sizeof (WavpackHeader),
        &ret);
348

349 350
    if (buf == NULL)
      break;
351

352 353
    gst_wavpack_read_header (&header, GST_BUFFER_DATA (buf));
    gst_buffer_unref (buf);
354

355 356
    gst_wavpack_parse_index_append_entry (parse, off, header.block_index,
        header.block_samples);
357

358 359 360 361 362 363
    if (header.block_index <= sample &&
        sample < (header.block_index + header.block_samples)) {
      *byte_offset = off;
      *start_sample = header.block_index;
      return TRUE;
    }
364

365 366
    off += header.ckSize + 8;
  } while (1);
367

368 369
  GST_DEBUG_OBJECT (parse, "scan failed: %s (off=0x%08" G_GINT64_MODIFIER "x)",
      gst_flow_get_name (ret), off);
370

371
  return FALSE;
372 373
}

374 375
static gboolean
gst_wavpack_parse_send_newsegment (GstWavpackParse * wvparse, gboolean update)
376
{
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
  GstSegment *s = &wvparse->segment;
  gboolean ret;
  gint64 stop_time = -1;
  gint64 start_time = 0;
  gint64 cur_pos_time;
  gint64 diff;

  /* segment is in DEFAULT format, but we want to send a TIME newsegment */
  start_time = gst_util_uint64_scale_int (s->start, GST_SECOND,
      wvparse->samplerate);

  if (s->stop != -1) {
    stop_time = gst_util_uint64_scale_int (s->stop, GST_SECOND,
        wvparse->samplerate);
  }
392

393 394 395
  GST_DEBUG_OBJECT (wvparse, "sending newsegment from %" GST_TIME_FORMAT
      " to %" GST_TIME_FORMAT, GST_TIME_ARGS (start_time),
      GST_TIME_ARGS (stop_time));
396

397 398 399 400 401 402 403 404
  /* after a seek, s->last_stop will point to a chunk boundary, ie. from
   * which sample we will start sending data again, while s->start will
   * point to the sample we actually want to seek to and want to start
   * playing right after the seek. Adjust clock-time for the difference
   * so we start playing from start_time */
  cur_pos_time = gst_util_uint64_scale_int (s->last_stop, GST_SECOND,
      wvparse->samplerate);
  diff = start_time - cur_pos_time;
405

406 407 408
  ret = gst_pad_push_event (wvparse->srcpad,
      gst_event_new_new_segment (update, s->rate, GST_FORMAT_TIME,
          start_time, stop_time, start_time - diff));
409

410
  return ret;
411 412
}

413 414 415
static gboolean
gst_wavpack_parse_handle_seek_event (GstWavpackParse * wvparse,
    GstEvent * event)
416
{
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  GstSeekFlags seek_flags;
  GstSeekType start_type;
  GstSeekType stop_type;
  GstSegment segment;
  GstFormat format;
  gboolean only_update;
  gboolean flush, ret;
  gdouble speed;
  gint64 stop;
  gint64 start;                 /* sample we want to seek to                  */
  gint64 byte_offset;           /* byte offset the chunk we seek to starts at */
  gint64 chunk_start;           /* first sample in chunk we seek to           */
  guint rate;

  gst_event_parse_seek (event, &speed, &format, &seek_flags, &start_type,
      &start, &stop_type, &stop);

  if (format != GST_FORMAT_DEFAULT && format != GST_FORMAT_TIME) {
    GST_DEBUG ("seeking is only supported in TIME or DEFAULT format");
    return FALSE;
437 438
  }

439 440 441 442
  if (speed < 0.0) {
    GST_DEBUG ("only forward playback supported, rate %f not allowed", speed);
    return FALSE;
  }
443

444
  GST_OBJECT_LOCK (wvparse);
445

446 447 448 449 450
  rate = wvparse->samplerate;
  if (rate == 0) {
    GST_OBJECT_UNLOCK (wvparse);
    GST_DEBUG ("haven't read header yet");
    return FALSE;
451 452
  }

453 454 455 456 457 458
  /* convert from time to samples if necessary */
  if (format == GST_FORMAT_TIME) {
    if (start_type != GST_SEEK_TYPE_NONE)
      start = gst_util_uint64_scale_int (start, rate, GST_SECOND);
    if (stop_type != GST_SEEK_TYPE_NONE)
      stop = gst_util_uint64_scale_int (stop, rate, GST_SECOND);
459
  }
460

461 462 463 464 465
  /* if seek is to something after the end of the stream seek only
   * to the end. this can be caused by rounding errors */
  if (start >= wvparse->total_samples)
    start = wvparse->total_samples;

466 467 468 469 470 471
  flush = ((seek_flags & GST_SEEK_FLAG_FLUSH) != 0);

  if (start < 0) {
    GST_OBJECT_UNLOCK (wvparse);
    GST_DEBUG_OBJECT (wvparse, "Invalid start sample %" G_GINT64_FORMAT, start);
    return FALSE;
472 473
  }

474 475
  /* operate on segment copy until we know the seek worked */
  segment = wvparse->segment;
476

477 478
  gst_segment_set_seek (&segment, speed, GST_FORMAT_DEFAULT,
      seek_flags, start_type, start, stop_type, stop, &only_update);
479

480 481 482 483 484 485 486
#if 0
  if (only_update) {
    wvparse->segment = segment;
    gst_wavpack_parse_send_newsegment (wvparse, TRUE);
    goto done;
  }
#endif
487

488
  gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_start ());
489

490 491 492 493 494
  if (flush) {
    gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_start ());
  } else {
    gst_pad_stop_task (wvparse->sinkpad);
  }
495

496
  GST_PAD_STREAM_LOCK (wvparse->sinkpad);
497

498
  gst_pad_push_event (wvparse->sinkpad, gst_event_new_flush_stop ());
499

500 501 502
  if (flush) {
    gst_pad_push_event (wvparse->srcpad, gst_event_new_flush_stop ());
  }
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  GST_DEBUG_OBJECT (wvparse, "Performing seek to %" GST_TIME_FORMAT " sample %"
      G_GINT64_FORMAT, GST_TIME_ARGS (segment.start * GST_SECOND / rate),
      start);

  ret = gst_wavpack_parse_scan_to_find_sample (wvparse, segment.start,
      &byte_offset, &chunk_start);

  if (ret) {
    GST_DEBUG_OBJECT (wvparse, "new offset: %" G_GINT64_FORMAT, byte_offset);
    wvparse->current_offset = byte_offset;
    /* we want to send a newsegment event with the actual seek position
     * as start, even though our first buffer might start before the
     * configured segment. We leave it up to the decoder or sink to crop
     * the output buffers accordingly */
    wvparse->segment = segment;
    wvparse->segment.last_stop = chunk_start;
    gst_wavpack_parse_send_newsegment (wvparse, FALSE);
  } else {
    GST_DEBUG_OBJECT (wvparse, "seek failed: don't know where to seek to");
  }
524

525 526
  GST_PAD_STREAM_UNLOCK (wvparse->sinkpad);
  GST_OBJECT_UNLOCK (wvparse);
527

528 529
  gst_pad_start_task (wvparse->sinkpad,
      (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 538 539 540
  GstWavpackParse *wavpackparse;
  gboolean ret;

  wavpackparse = GST_WAVPACK_PARSE (gst_pad_get_parent (pad));
541 542

  switch (GST_EVENT_TYPE (event)) {
543 544 545
    case GST_EVENT_SEEK:
      ret = gst_wavpack_parse_handle_seek_event (wavpackparse, event);
      break;
546
    default:
547
      ret = gst_pad_event_default (pad, event);
548
      break;
549
  }
550

551 552
  gst_object_unref (wavpackparse);
  return ret;
553 554 555
}

static void
556 557
gst_wavpack_parse_init (GstWavpackParse * wavpackparse,
    GstWavpackParseClass * gclass)
558
{
559 560
  GstElementClass *klass = GST_ELEMENT_GET_CLASS (wavpackparse);
  GstPadTemplate *tmpl;
561

562 563
  tmpl = gst_element_class_get_pad_template (klass, "sink");
  wavpackparse->sinkpad = gst_pad_new_from_template (tmpl, "sink");
564

565 566
  gst_pad_set_activate_function (wavpackparse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_wavepack_parse_sink_activate));
567

568 569
  gst_pad_set_activatepull_function (wavpackparse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_wavepack_parse_sink_activate_pull));
570

571
  gst_element_add_pad (GST_ELEMENT (wavpackparse), wavpackparse->sinkpad);
572

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  wavpackparse->srcpad = NULL;
  gst_wavpack_parse_reset (wavpackparse);
}

static gint64
gst_wavpack_parse_get_upstream_length (GstWavpackParse * wavpackparse)
{
  GstPad *peer;
  gint64 length = -1;

  peer = gst_pad_get_peer (wavpackparse->sinkpad);
  if (peer) {
    GstFormat format = GST_FORMAT_BYTES;

    if (!gst_pad_query_duration (peer, &format, &length)) {
      length = -1;
    } else {
      GST_DEBUG ("upstream length: %" G_GINT64_FORMAT, length);
591
    }
592 593 594
    gst_object_unref (peer);
  } else {
    GST_DEBUG ("no peer!");
595 596
  }

597 598
  return length;
}
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
static GstBuffer *
gst_wavpack_parse_pull_buffer (GstWavpackParse * wvparse, gint64 offset,
    guint size, GstFlowReturn * flow)
{
  GstFlowReturn flow_ret;
  GstBuffer *buf = NULL;

  if (offset + size >= wvparse->upstream_length) {
    wvparse->upstream_length = gst_wavpack_parse_get_upstream_length (wvparse);
    if (offset + size >= wvparse->upstream_length) {
      GST_DEBUG_OBJECT (wvparse, "EOS: %" G_GINT64_FORMAT " + %u > %"
          G_GINT64_FORMAT, offset, size, wvparse->upstream_length);
      flow_ret = GST_FLOW_UNEXPECTED;
      goto done;
    }
615 616
  }

617
  flow_ret = gst_pad_pull_range (wvparse->sinkpad, offset, size, &buf);
618

619 620 621 622
  if (flow_ret != GST_FLOW_OK) {
    GST_DEBUG_OBJECT (wvparse, "pull_range (%" G_GINT64_FORMAT ", %u) "
        "failed, flow: %s", offset, size, gst_flow_get_name (flow_ret));
    return NULL;
623 624
  }

625 626 627
  if (GST_BUFFER_SIZE (buf) < size) {
    GST_DEBUG_OBJECT (wvparse, "Short read at offset %" G_GINT64_FORMAT
        ", got only %u of %u bytes", offset, GST_BUFFER_SIZE (buf), size);
628
    gst_buffer_unref (buf);
629 630
    buf = NULL;
    flow_ret = GST_FLOW_UNEXPECTED;
631 632
  }

633 634 635 636 637 638 639 640 641 642
done:
  if (flow)
    *flow = flow_ret;
  return buf;
}

static gboolean
gst_wavpack_parse_create_src_pad (GstWavpackParse * wvparse, GstBuffer * buf,
    WavpackHeader * header)
{
643
  GstWavpackMetadata meta;
644 645 646 647
  GstCaps *caps = NULL;
  guchar *bufptr;

  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 653
    switch (meta.id) {
      case ID_WVC_BITSTREAM:{
654 655
        caps = gst_caps_new_simple ("audio/x-wavpack-correction",
            "framed", G_TYPE_BOOLEAN, TRUE, NULL);
656
        wvparse->srcpad =
657
            gst_pad_new_from_template (gst_element_class_get_pad_template
658 659 660
            (GST_ELEMENT_GET_CLASS (wvparse), "wvcsrc"), "wvcsrc");
        break;
      }
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
      case ID_WV_BITSTREAM:
      case ID_WVX_BITSTREAM:{
        WavpackStreamReader *stream_reader = gst_wavpack_stream_reader_new ();
        WavpackContext *wpc;
        gchar error_msg[80];
        read_id rid;

        rid.buffer = GST_BUFFER_DATA (buf);
        rid.length = GST_BUFFER_SIZE (buf);
        rid.position = 0;

        wpc =
            WavpackOpenFileInputEx (stream_reader, &rid, NULL, error_msg, 0, 0);

        if (!wpc)
          return FALSE;

        wvparse->samplerate = WavpackGetSampleRate (wpc);
        wvparse->channels = WavpackGetNumChannels (wpc);
680
        wvparse->total_samples = header->total_samples;
681 682 683 684 685
        if (wvparse->total_samples == (int32_t) - 1)
          wvparse->total_samples = 0;
        else
          wvparse->total_samples--;

686
        caps = gst_caps_new_simple ("audio/x-wavpack",
687
            "width", G_TYPE_INT, WavpackGetBitsPerSample (wpc),
688 689
            "channels", G_TYPE_INT, wvparse->channels,
            "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 695
        WavpackCloseFile (wpc);
        g_free (stream_reader);
696 697 698 699 700
        break;
      }
      default:{
        GST_WARNING_OBJECT (wvparse, "unhandled ID: 0x%02x", meta.id);
        break;
701 702
      }
    }
703 704 705
    if (caps != NULL)
      break;
  }
706

707 708
  if (caps == NULL || wvparse->srcpad == NULL)
    return FALSE;
709

710
  GST_DEBUG_OBJECT (wvparse, "Added src pad with caps %" GST_PTR_FORMAT, caps);
711

712 713 714 715
  gst_pad_set_query_function (wvparse->srcpad,
      GST_DEBUG_FUNCPTR (gst_wavpack_parse_src_query));
  gst_pad_set_event_function (wvparse->srcpad,
      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 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
  gst_object_ref (wvparse->srcpad);
  gst_element_add_pad (GST_ELEMENT (wvparse), wvparse->srcpad);
  gst_element_no_more_pads (GST_ELEMENT (wvparse));

  return TRUE;
}

static void
gst_wavpack_parse_loop (GstElement * element)
{
  GstWavpackParse *wavpackparse = GST_WAVPACK_PARSE (element);
  GstFlowReturn flow_ret;
  WavpackHeader header = { {0,}, 0, };
  GstBuffer *buf = NULL;

  GST_LOG_OBJECT (wavpackparse, "Current offset: %" G_GINT64_FORMAT,
      wavpackparse->current_offset);

  buf = gst_wavpack_parse_pull_buffer (wavpackparse,
      wavpackparse->current_offset, sizeof (WavpackHeader), &flow_ret);

  if (buf == NULL && flow_ret == GST_FLOW_UNEXPECTED) {
    goto eos;
  } else if (buf == NULL) {
    goto pause;
746 747
  }

748 749 750 751 752 753 754 755
  gst_wavpack_read_header (&header, GST_BUFFER_DATA (buf));
  gst_buffer_unref (buf);

  GST_LOG_OBJECT (wavpackparse, "Read header at offset %" G_GINT64_FORMAT
      ": chunk size = %u+8", wavpackparse->current_offset, header.ckSize);

  buf = gst_wavpack_parse_pull_buffer (wavpackparse,
      wavpackparse->current_offset, header.ckSize + 8, &flow_ret);
756

757 758 759 760 761 762 763 764 765 766
  if (buf == NULL && flow_ret == GST_FLOW_UNEXPECTED) {
    goto eos;
  } else if (buf == NULL) {
    goto pause;
  }

  if (wavpackparse->srcpad == NULL) {
    if (!gst_wavpack_parse_create_src_pad (wavpackparse, buf, &header)) {
      GST_ELEMENT_ERROR (wavpackparse, STREAM, DECODE, (NULL), (NULL));
      goto pause;
767 768 769
    }
  }

770 771 772 773 774 775
  gst_wavpack_parse_index_append_entry (wavpackparse,
      wavpackparse->current_offset, header.block_index, header.block_samples);

  wavpackparse->current_offset += header.ckSize + 8;

  wavpackparse->segment.last_stop = header.block_index;
776

777 778 779 780 781 782 783 784 785 786
  if (wavpackparse->need_newsegment) {
    if (gst_wavpack_parse_send_newsegment (wavpackparse, FALSE))
      wavpackparse->need_newsegment = FALSE;
  }

  GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (header.block_index,
      GST_SECOND, wavpackparse->samplerate);
  GST_BUFFER_DURATION (buf) = gst_util_uint64_scale_int (header.block_samples,
      GST_SECOND, wavpackparse->samplerate);
  GST_BUFFER_OFFSET (buf) = header.block_index;
787 788
  gst_buffer_set_caps (buf, GST_PAD_CAPS (wavpackparse->srcpad));

789 790 791 792 793 794 795 796
  GST_LOG_OBJECT (wavpackparse, "Pushing buffer with time %" GST_TIME_FORMAT,
      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));

  flow_ret = gst_pad_push (wavpackparse->srcpad, buf);
  if (flow_ret != GST_FLOW_OK) {
    GST_DEBUG_OBJECT (wavpackparse, "Push failed, flow: %s",
        gst_flow_get_name (flow_ret));
    goto pause;
797 798 799 800
  }

  return;

801 802 803 804 805 806 807 808 809 810 811 812 813 814
eos:
  {
    GST_DEBUG_OBJECT (wavpackparse, "sending EOS");
    if (wavpackparse->srcpad) {
      gst_pad_push_event (wavpackparse->srcpad, gst_event_new_eos ());
    }
    /* fall through and pause task */
  }
pause:
  {
    GST_DEBUG_OBJECT (wavpackparse, "Pausing task");
    gst_pad_pause_task (wavpackparse->sinkpad);
    return;
  }
815 816
}

817 818
static GstStateChangeReturn
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 824
  switch (transition) {
    case GST_STATE_CHANGE_READY_TO_PAUSED:
825 826
      gst_segment_init (&wvparse->segment, GST_FORMAT_DEFAULT);
      wvparse->segment.last_stop = 0;
827 828 829 830
    default:
      break;
  }

831 832
  if (GST_ELEMENT_CLASS (parent_class)->change_state)
    ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
833 834 835

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
836
      gst_wavpack_parse_reset (wvparse);
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
      break;
    default:
      break;
  }

  return ret;
}


static gboolean
gst_wavepack_parse_sink_activate (GstPad * sinkpad)
{
  if (gst_pad_check_pull_range (sinkpad)) {
    return gst_pad_activate_pull (sinkpad, TRUE);
  } else {
    return FALSE;
  }
}

static gboolean
gst_wavepack_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
{
  gboolean result;
860

861 862 863 864 865 866 867 868
  if (active) {
    result = gst_pad_start_task (sinkpad,
        (GstTaskFunction) gst_wavpack_parse_loop, GST_PAD_PARENT (sinkpad));
  } else {
    result = gst_pad_stop_task (sinkpad);
  }

  return result;
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
}

gboolean
gst_wavpack_parse_plugin_init (GstPlugin * plugin)
{
  if (!gst_element_register (plugin, "wavpackparse",
          GST_RANK_PRIMARY, GST_TYPE_WAVPACK_PARSE)) {
    return FALSE;
  }

  GST_DEBUG_CATEGORY_INIT (gst_wavpack_parse_debug, "wavpackparse", 0,
      "wavpack file parser");

  return TRUE;
}