gstdvdemux.c 33.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* GStreamer
 * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
 *               <2005> Wim Taymans <wim@fluendo.com>
 *
 * 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <math.h>

27
#include <gst/audio/audio.h>
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
#include "gstdvdemux.h"

/* DV output has two modes, normal and wide. The resolution is the same in both
 * cases: 720 pixels wide by 576 pixels tall in PAL format, and 720x480 for
 * NTSC.
 *
 * Each of the modes has its own pixel aspect ratio, which is fixed in practice
 * by ITU-R BT.601 (also known as "CCIR-601" or "Rec.601"). Or so claims a
 * reference that I culled from the reliable "internet",
 * http://www.mir.com/DMG/aspect.html. Normal PAL is 59/54 and normal NTSC is
 * 10/11. Because the pixel resolution is the same for both cases, we can get
 * the pixel aspect ratio for wide recordings by multiplying by the ratio of
 * display aspect ratios, 16/9 (for wide) divided by 4/3 (for normal):
 *
 * Wide NTSC: 10/11 * (16/9)/(4/3) = 40/33
 * Wide PAL: 59/54 * (16/9)/(4/3) = 118/81
 *
 * However, the pixel resolution coming out of a DV source does not combine with
 * the standard pixel aspect ratios to give a proper display aspect ratio. An
 * image 480 pixels tall, with a 4:3 display aspect ratio, will be 768 pixels
 * wide. But, if we take the normal PAL aspect ratio of 59/54, and multiply it
 * with the width of the DV image (720 pixels), we get 786.666..., which is
 * nonintegral and too wide. The camera is not outputting a 4:3 image.
 * 
 * If the video sink for this stream has fixed dimensions (such as for
 * fullscreen playback, or for a java applet in a web page), you then have two
 * choices. Either you show the whole image, but pad the image with black
 * borders on the top and bottom (like watching a widescreen video on a 4:3
 * device), or you crop the video to the proper ratio. Apparently the latter is
 * the standard practice.
 *
 * For its part, GStreamer is concerned with accuracy and preservation of
 * information. This element outputs the 720x576 or 720x480 video that it
 * recieves, noting the proper aspect ratio. This should not be a problem for
 * windowed applications, which can change size to fit the video. Applications
 * with fixed size requirements should decide whether to crop or pad which
 * an element such as videobox can do.
 */

#define NTSC_HEIGHT 480
#define NTSC_BUFFER 120000
69 70
#define NTSC_FRAMERATE_NUMERATOR 30000
#define NTSC_FRAMERATE_DENOMINATOR 1001
71 72 73

#define PAL_HEIGHT 576
#define PAL_BUFFER 144000
74 75
#define PAL_FRAMERATE_NUMERATOR 25
#define PAL_FRAMERATE_DENOMINATOR 1
76

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
77 78 79 80
#define PAL_NORMAL_PAR_X        59
#define PAL_NORMAL_PAR_Y        54
#define PAL_WIDE_PAR_X          118
#define PAL_WIDE_PAR_Y          81
81

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
82 83 84 85
#define NTSC_NORMAL_PAR_X       10
#define NTSC_NORMAL_PAR_Y       11
#define NTSC_WIDE_PAR_X         40
#define NTSC_WIDE_PAR_Y         33
86

87 88 89
GST_DEBUG_CATEGORY (dvdemux_debug);
#define GST_CAT_DEFAULT dvdemux_debug

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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
static GstElementDetails dvdemux_details =
GST_ELEMENT_DETAILS ("DV system stream demuxer",
    "Codec/Demuxer",
    "Uses libdv to separate DV audio from DV video",
    "Erik Walthinsen <omega@cse.ogi.edu>, Wim Taymans <wim@fluendo.com>");

static GstStaticPadTemplate sink_temp = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) true")
    );

static GstStaticPadTemplate video_src_temp = GST_STATIC_PAD_TEMPLATE ("video",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS ("video/x-dv, systemstream = (boolean) false")
    );

static GstStaticPadTemplate audio_src_temp = GST_STATIC_PAD_TEMPLATE ("audio",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS ("audio/x-raw-int, "
        "depth = (int) 16, "
        "width = (int) 16, "
        "signed = (boolean) TRUE, "
        "channels = (int) {2, 4}, "
        "endianness = (int) " G_STRINGIFY (G_BYTE_ORDER) ", "
        "rate = (int) { 32000, 44100, 48000 }")
    );


GST_BOILERPLATE (GstDVDemux, gst_dvdemux, GstElement, GST_TYPE_ELEMENT);


static const GstQueryType *gst_dvdemux_get_src_query_types (GstPad * pad);
static gboolean gst_dvdemux_src_query (GstPad * pad, GstQuery * query);
static const GstQueryType *gst_dvdemux_get_sink_query_types (GstPad * pad);
static gboolean gst_dvdemux_sink_query (GstPad * pad, GstQuery * query);

static gboolean gst_dvdemux_sink_convert (GstPad * pad, GstFormat src_format,
    gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
static gboolean gst_dvdemux_src_convert (GstPad * pad, GstFormat src_format,
    gint64 src_value, GstFormat * dest_format, gint64 * dest_value);

static gboolean gst_dvdemux_handle_src_event (GstPad * pad, GstEvent * event);
static GstFlowReturn gst_dvdemux_flush (GstDVDemux * dvdemux);
static GstFlowReturn gst_dvdemux_chain (GstPad * pad, GstBuffer * buffer);
static gboolean gst_dvdemux_handle_sink_event (GstPad * pad, GstEvent * event);

139 140
static GstStateChangeReturn gst_dvdemux_change_state (GstElement * element,
    GstStateChange transition);
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155


static void
gst_dvdemux_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_temp));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&video_src_temp));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&audio_src_temp));

  gst_element_class_set_details (element_class, &dvdemux_details);
156 157

  GST_DEBUG_CATEGORY_INIT (dvdemux_debug, "dvdemux", 0, "DV demuxer element");
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
}

static void
gst_dvdemux_class_init (GstDVDemuxClass * klass)
{
  GstElementClass *gstelement_class;

  gstelement_class = (GstElementClass *) klass;

  gstelement_class->change_state = gst_dvdemux_change_state;

  /* table initialization, only do once */
  dv_init (0, 0);
}

static void
174
gst_dvdemux_init (GstDVDemux * dvdemux, GstDVDemuxClass * g_class)
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 216 217 218 219 220 221 222
{
  gint i;

  dvdemux->sinkpad =
      gst_pad_new_from_template (gst_static_pad_template_get (&sink_temp),
      "sink");
  gst_pad_set_chain_function (dvdemux->sinkpad, gst_dvdemux_chain);
  gst_pad_set_event_function (dvdemux->sinkpad, gst_dvdemux_handle_sink_event);
  gst_pad_set_query_function (dvdemux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_sink_query));
  gst_pad_set_query_type_function (dvdemux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_get_sink_query_types));
  gst_element_add_pad (GST_ELEMENT (dvdemux), dvdemux->sinkpad);

  dvdemux->adapter = gst_adapter_new ();

  for (i = 0; i < 4; i++) {
    dvdemux->audio_buffers[i] =
        (gint16 *) g_malloc (DV_AUDIO_MAX_SAMPLES * sizeof (gint16));
  }
}

static void
gst_dvdemux_add_pads (GstDVDemux * dvdemux)
{
  dvdemux->videosrcpad =
      gst_pad_new_from_template (gst_static_pad_template_get (&video_src_temp),
      "video");
  gst_pad_set_query_function (dvdemux->videosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_src_query));
  gst_pad_set_query_type_function (dvdemux->videosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_get_src_query_types));
  gst_pad_set_event_function (dvdemux->videosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_handle_src_event));
  gst_pad_use_fixed_caps (dvdemux->videosrcpad);
  gst_element_add_pad (GST_ELEMENT (dvdemux), dvdemux->videosrcpad);

  dvdemux->audiosrcpad =
      gst_pad_new_from_template (gst_static_pad_template_get (&audio_src_temp),
      "audio");
  gst_pad_set_query_function (dvdemux->audiosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_src_query));
  gst_pad_set_query_type_function (dvdemux->audiosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_get_src_query_types));
  gst_pad_set_event_function (dvdemux->audiosrcpad,
      GST_DEBUG_FUNCPTR (gst_dvdemux_handle_src_event));
  gst_pad_use_fixed_caps (dvdemux->audiosrcpad);
  gst_element_add_pad (GST_ELEMENT (dvdemux), dvdemux->audiosrcpad);
223 224

  gst_element_no_more_pads (GST_ELEMENT (dvdemux));
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
}

static gboolean
gst_dvdemux_src_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
    GstFormat * dest_format, gint64 * dest_value)
{
  gboolean res = TRUE;
  GstDVDemux *dvdemux;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));
  if (dvdemux->frame_len == -1)
    goto error;

  if (dvdemux->decoder == NULL)
    goto error;

  if (*dest_format == src_format) {
    *dest_value = src_value;
    goto done;
  }

246 247
  GST_INFO ("pad:%s:%s, src_value:%lld, src_format:%d, dest_format:%d",
      GST_DEBUG_PAD_NAME (pad), src_value, src_format, *dest_format);
248

249 250 251 252
  switch (src_format) {
    case GST_FORMAT_BYTES:
      switch (*dest_format) {
        case GST_FORMAT_DEFAULT:
253 254 255 256 257
          if (pad == dvdemux->videosrcpad)
            *dest_value = src_value / dvdemux->frame_len;
          else if (pad == dvdemux->audiosrcpad)
            *dest_value = src_value / gst_audio_frame_byte_size (pad);
          break;
258 259 260
        case GST_FORMAT_TIME:
          *dest_format = GST_FORMAT_TIME;
          if (pad == dvdemux->videosrcpad)
261 262 263
            *dest_value = gst_util_uint64_scale (src_value,
                GST_SECOND * dvdemux->framerate_denominator,
                dvdemux->frame_len * dvdemux->framerate_numerator);
264
          else if (pad == dvdemux->audiosrcpad)
265 266
            *dest_value = gst_util_uint64_scale_int (src_value, GST_SECOND,
                2 * dvdemux->frequency * dvdemux->channels);
267 268 269 270 271 272 273 274 275
          break;
        default:
          res = FALSE;
      }
      break;
    case GST_FORMAT_TIME:
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
          if (pad == dvdemux->videosrcpad)
276 277 278
            *dest_value = gst_util_uint64_scale (src_value,
                dvdemux->frame_len * dvdemux->framerate_numerator,
                dvdemux->framerate_denominator * GST_SECOND);
279
          else if (pad == dvdemux->audiosrcpad)
280 281
            *dest_value = gst_util_uint64_scale_int (src_value,
                2 * dvdemux->frequency * dvdemux->channels, GST_SECOND);
282 283
          break;
        case GST_FORMAT_DEFAULT:
284 285
          if (pad == dvdemux->videosrcpad) {
            if (src_value)
286 287 288
              *dest_value = gst_util_uint64_scale (src_value,
                  dvdemux->framerate_numerator,
                  dvdemux->framerate_denominator * GST_SECOND);
289 290
            else
              *dest_value = 0;
291
          } else if (pad == dvdemux->audiosrcpad) {
292 293 294
            *dest_value = gst_util_uint64_scale (src_value,
                2 * dvdemux->frequency * dvdemux->channels,
                GST_SECOND * gst_audio_frame_byte_size (pad));
295
          }
296 297 298 299 300 301 302 303 304
          break;
        default:
          res = FALSE;
      }
      break;
    case GST_FORMAT_DEFAULT:
      switch (*dest_format) {
        case GST_FORMAT_TIME:
          if (pad == dvdemux->videosrcpad) {
305 306 307
            *dest_value = gst_util_uint64_scale (src_value,
                GST_SECOND * dvdemux->framerate_denominator,
                dvdemux->framerate_numerator);
308 309
          } else if (pad == dvdemux->audiosrcpad) {
            if (src_value)
310 311 312
              *dest_value = gst_util_uint64_scale (src_value,
                  GST_SECOND * gst_audio_frame_byte_size (pad),
                  2 * dvdemux->frequency * dvdemux->channels);
313 314 315 316 317 318 319 320 321 322
            else
              *dest_value = 0;
          }
          break;
        case GST_FORMAT_BYTES:
          if (pad == dvdemux->videosrcpad) {
            *dest_value = src_value * dvdemux->frame_len;
          } else if (pad == dvdemux->audiosrcpad) {
            *dest_value = src_value * gst_audio_frame_byte_size (pad);
          }
323 324 325 326 327 328 329 330 331 332 333 334
          break;
        default:
          res = FALSE;
      }
      break;
    default:
      res = FALSE;
  }

done:
  gst_object_unref (dvdemux);

335 336
  GST_INFO ("Result : dest_format:%d, dest_value:%lld, res:%d",
      *dest_format, *dest_value, res);
337 338
  return res;

339
  /* ERRORS */
340 341
error:
  {
342
    GST_INFO ("source conversion failed");
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    gst_object_unref (dvdemux);
    return FALSE;
  }
}

static gboolean
gst_dvdemux_sink_convert (GstPad * pad, GstFormat src_format, gint64 src_value,
    GstFormat * dest_format, gint64 * dest_value)
{
  gboolean res = TRUE;
  GstDVDemux *dvdemux;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));

  if (dvdemux->frame_len <= 0)
    goto error;

  GST_DEBUG ("%d -> %d", src_format, *dest_format);
361 362
  GST_INFO ("pad:%s:%s, src_value:%lld, src_format:%d, dest_format:%d",
      GST_DEBUG_PAD_NAME (pad), src_value, src_format, *dest_format);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

  if (*dest_format == GST_FORMAT_DEFAULT)
    *dest_format = GST_FORMAT_TIME;

  if (*dest_format == src_format) {
    *dest_value = src_value;
    goto done;
  }

  switch (src_format) {
    case GST_FORMAT_BYTES:
      switch (*dest_format) {
        case GST_FORMAT_TIME:
        {
          guint64 frame;

          /* get frame number */
          frame = src_value / dvdemux->frame_len;

382 383 384
          *dest_value = gst_util_uint64_scale (frame,
              GST_SECOND * dvdemux->framerate_denominator,
              dvdemux->framerate_numerator);
385 386 387 388 389 390 391 392 393 394 395 396 397
          break;
        }
        default:
          res = FALSE;
      }
      break;
    case GST_FORMAT_TIME:
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
        {
          guint64 frame;

          /* calculate the frame */
398 399 400 401
          frame =
              gst_util_uint64_scale (src_value, dvdemux->framerate_numerator,
              dvdemux->framerate_denominator * GST_SECOND);

402 403 404 405 406 407 408 409 410 411 412
          /* calculate the offset */
          *dest_value = frame * dvdemux->frame_len;
          break;
        }
        default:
          res = FALSE;
      }
      break;
    default:
      res = FALSE;
  }
413 414
  GST_INFO ("Result : dest_format:%d, dest_value:%lld, res:%d",
      *dest_format, *dest_value, res);
415 416 417 418 419 420 421

done:
  gst_object_unref (dvdemux);
  return res;

error:
  {
422
    GST_INFO ("sink conversion failed");
423 424 425 426 427 428 429 430 431 432
    gst_object_unref (dvdemux);
    return FALSE;
  }
}

static const GstQueryType *
gst_dvdemux_get_src_query_types (GstPad * pad)
{
  static const GstQueryType src_query_types[] = {
    GST_QUERY_POSITION,
Wim Taymans's avatar
Wim Taymans committed
433
    GST_QUERY_DURATION,
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    GST_QUERY_CONVERT,
    0
  };

  return src_query_types;
}

static gboolean
gst_dvdemux_src_query (GstPad * pad, GstQuery * query)
{
  gboolean res = TRUE;
  GstDVDemux *dvdemux;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_POSITION:
Wim Taymans's avatar
Wim Taymans committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    {
      GstFormat format;
      gint64 cur;

      /* get target format */
      gst_query_parse_position (query, &format, NULL);

      /* bring the position to the requested format. */
      if (!(res = gst_pad_query_convert (pad,
                  GST_FORMAT_TIME, dvdemux->timestamp, &format, &cur)))
        goto error;
      gst_query_set_position (query, format, cur);
      break;
    }
    case GST_QUERY_DURATION:
466 467
    {
      GstFormat format;
468
      GstFormat format2;
Wim Taymans's avatar
Wim Taymans committed
469
      gint64 end;
470 471 472
      GstPad *peer;

      /* get target format */
Wim Taymans's avatar
Wim Taymans committed
473
      gst_query_parse_duration (query, &format, NULL);
474

Wim Taymans's avatar
Wim Taymans committed
475 476
      /* change query to bytes to perform on peer */
      gst_query_set_duration (query, GST_FORMAT_BYTES, -1);
477 478 479 480 481 482 483 484 485

      if ((peer = gst_pad_get_peer (dvdemux->sinkpad))) {
        /* ask peer for total length */
        if (!(res = gst_pad_query (peer, query))) {
          gst_object_unref (peer);
          goto error;
        }

        /* get peer total length */
Wim Taymans's avatar
Wim Taymans committed
486 487 488
        gst_query_parse_duration (query, NULL, &end);

        gst_object_unref (peer);
489 490 491

        /* convert end to requested format */
        if (end != -1) {
492
          format2 = format;
493
          if (!(res = gst_pad_query_convert (dvdemux->sinkpad,
494
                      GST_FORMAT_BYTES, end, &format2, &end))) {
495 496 497 498 499 500
            goto error;
          }
        }
      } else {
        end = -1;
      }
Wim Taymans's avatar
Wim Taymans committed
501
      gst_query_set_duration (query, format, end);
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
      break;
    }
    case GST_QUERY_CONVERT:
    {
      GstFormat src_fmt, dest_fmt;
      gint64 src_val, dest_val;

      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
      if (!(res =
              gst_dvdemux_src_convert (pad, src_fmt, src_val, &dest_fmt,
                  &dest_val)))
        goto error;
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
      break;
    }
    default:
518
      res = gst_pad_query_default (pad, query);
519 520 521 522 523 524 525 526 527
      break;
  }
  gst_object_unref (dvdemux);

  return res;

error:
  {
    gst_object_unref (dvdemux);
528
    GST_DEBUG ("error source query");
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    return FALSE;
  }
}

static const GstQueryType *
gst_dvdemux_get_sink_query_types (GstPad * pad)
{
  static const GstQueryType sink_query_types[] = {
    GST_QUERY_CONVERT,
    0
  };

  return sink_query_types;
}

static gboolean
gst_dvdemux_sink_query (GstPad * pad, GstQuery * query)
{
  gboolean res = TRUE;
  GstDVDemux *dvdemux;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_CONVERT:
    {
      GstFormat src_fmt, dest_fmt;
      gint64 src_val, dest_val;

      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
      if (!(res =
              gst_dvdemux_sink_convert (pad, src_fmt, src_val, &dest_fmt,
                  &dest_val)))
        goto error;
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
      break;
    }
    default:
567
      res = gst_pad_query_default (pad, query);
568 569 570 571 572 573 574 575 576
      break;
  }
  gst_object_unref (dvdemux);

  return res;

error:
  {
    gst_object_unref (dvdemux);
577
    GST_DEBUG ("error handling sink query");
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    return FALSE;
  }
}

static gboolean
gst_dvdemux_send_event (GstDVDemux * dvdemux, GstEvent * event)
{
  gboolean res = FALSE;

  gst_event_ref (event);
  if (dvdemux->videosrcpad)
    res |= gst_pad_push_event (dvdemux->videosrcpad, event);
  if (dvdemux->audiosrcpad)
    res |= gst_pad_push_event (dvdemux->audiosrcpad, event);

  return res;
}

static gboolean
gst_dvdemux_handle_sink_event (GstPad * pad, GstEvent * event)
{
  GstDVDemux *dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));
  gboolean res = TRUE;

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_FLUSH_START:
      /* we are not blocking on anything exect the push() calls
       * to the peer which will be unblocked by forwarding the
       * event.*/
      res = gst_dvdemux_send_event (dvdemux, event);
      break;
    case GST_EVENT_FLUSH_STOP:
      gst_adapter_clear (dvdemux->adapter);
      GST_DEBUG ("cleared adapter");
      res = gst_dvdemux_send_event (dvdemux, event);
613 614
      gst_segment_init (&dvdemux->byte_segment, GST_FORMAT_BYTES);
      gst_segment_init (&dvdemux->time_segment, GST_FORMAT_TIME);
615 616 617
      break;
    case GST_EVENT_NEWSEGMENT:
    {
618 619
      gboolean update;
      gdouble rate;
620
      GstFormat format;
621
      gint64 start, stop, time;
622 623

      /* parse byte start and stop positions */
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
      gst_event_parse_new_segment (event, &update, &rate, &format,
          &start, &stop, &time);

      switch (format) {
        case GST_FORMAT_BYTES:
          gst_segment_set_newsegment (&dvdemux->byte_segment, update,
              rate, format, start, stop, time);

          /* and queue a SEGMENT before sending the next set of buffers, we
           * cannot convert to time yet as we might not know the size of the
           * frames, etc.. */
          dvdemux->need_segment = TRUE;
          gst_event_unref (event);
          break;
        case GST_FORMAT_TIME:
          gst_segment_set_newsegment (&dvdemux->time_segment, update,
              rate, format, start, stop, time);
641

642 643 644 645 646 647 648 649 650
          /* and we can just forward this time event */
          res = gst_dvdemux_send_event (dvdemux, event);
          break;
        default:
          gst_event_unref (event);
          /* cannot accept this format */
          res = FALSE;
          break;
      }
651 652 653 654 655 656 657 658 659 660
      break;
    }
    case GST_EVENT_EOS:
      /* flush any pending data */
      gst_dvdemux_flush (dvdemux);
      /* forward event */
      res = gst_dvdemux_send_event (dvdemux, event);
      /* and clear the adapter */
      gst_adapter_clear (dvdemux->adapter);
      break;
661 662 663
    default:
      res = gst_dvdemux_send_event (dvdemux, event);
      break;
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
  }

  gst_object_unref (dvdemux);

  return res;
}

static gboolean
gst_dvdemux_handle_src_event (GstPad * pad, GstEvent * event)
{
  gboolean res = TRUE;
  GstDVDemux *dvdemux;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_SEEK:
    {
      GstEvent *newevent;
      gint64 offset;
      GstFormat format, conv;
      gint64 cur, stop;
      gdouble rate;
      GstSeekType cur_type, stop_type;
      GstSeekFlags flags;
      gint64 start_position, end_position;

      gst_event_parse_seek (event, &rate, &format, &flags,
          &cur_type, &cur, &stop_type, &stop);

      if ((offset = cur) != -1) {
695
        GST_INFO ("starting conversion of cur");
696 697 698 699 700 701 702 703 704 705 706 707 708 709
        /* bring the format to time on srcpad. */
        conv = GST_FORMAT_TIME;
        if (!(res = gst_pad_query_convert (pad,
                    format, offset, &conv, &start_position))) {
          /* could not convert seek format to time offset */
          break;
        }
        /* and convert to bytes on sinkpad. */
        conv = GST_FORMAT_BYTES;
        if (!(res = gst_pad_query_convert (dvdemux->sinkpad,
                    GST_FORMAT_TIME, start_position, &conv, &start_position))) {
          /* could not convert time format to bytes offset */
          break;
        }
710 711
        GST_INFO ("Finished conversion of cur, BYTES cur : %lld",
            start_position);
712 713 714 715 716
      } else {
        start_position = -1;
      }

      if ((offset = stop) != -1) {
717
        GST_INFO ("starting conversion of stop");
718 719 720 721 722 723 724 725 726 727 728 729 730 731
        /* bring the format to time on srcpad. */
        conv = GST_FORMAT_TIME;
        if (!(res = gst_pad_query_convert (pad,
                    format, offset, &conv, &end_position))) {
          /* could not convert seek format to time offset */
          break;
        }
        conv = GST_FORMAT_BYTES;
        /* and convert to bytes on sinkpad. */
        if (!(res = gst_pad_query_convert (dvdemux->sinkpad,
                    GST_FORMAT_TIME, end_position, &conv, &end_position))) {
          /* could not convert seek format to bytes offset */
          break;
        }
732 733
        GST_INFO ("Finished conversion of stop, BYTES cur : %lld",
            start_position);
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
      } else {
        end_position = -1;
      }
      /* now this is the updated seek event on bytes */
      newevent = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
          cur_type, start_position, stop_type, end_position);

      res = gst_pad_push_event (dvdemux->sinkpad, newevent);
      break;
    }
    default:
      res = FALSE;
      break;
  }
  gst_event_unref (event);

  gst_object_unref (dvdemux);

  return res;
}

static GstFlowReturn
gst_dvdemux_demux_audio (GstDVDemux * dvdemux, const guint8 * data)
{
  gint num_samples;
  gint frequency, channels;
  GstFlowReturn ret;

  frequency = dv_get_frequency (dvdemux->decoder);
  channels = dv_get_num_channels (dvdemux->decoder);

  /* check if format changed */
  if ((frequency != dvdemux->frequency) || (channels != dvdemux->channels)) {
    GstCaps *caps;

    dvdemux->frequency = frequency;
    dvdemux->channels = channels;

    /* and set new caps */
    caps = gst_caps_new_simple ("audio/x-raw-int",
        "rate", G_TYPE_INT, frequency,
        "depth", G_TYPE_INT, 16,
        "width", G_TYPE_INT, 16,
        "signed", G_TYPE_BOOLEAN, TRUE,
        "channels", G_TYPE_INT, channels,
        "endianness", G_TYPE_INT, G_BYTE_ORDER, NULL);
    gst_pad_set_caps (dvdemux->audiosrcpad, caps);
    gst_caps_unref (caps);
  }

  dv_decode_full_audio (dvdemux->decoder, data, dvdemux->audio_buffers);

  if ((num_samples = dv_get_num_samples (dvdemux->decoder)) > 0) {
    gint16 *a_ptr;
    gint i, j;
    GstBuffer *outbuf;

    outbuf = gst_buffer_new_and_alloc (num_samples *
        sizeof (gint16) * dvdemux->channels);

    a_ptr = (gint16 *) GST_BUFFER_DATA (outbuf);

    for (i = 0; i < num_samples; i++) {
      for (j = 0; j < dvdemux->channels; j++) {
        *(a_ptr++) = dvdemux->audio_buffers[j][i];
      }
    }

    GST_DEBUG ("pushing audio %" GST_TIME_FORMAT,
        GST_TIME_ARGS (dvdemux->timestamp));

    GST_BUFFER_TIMESTAMP (outbuf) = dvdemux->timestamp;
    GST_BUFFER_DURATION (outbuf) = dvdemux->duration;
    GST_BUFFER_OFFSET (outbuf) = dvdemux->audio_offset;
    dvdemux->audio_offset += num_samples;
    GST_BUFFER_OFFSET_END (outbuf) = dvdemux->audio_offset;

    gst_buffer_set_caps (outbuf, GST_PAD_CAPS (dvdemux->audiosrcpad));

    ret = gst_pad_push (dvdemux->audiosrcpad, outbuf);
  } else {
    /* no samples */
    ret = GST_FLOW_OK;
  }

  return ret;
}

static GstFlowReturn
gst_dvdemux_demux_video (GstDVDemux * dvdemux, const guint8 * data)
{
  GstBuffer *outbuf;
  gint height;
  gboolean wide;
  GstFlowReturn ret = GST_FLOW_OK;

  /* get params */
  /* framerate is already up-to-date */
  height = (dvdemux->PAL ? PAL_HEIGHT : NTSC_HEIGHT);
  wide = dv_format_wide (dvdemux->decoder);

  /* see if anything changed */
  if ((dvdemux->height != height) || dvdemux->wide != wide) {
    GstCaps *caps;
    gint par_x, par_y;

    dvdemux->height = height;
    dvdemux->wide = wide;

    if (dvdemux->PAL) {
      if (wide) {
        par_x = PAL_WIDE_PAR_X;
        par_y = PAL_WIDE_PAR_Y;
      } else {
        par_x = PAL_NORMAL_PAR_X;
        par_y = PAL_NORMAL_PAR_Y;
      }
    } else {
      if (wide) {
        par_x = NTSC_WIDE_PAR_X;
        par_y = NTSC_WIDE_PAR_Y;
      } else {
        par_x = NTSC_NORMAL_PAR_X;
        par_y = NTSC_NORMAL_PAR_Y;
      }
    }

    caps = gst_caps_new_simple ("video/x-dv",
        "systemstream", G_TYPE_BOOLEAN, FALSE,
        "width", G_TYPE_INT, 720,
        "height", G_TYPE_INT, height,
865 866
        "framerate", GST_TYPE_FRACTION, dvdemux->framerate_numerator,
        dvdemux->framerate_denominator,
867 868 869 870 871 872 873 874
        "pixel-aspect-ratio", GST_TYPE_FRACTION, par_x, par_y, NULL);
    gst_pad_set_caps (dvdemux->videosrcpad, caps);
    gst_caps_unref (caps);
  }

  outbuf = gst_buffer_new ();

  gst_buffer_set_data (outbuf, (guint8 *) data, dvdemux->frame_len);
875
  outbuf->malloc_data = GST_BUFFER_DATA (outbuf);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899

  GST_BUFFER_TIMESTAMP (outbuf) = dvdemux->timestamp;
  GST_BUFFER_OFFSET (outbuf) = dvdemux->video_offset;
  GST_BUFFER_OFFSET_END (outbuf) = dvdemux->video_offset + 1;
  GST_BUFFER_DURATION (outbuf) = dvdemux->duration;

  gst_buffer_set_caps (outbuf, GST_PAD_CAPS (dvdemux->videosrcpad));

  GST_DEBUG ("pushing video %" GST_TIME_FORMAT,
      GST_TIME_ARGS (dvdemux->timestamp));

  ret = gst_pad_push (dvdemux->videosrcpad, outbuf);

  dvdemux->video_offset++;

  return ret;
}

static GstFlowReturn
gst_dvdemux_demux_frame (GstDVDemux * dvdemux, const guint8 * data)
{
  GstClockTime next_ts;
  GstFlowReturn aret, vret, ret;

900
  if (dvdemux->need_segment) {
901 902 903 904 905 906 907
    GstEvent *event;
    GstFormat format;
    gboolean res;

    /* convert to time and store as start/end_timestamp */
    format = GST_FORMAT_TIME;
    if (!(res = gst_pad_query_convert (dvdemux->sinkpad,
908 909 910
                GST_FORMAT_BYTES, dvdemux->byte_segment.start,
                &format, &dvdemux->time_segment.start))) {
      goto segment_error;
911
    }
912
    dvdemux->timestamp = dvdemux->time_segment.start;
913

914 915 916
    /* calculate current frame number */
    format = GST_FORMAT_DEFAULT;
    if (!(res = gst_pad_query_convert (dvdemux->videosrcpad,
917 918 919
                GST_FORMAT_TIME, dvdemux->time_segment.start,
                &format, &dvdemux->total_frames))) {
      goto segment_error;
920 921
    }

922 923
    if (dvdemux->byte_segment.stop == -1) {
      dvdemux->time_segment.stop = -1;
924 925 926
    } else {
      format = GST_FORMAT_TIME;
      if (!(res = gst_pad_query_convert (dvdemux->sinkpad,
927 928 929
                  GST_FORMAT_BYTES, dvdemux->byte_segment.stop,
                  &format, &dvdemux->time_segment.stop))) {
        goto segment_error;
930
      }
931 932
    }

933 934 935 936 937
    GST_DEBUG_OBJECT (dvdemux, "sending segment start: %" GST_TIME_FORMAT
        ", stop: %" GST_TIME_FORMAT ", time: %" GST_TIME_FORMAT,
        dvdemux->time_segment.start, dvdemux->time_segment.stop,
        dvdemux->time_segment.start);

938
    event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_TIME,
939 940
        dvdemux->time_segment.start, dvdemux->time_segment.stop,
        dvdemux->time_segment.start);
941 942
    gst_dvdemux_send_event (dvdemux, event);

943
    dvdemux->need_segment = FALSE;
944 945
  }

946 947 948
  next_ts = gst_util_uint64_scale_int (
      (dvdemux->total_frames + 1) * GST_SECOND,
      dvdemux->framerate_denominator, dvdemux->framerate_numerator);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
  dvdemux->duration = next_ts - dvdemux->timestamp;

  dv_parse_packs (dvdemux->decoder, data);
  if (dv_is_new_recording (dvdemux->decoder, data))
    dvdemux->new_media = TRUE;

  aret = ret = gst_dvdemux_demux_audio (dvdemux, data);
  if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
    goto done;

  vret = ret = gst_dvdemux_demux_video (dvdemux, data);
  if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)
    goto done;

  if (aret == GST_FLOW_NOT_LINKED && vret == GST_FLOW_NOT_LINKED) {
    ret = GST_FLOW_NOT_LINKED;
    goto done;
  }

  ret = GST_FLOW_OK;
  dvdemux->timestamp = next_ts;
970
  dvdemux->total_frames++;
971 972 973 974

done:
  return ret;

975
segment_error:
976
  {
977
    GST_DEBUG ("error generating new_segment event");
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    return GST_FLOW_ERROR;
  }
}

/* flush any remaining data in the adapter */
static GstFlowReturn
gst_dvdemux_flush (GstDVDemux * dvdemux)
{
  GstFlowReturn ret = GST_FLOW_OK;

  while (gst_adapter_available (dvdemux->adapter) >= dvdemux->frame_len) {
    const guint8 *data;
    gint length;

    /* get the accumulated bytes */
    data = gst_adapter_peek (dvdemux->adapter, dvdemux->frame_len);

    /* parse header to know the length and other params */
    if (dv_parse_header (dvdemux->decoder, data) < 0)
      goto parse_header_error;

    dvdemux->found_header = TRUE;

    /* after parsing the header we know the length of the data */
    dvdemux->PAL = dv_system_50_fields (dvdemux->decoder);
    length = dvdemux->frame_len = (dvdemux->PAL ? PAL_BUFFER : NTSC_BUFFER);
1004 1005 1006 1007 1008 1009 1010
    if (dvdemux->PAL) {
      dvdemux->framerate_numerator = PAL_FRAMERATE_NUMERATOR;
      dvdemux->framerate_denominator = PAL_FRAMERATE_DENOMINATOR;
    } else {
      dvdemux->framerate_numerator = NTSC_FRAMERATE_NUMERATOR;
      dvdemux->framerate_denominator = NTSC_FRAMERATE_DENOMINATOR;
    }
1011 1012 1013 1014 1015 1016
    /* let demux_video set the height, it needs to detect when things change so
     * it can reset caps */

    /* if we still have enough for a frame, start decoding */
    if (gst_adapter_available (dvdemux->adapter) >= length) {

1017
      data = gst_adapter_take (dvdemux->adapter, length);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

      /* and decode the data */
      ret = gst_dvdemux_demux_frame (dvdemux, data);

      if (ret != GST_FLOW_OK)
        goto done;
    }
  }
done:
  return ret;

  /* ERRORS */
parse_header_error:
  {
    GST_ELEMENT_ERROR (dvdemux, STREAM, DECODE,
        ("Error parsing DV header"), ("Error parsing DV header"));

    return GST_FLOW_ERROR;
  }
}

/* streaming operation: 
 *
 * accumulate data until we have a frame, then decode. 
 */
static GstFlowReturn
gst_dvdemux_chain (GstPad * pad, GstBuffer * buffer)
{
  GstDVDemux *dvdemux;
  GstFlowReturn ret;

  dvdemux = GST_DVDEMUX (gst_pad_get_parent (pad));

1051 1052 1053
  if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))
    gst_adapter_clear (dvdemux->adapter);

1054 1055 1056 1057
  /* temporary hack? Can't do this from the state change */
  if (!dvdemux->videosrcpad)
    gst_dvdemux_add_pads (dvdemux);

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  gst_adapter_push (dvdemux->adapter, buffer);

  /* Apparently dv_parse_header can read from the body of the frame
   * too, so it needs more than header_size bytes. Wacky!
   */
  if (dvdemux->frame_len == -1) {
    /* if we don't know the length of a frame, we assume it is
     * the NTSC_BUFFER length, as this is enough to figure out 
     * if this is PAL or NTSC */
    dvdemux->frame_len = NTSC_BUFFER;
  }

  /* and try to flush pending frames */
  ret = gst_dvdemux_flush (dvdemux);

  gst_object_unref (dvdemux);

  return ret;
}

1078 1079
static GstStateChangeReturn
gst_dvdemux_change_state (GstElement * element, GstStateChange transition)
1080 1081
{
  GstDVDemux *dvdemux = GST_DVDEMUX (element);
1082
  GstStateChangeReturn ret;
1083 1084 1085


  switch (transition) {
1086
    case GST_STATE_CHANGE_NULL_TO_READY:
1087
      break;
1088
    case GST_STATE_CHANGE_READY_TO_PAUSED:
1089
      dvdemux->decoder = dv_decoder_new (0, FALSE, FALSE);
1090
      dv_set_error_log (dvdemux->decoder, NULL);
1091 1092 1093 1094 1095
      dvdemux->audio_offset = 0;
      dvdemux->video_offset = 0;
      dvdemux->framecount = 0;
      dvdemux->found_header = FALSE;
      dvdemux->frame_len = -1;
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
      dvdemux->timestamp = 0LL;
      dvdemux->need_segment = FALSE;
      dvdemux->new_media = FALSE;
      dvdemux->framerate_numerator = 0;
      dvdemux->framerate_denominator = 0;
      dvdemux->total_frames = 0;
      dvdemux->height = 0;
      dvdemux->frequency = 0;
      dvdemux->channels = 0;
      dvdemux->wide = FALSE;
      gst_segment_init (&dvdemux->byte_segment, GST_FORMAT_BYTES);
      gst_segment_init (&dvdemux->time_segment, GST_FORMAT_TIME);
1108
      break;
1109
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1110 1111 1112 1113 1114
      break;
    default:
      break;
  }

1115
  ret = parent_class->change_state (element, transition);
1116 1117

  switch (transition) {
1118
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1119
      break;
1120
    case GST_STATE_CHANGE_PAUSED_TO_READY:
1121 1122 1123 1124
      gst_adapter_clear (dvdemux->adapter);
      dv_decoder_free (dvdemux->decoder);
      dvdemux->decoder = NULL;
      break;
1125
    case GST_STATE_CHANGE_READY_TO_NULL:
1126 1127 1128 1129 1130 1131
      break;
    default:
      break;
  }
  return ret;
}