gstflvdemux.c 103 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* GStreamer
 * Copyright (C) <2007> Julien Moutte <julien@moutte.net>
 *
 * 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
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
16 17
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
18 19
 */

20 21 22 23 24 25 26 27
/**
 * SECTION:element-flvdemux
 *
 * flvdemux demuxes an FLV file into the different contained streams.
 *
 * <refsect2>
 * <title>Example launch line</title>
 * |[
28
 * gst-launch-1.0 -v filesrc location=/path/to/flv ! flvdemux ! audioconvert ! autoaudiosink
29 30 31 32
 * ]| This pipeline demuxes an FLV file and outputs the contained raw audio streams.
 * </refsect2>
 */

33 34 35 36 37
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstflvdemux.h"
38
#include "gstflvmux.h"
39 40

#include <string.h>
41
#include <stdio.h>
42
#include <gst/base/gstbytereader.h>
43
#include <gst/base/gstbytewriter.h>
44
#include <gst/pbutils/descriptions.h>
45
#include <gst/pbutils/pbutils.h>
Wim Taymans's avatar
Wim Taymans committed
46
#include <gst/audio/audio.h>
47
#include <gst/video/video.h>
48
#include <gst/tag/tag.h>
49

50 51 52 53 54 55 56
/* FIXME: don't rely on own GstIndex */
#include "gstindex.c"
#include "gstmemindex.c"
#define GST_ASSOCIATION_FLAG_NONE GST_INDEX_ASSOCIATION_FLAG_NONE
#define GST_ASSOCIATION_FLAG_KEY_UNIT GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT
#define GST_ASSOCIATION_FLAG_DELTA_UNIT GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT

57 58 59 60 61 62 63
static GstStaticPadTemplate flv_sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("video/x-flv")
    );

static GstStaticPadTemplate audio_src_template =
Stefan Kost's avatar
Stefan Kost committed
64
    GST_STATIC_PAD_TEMPLATE ("audio",
65 66
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
Stefan Kost's avatar
Stefan Kost committed
67 68 69
    GST_STATIC_CAPS
    ("audio/x-adpcm, layout = (string) swf, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
        "audio/mpeg, mpegversion = (int) 1, layer = (int) 3, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 22050, 44100 }, parsed = (boolean) TRUE; "
70
        "audio/mpeg, mpegversion = (int) 4, stream-format = (string) raw, framed = (boolean) TRUE; "
Stefan Kost's avatar
Stefan Kost committed
71
        "audio/x-nellymoser, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 16000, 22050, 44100 }; "
Wim Taymans's avatar
Wim Taymans committed
72
        "audio/x-raw, format = (string) { U8, S16LE }, layout = (string) interleaved, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
Stefan Kost's avatar
Stefan Kost committed
73 74
        "audio/x-alaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
        "audio/x-mulaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
75
        "audio/x-speex, channels = (int) 1, rate = (int) 16000;")
Stefan Kost's avatar
Stefan Kost committed
76
    );
77 78

static GstStaticPadTemplate video_src_template =
Stefan Kost's avatar
Stefan Kost committed
79
    GST_STATIC_PAD_TEMPLATE ("video",
80 81
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
82
    GST_STATIC_CAPS ("video/x-flash-video, flvversion=(int) 1; "
Stefan Kost's avatar
Stefan Kost committed
83
        "video/x-flash-screen; "
84 85
        "video/x-vp6-flash; " "video/x-vp6-alpha; "
        "video/x-h264, stream-format=avc;")
Stefan Kost's avatar
Stefan Kost committed
86
    );
87

88
GST_DEBUG_CATEGORY_STATIC (flvdemux_debug);
89 90
#define GST_CAT_DEFAULT flvdemux_debug

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
91 92
#define gst_flv_demux_parent_class parent_class
G_DEFINE_TYPE (GstFlvDemux, gst_flv_demux, GST_TYPE_ELEMENT);
93

94
/* 9 bytes of header + 4 bytes of first previous tag size */
95
#define FLV_HEADER_SIZE 13
96
/* 1 byte of tag type + 3 bytes of tag data size */
97 98
#define FLV_TAG_TYPE_SIZE 4

99
/* two seconds - consider dts are resynced to another base if this different */
100 101
#define RESYNC_THRESHOLD 2000

102 103 104
/* how much stream time to wait for audio tags to appear after we have video, or vice versa */
#define NO_MORE_PADS_THRESHOLD (6 * GST_SECOND)

105
static gboolean flv_demux_handle_seek_push (GstFlvDemux * demux,
106
    GstEvent * event);
107
static gboolean gst_flv_demux_handle_seek_pull (GstFlvDemux * demux,
108
    GstEvent * event, gboolean seeking);
109

Wim Taymans's avatar
Wim Taymans committed
110 111
static gboolean gst_flv_demux_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
Wim Taymans's avatar
Wim Taymans committed
112 113
static gboolean gst_flv_demux_src_event (GstPad * pad, GstObject * parent,
    GstEvent * event);
114

115
static GstIndex *gst_flv_demux_get_index (GstElement * element);
116 117

static void
118
gst_flv_demux_parse_and_add_index_entry (GstFlvDemux * demux, GstClockTime ts,
119 120
    guint64 pos, gboolean keyframe)
{
121
  GstIndexAssociation associations[2];
122
  GstIndex *index;
123
  GstIndexEntry *entry;
124 125 126 127 128

  GST_LOG_OBJECT (demux,
      "adding key=%d association %" GST_TIME_FORMAT "-> %" G_GUINT64_FORMAT,
      keyframe, GST_TIME_ARGS (ts), pos);

129 130 131 132
  /* if upstream is not seekable there is no point in building an index */
  if (!demux->upstream_seekable)
    return;

133 134 135 136 137
  index = gst_flv_demux_get_index (GST_ELEMENT (demux));

  if (!index)
    return;

138
  /* entry may already have been added before, avoid adding indefinitely */
139
  entry = gst_index_get_assoc_entry (index, demux->index_id,
140 141 142 143
      GST_INDEX_LOOKUP_EXACT, GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_BYTES, pos);

  if (entry) {
#ifndef GST_DISABLE_GST_DEBUG
144
    gint64 time = 0;
145 146 147
    gboolean key;

    gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
Wim Taymans's avatar
Wim Taymans committed
148
    key = ! !(GST_INDEX_ASSOC_FLAGS (entry) & GST_ASSOCIATION_FLAG_KEY_UNIT);
149 150 151
    GST_LOG_OBJECT (demux, "position already mapped to time %" GST_TIME_FORMAT
        ", keyframe %d", GST_TIME_ARGS (time), key);
    /* there is not really a way to delete the existing one */
Wim Taymans's avatar
Wim Taymans committed
152
    if (time != ts || key != ! !keyframe)
153 154
      GST_DEBUG_OBJECT (demux, "metadata mismatch");
#endif
155
    gst_object_unref (index);
156 157 158 159 160 161 162 163
    return;
  }

  associations[0].format = GST_FORMAT_TIME;
  associations[0].value = ts;
  associations[1].format = GST_FORMAT_BYTES;
  associations[1].value = pos;

164
  gst_index_add_associationv (index, demux->index_id,
165 166 167
      (keyframe) ? GST_ASSOCIATION_FLAG_KEY_UNIT :
      GST_ASSOCIATION_FLAG_DELTA_UNIT, 2,
      (const GstIndexAssociation *) &associations);
168 169 170 171 172

  if (pos > demux->index_max_pos)
    demux->index_max_pos = pos;
  if (ts > demux->index_max_time)
    demux->index_max_time = ts;
173 174

  gst_object_unref (index);
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
}

static gchar *
FLV_GET_STRING (GstByteReader * reader)
{
  guint16 string_size = 0;
  gchar *string = NULL;
  const guint8 *str = NULL;

  g_return_val_if_fail (reader != NULL, NULL);

  if (G_UNLIKELY (!gst_byte_reader_get_uint16_be (reader, &string_size)))
    return NULL;

  if (G_UNLIKELY (string_size > gst_byte_reader_get_remaining (reader)))
    return NULL;

  string = g_try_malloc0 (string_size + 1);
  if (G_UNLIKELY (!string)) {
    return NULL;
  }

  if (G_UNLIKELY (!gst_byte_reader_get_data (reader, string_size, &str))) {
    g_free (string);
    return NULL;
  }

  memcpy (string, str, string_size);
  if (!g_utf8_validate (string, string_size, NULL)) {
    g_free (string);
    return NULL;
  }

  return string;
}

211 212 213 214 215 216 217 218 219 220 221
static void
gst_flv_demux_check_seekability (GstFlvDemux * demux)
{
  GstQuery *query;
  gint64 start = -1, stop = -1;

  demux->upstream_seekable = FALSE;

  query = gst_query_new_seeking (GST_FORMAT_BYTES);
  if (!gst_pad_peer_query (demux->sinkpad, query)) {
    GST_DEBUG_OBJECT (demux, "seeking query failed");
222
    gst_query_unref (query);
223 224 225 226 227 228
    return;
  }

  gst_query_parse_seeking (query, NULL, &demux->upstream_seekable,
      &start, &stop);

229 230
  gst_query_unref (query);

231 232 233
  /* try harder to query upstream size if we didn't get it the first time */
  if (demux->upstream_seekable && stop == -1) {
    GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
234
    gst_pad_peer_query_duration (demux->sinkpad, GST_FORMAT_BYTES, &stop);
235 236 237 238 239 240 241 242 243 244 245 246
  }

  /* if upstream doesn't know the size, it's likely that it's not seekable in
   * practice even if it technically may be seekable */
  if (demux->upstream_seekable && (start != 0 || stop <= start)) {
    GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
    demux->upstream_seekable = FALSE;
  }

  GST_DEBUG_OBJECT (demux, "upstream seekable: %d", demux->upstream_seekable);
}

247 248
static GstDateTime *
parse_flv_demux_parse_date_string (const gchar * s)
249
{
250 251 252 253 254 255 256 257 258 259 260 261
  static const gchar months[12][4] = {
    "Jan", "Feb", "Mar", "Apr",
    "May", "Jun", "Jul", "Aug",
    "Sep", "Oct", "Nov", "Dec"
  };
  GstDateTime *dt = NULL;
  gchar **tokens;
  guint64 d;
  gchar *endptr;
  gint i, hh, mm, ss;
  gint year = -1, month = -1, day = -1;
  gint hour = -1, minute = -1, seconds = -1;
262 263

  /* "Fri Oct 15 15:13:16 2004" needs to be parsed */
264
  tokens = g_strsplit (s, " ", -1);
265

266 267
  if (g_strv_length (tokens) != 5)
    goto out;
268

269 270 271 272
  /* year */
  d = g_ascii_strtoull (tokens[4], &endptr, 10);
  if (d == 0 && *endptr != '\0')
    goto out;
273

274
  year = d;
275

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  /* month */
  if (strlen (tokens[1]) != 3)
    goto out;
  for (i = 0; i < 12; i++) {
    if (!strcmp (tokens[1], months[i])) {
      break;
    }
  }
  if (i == 12)
    goto out;

  month = i + 1;

  /* day */
  d = g_ascii_strtoull (tokens[2], &endptr, 10);
  if (d == 0 && *endptr != '\0')
    goto out;

  day = d;

  /* time */
  hh = mm = ss = 0;
298
  if (sscanf (tokens[3], "%d:%d:%d", &hh, &mm, &ss) < 2)
299 300 301 302 303
    goto out;
  if (hh >= 0 && hh < 24 && mm >= 0 && mm < 60 && ss >= 0 && ss < 60) {
    hour = hh;
    minute = mm;
    seconds = ss;
304
  }
305 306 307 308 309 310 311 312 313 314

out:

  if (tokens)
    g_strfreev (tokens);

  if (year > 0)
    dt = gst_date_time_new (0.0, year, month, day, hour, minute, seconds);

  return dt;
315 316 317
}

static gboolean
318
gst_flv_demux_parse_metadata_item (GstFlvDemux * demux, GstByteReader * reader,
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    gboolean * end_marker)
{
  gchar *tag_name = NULL;
  guint8 tag_type = 0;

  /* Initialize the end_marker flag to FALSE */
  *end_marker = FALSE;

  /* Name of the tag */
  tag_name = FLV_GET_STRING (reader);
  if (G_UNLIKELY (!tag_name)) {
    GST_WARNING_OBJECT (demux, "failed reading tag name");
    return FALSE;
  }

  /* What kind of object is that */
  if (!gst_byte_reader_get_uint8 (reader, &tag_type))
    goto error;

  GST_DEBUG_OBJECT (demux, "tag name %s, tag type %d", tag_name, tag_type);

  switch (tag_type) {
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
341
    case 0:                    /* Double */
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    {                           /* Use a union to read the uint64 and then as a double */
      gdouble d = 0;

      if (!gst_byte_reader_get_float64_be (reader, &d))
        goto error;

      GST_DEBUG_OBJECT (demux, "%s => (double) %f", tag_name, d);

      if (!strcmp (tag_name, "duration")) {
        demux->duration = d * GST_SECOND;

        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_DURATION, demux->duration, NULL);
      } else if (!strcmp (tag_name, "AspectRatioX")) {
        demux->par_x = d;
        demux->got_par = TRUE;
      } else if (!strcmp (tag_name, "AspectRatioY")) {
        demux->par_y = d;
        demux->got_par = TRUE;
361 362 363 364 365 366
      } else if (!strcmp (tag_name, "width")) {
        demux->w = d;
      } else if (!strcmp (tag_name, "height")) {
        demux->h = d;
      } else if (!strcmp (tag_name, "framerate")) {
        demux->framerate = d;
367 368 369 370 371 372
      } else {
        GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
      }

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
373
    case 1:                    /* Boolean */
374 375 376 377 378 379 380 381 382 383 384 385
    {
      guint8 b = 0;

      if (!gst_byte_reader_get_uint8 (reader, &b))
        goto error;

      GST_DEBUG_OBJECT (demux, "%s => (boolean) %d", tag_name, b);

      GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
386
    case 2:                    /* String */
387 388 389 390 391 392 393 394 395 396
    {
      gchar *s = NULL;

      s = FLV_GET_STRING (reader);
      if (s == NULL)
        goto error;

      GST_DEBUG_OBJECT (demux, "%s => (string) %s", tag_name, s);

      if (!strcmp (tag_name, "creationdate")) {
397
        GstDateTime *dt;
398

399 400 401
        dt = parse_flv_demux_parse_date_string (s);
        if (dt == NULL) {
          GST_DEBUG_OBJECT (demux, "Failed to parse '%s' into datetime", s);
402 403
        } else {
          gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
404
              GST_TAG_DATE_TIME, dt, NULL);
405
        }
406
        gst_date_time_unref (dt);
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
      } else if (!strcmp (tag_name, "creator")) {
        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_ARTIST, s, NULL);
      } else if (!strcmp (tag_name, "title")) {
        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_TITLE, s, NULL);
      } else if (!strcmp (tag_name, "metadatacreator")) {
        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_ENCODER, s, NULL);
      } else {
        GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
      }

      g_free (s);

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
424
    case 3:                    /* Object */
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    {
      gboolean end_of_object_marker = FALSE;

      while (!end_of_object_marker) {
        gboolean ok = gst_flv_demux_parse_metadata_item (demux, reader,
            &end_of_object_marker);

        if (G_UNLIKELY (!ok)) {
          GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
          goto error;
        }
      }

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
440
    case 8:                    /* ECMA array */
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    {
      guint32 nb_elems = 0;
      gboolean end_of_object_marker = FALSE;

      if (!gst_byte_reader_get_uint32_be (reader, &nb_elems))
        goto error;

      GST_DEBUG_OBJECT (demux, "there are approx. %d elements in the array",
          nb_elems);

      while (!end_of_object_marker) {
        gboolean ok = gst_flv_demux_parse_metadata_item (demux, reader,
            &end_of_object_marker);

        if (G_UNLIKELY (!ok)) {
          GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
          goto error;
        }
      }

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
463
    case 9:                    /* End marker */
464 465 466 467 468 469 470 471 472 473 474
    {
      GST_DEBUG_OBJECT (demux, "end marker ?");
      if (tag_name[0] == '\0') {

        GST_DEBUG_OBJECT (demux, "end marker detected");

        *end_marker = TRUE;
      }

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
475
    case 10:                   /* Array */
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    {
      guint32 nb_elems = 0;

      if (!gst_byte_reader_get_uint32_be (reader, &nb_elems))
        goto error;

      GST_DEBUG_OBJECT (demux, "array has %d elements", nb_elems);

      if (!strcmp (tag_name, "times")) {
        if (demux->times) {
          g_array_free (demux->times, TRUE);
        }
        demux->times = g_array_new (FALSE, TRUE, sizeof (gdouble));
      } else if (!strcmp (tag_name, "filepositions")) {
        if (demux->filepositions) {
          g_array_free (demux->filepositions, TRUE);
        }
        demux->filepositions = g_array_new (FALSE, TRUE, sizeof (gdouble));
      }

      while (nb_elems--) {
        guint8 elem_type = 0;

        if (!gst_byte_reader_get_uint8 (reader, &elem_type))
          goto error;

        switch (elem_type) {
          case 0:
          {
            gdouble d;

            if (!gst_byte_reader_get_float64_be (reader, &d))
              goto error;

            GST_DEBUG_OBJECT (demux, "element is a double %f", d);

            if (!strcmp (tag_name, "times") && demux->times) {
              g_array_append_val (demux->times, d);
            } else if (!strcmp (tag_name, "filepositions") &&
                demux->filepositions) {
              g_array_append_val (demux->filepositions, d);
            }
            break;
          }
          default:
            GST_WARNING_OBJECT (demux, "unsupported array element type %d",
                elem_type);
        }
      }

      break;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
528
    case 11:                   /* Date */
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
    {
      gdouble d = 0;
      gint16 i = 0;

      if (!gst_byte_reader_get_float64_be (reader, &d))
        goto error;

      if (!gst_byte_reader_get_int16_be (reader, &i))
        goto error;

      GST_DEBUG_OBJECT (demux,
          "%s => (date as a double) %f, timezone offset %d", tag_name, d, i);

      GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);

      break;
    }
    default:
      GST_WARNING_OBJECT (demux, "unsupported tag type %d", tag_type);
  }

  g_free (tag_name);

  return TRUE;

error:
  g_free (tag_name);

  return FALSE;
}

static GstFlowReturn
561
gst_flv_demux_parse_tag_script (GstFlvDemux * demux, GstBuffer * buffer)
562 563
{
  GstFlowReturn ret = GST_FLOW_OK;
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
564
  GstByteReader reader;
565
  guint8 type = 0;
Wim Taymans's avatar
Wim Taymans committed
566
  GstMapInfo map;
567

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
568 569
  g_return_val_if_fail (gst_buffer_get_size (buffer) >= 7, GST_FLOW_ERROR);

Wim Taymans's avatar
Wim Taymans committed
570 571
  gst_buffer_map (buffer, &map, GST_MAP_READ);
  gst_byte_reader_init (&reader, map.data, map.size);
572

573
  gst_byte_reader_skip_unchecked (&reader, 7);
574 575 576 577

  GST_LOG_OBJECT (demux, "parsing a script tag");

  if (!gst_byte_reader_get_uint8 (&reader, &type))
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
578
    goto cleanup;
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

  /* Must be string */
  if (type == 2) {
    gchar *function_name;
    guint i;

    function_name = FLV_GET_STRING (&reader);

    GST_LOG_OBJECT (demux, "function name is %s", GST_STR_NULL (function_name));

    if (function_name != NULL && strcmp (function_name, "onMetaData") == 0) {
      gboolean end_marker = FALSE;
      GST_DEBUG_OBJECT (demux, "we have a metadata script object");

      if (!gst_byte_reader_get_uint8 (&reader, &type)) {
        g_free (function_name);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
595
        goto cleanup;
596 597 598 599 600 601 602 603 604 605
      }

      switch (type) {
        case 8:
        {
          guint32 nb_elems = 0;

          /* ECMA array */
          if (!gst_byte_reader_get_uint32_be (&reader, &nb_elems)) {
            g_free (function_name);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
606
            goto cleanup;
607 608
          }

609
          /* The number of elements is just a hint, some files have
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
             nb_elements == 0 and actually contain items. */
          GST_DEBUG_OBJECT (demux, "there are approx. %d elements in the array",
              nb_elems);
        }
          /* fallthrough to read data */
        case 3:
        {
          /* Object */
          while (!end_marker) {
            gboolean ok =
                gst_flv_demux_parse_metadata_item (demux, &reader, &end_marker);

            if (G_UNLIKELY (!ok)) {
              GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
              break;
            }
          }
        }
          break;
        default:
          GST_DEBUG_OBJECT (demux, "Unhandled script data type : %d", type);
          g_free (function_name);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
632
          goto cleanup;
633 634 635 636 637 638 639
      }

      demux->push_tags = TRUE;
    }

    g_free (function_name);

640
    if (demux->times && demux->filepositions) {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
      guint num;

      /* If an index was found, insert associations */
      num = MIN (demux->times->len, demux->filepositions->len);
      for (i = 0; i < num; i++) {
        guint64 time, fileposition;

        time = g_array_index (demux->times, gdouble, i) * GST_SECOND;
        fileposition = g_array_index (demux->filepositions, gdouble, i);
        gst_flv_demux_parse_and_add_index_entry (demux, time, fileposition,
            TRUE);
      }
      demux->indexed = TRUE;
    }
  }

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
657
cleanup:
Wim Taymans's avatar
Wim Taymans committed
658
  gst_buffer_unmap (buffer, &map);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
659

660 661 662
  return ret;
}

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
static gboolean
have_group_id (GstFlvDemux * demux)
{
  GstEvent *event;

  event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
  if (event) {
    if (gst_event_parse_group_id (event, &demux->group_id))
      demux->have_group_id = TRUE;
    else
      demux->have_group_id = FALSE;
    gst_event_unref (event);
  } else if (!demux->have_group_id) {
    demux->have_group_id = TRUE;
    demux->group_id = gst_util_group_id_next ();
  }

  return demux->have_group_id;
}

683
static gboolean
684
gst_flv_demux_audio_negotiate (GstFlvDemux * demux, guint32 codec_tag,
685 686
    guint32 rate, guint32 channels, guint32 width)
{
687
  GstCaps *caps = NULL, *old_caps;
688
  gchar *codec_name = NULL;
689
  gboolean ret = FALSE;
690
  guint adjusted_rate = rate;
691
  GstEvent *event;
692
  gchar *stream_id;
693 694 695 696 697 698 699 700 701 702 703 704 705 706

  switch (codec_tag) {
    case 1:
      caps = gst_caps_new_simple ("audio/x-adpcm", "layout", G_TYPE_STRING,
          "swf", NULL);
      break;
    case 2:
    case 14:
      caps = gst_caps_new_simple ("audio/mpeg",
          "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, 3,
          "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
      break;
    case 0:
    case 3:
Wim Taymans's avatar
Wim Taymans committed
707 708 709
    {
      GstAudioFormat format;

710 711 712
      /* Assuming little endian for 0 (aka endianness of the
       * system on which the file was created) as most people
       * are probably using little endian machines */
Wim Taymans's avatar
Wim Taymans committed
713 714 715 716 717 718
      format = gst_audio_format_build_integer ((width == 8) ? FALSE : TRUE,
          G_LITTLE_ENDIAN, width, width);

      caps = gst_caps_new_simple ("audio/x-raw",
          "format", G_TYPE_STRING, gst_audio_format_to_string (format),
          "layout", G_TYPE_STRING, "interleaved", NULL);
719
      break;
Wim Taymans's avatar
Wim Taymans committed
720
    }
721 722 723
    case 4:
    case 5:
    case 6:
724
      caps = gst_caps_new_empty_simple ("audio/x-nellymoser");
725 726
      break;
    case 10:
727
    {
728 729 730 731 732 733
      GstMapInfo map;
      if (!demux->audio_codec_data) {
        GST_DEBUG_OBJECT (demux, "don't have AAC codec data yet");
        ret = TRUE;
        goto done;
      }
Wim Taymans's avatar
Wim Taymans committed
734

735
      gst_buffer_map (demux->audio_codec_data, &map, GST_MAP_READ);
Wim Taymans's avatar
Wim Taymans committed
736

737 738 739
      /* use codec-data to extract and verify samplerate */
      if (map.size >= 2) {
        gint freq_index;
Wim Taymans's avatar
Wim Taymans committed
740

741 742 743 744
        freq_index = GST_READ_UINT16_BE (map.data);
        freq_index = (freq_index & 0x0780) >> 7;
        adjusted_rate =
            gst_codec_utils_aac_get_sample_rate_from_index (freq_index);
Wim Taymans's avatar
Wim Taymans committed
745

746 747 748 749 750
        if (adjusted_rate && (rate != adjusted_rate)) {
          GST_LOG_OBJECT (demux, "Ajusting AAC sample rate %d -> %d", rate,
              adjusted_rate);
        } else {
          adjusted_rate = rate;
751 752
        }
      }
753
      gst_buffer_unmap (demux->audio_codec_data, &map);
Wim Taymans's avatar
Wim Taymans committed
754

755
      caps = gst_caps_new_simple ("audio/mpeg",
756 757
          "mpegversion", G_TYPE_INT, 4, "framed", G_TYPE_BOOLEAN, TRUE,
          "stream-format", G_TYPE_STRING, "raw", NULL);
758
      break;
759
    }
760
    case 7:
761
      caps = gst_caps_new_empty_simple ("audio/x-alaw");
762 763
      break;
    case 8:
764
      caps = gst_caps_new_empty_simple ("audio/x-mulaw");
765 766
      break;
    case 11:
767 768 769
    {
      GValue streamheader = G_VALUE_INIT;
      GValue value = G_VALUE_INIT;
770
      GstByteWriter w;
771 772
      GstStructure *structure;
      GstBuffer *buf;
773
      GstTagList *tags;
774

775
      caps = gst_caps_new_empty_simple ("audio/x-speex");
776 777 778 779
      structure = gst_caps_get_structure (caps, 0);

      GST_DEBUG_OBJECT (demux, "generating speex header");

780 781
      /* Speex decoder expects streamheader to be { [header], [comment] } */
      g_value_init (&streamheader, GST_TYPE_ARRAY);
782

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
      /* header part */
      gst_byte_writer_init_with_size (&w, 80, TRUE);
      gst_byte_writer_put_data (&w, (guint8 *) "Speex   ", 8);
      gst_byte_writer_put_data (&w, (guint8 *) "1.1.12", 7);
      gst_byte_writer_fill (&w, 0, 13);
      gst_byte_writer_put_uint32_le (&w, 1);    /* version */
      gst_byte_writer_put_uint32_le (&w, 80);   /* header_size */
      gst_byte_writer_put_uint32_le (&w, 16000);        /* rate */
      gst_byte_writer_put_uint32_le (&w, 1);    /* mode: Wideband */
      gst_byte_writer_put_uint32_le (&w, 4);    /* mode_bitstream_version */
      gst_byte_writer_put_uint32_le (&w, 1);    /* nb_channels: 1 */
      gst_byte_writer_put_uint32_le (&w, -1);   /* bitrate */
      gst_byte_writer_put_uint32_le (&w, 0x50); /* frame_size */
      gst_byte_writer_put_uint32_le (&w, 0);    /* VBR */
      gst_byte_writer_put_uint32_le (&w, 1);    /* frames_per_packet */
      gst_byte_writer_put_uint32_le (&w, 0);    /* extra_headers */
      gst_byte_writer_put_uint32_le (&w, 0);    /* reserved1 */
      gst_byte_writer_put_uint32_le (&w, 0);    /* reserved2 */
      g_assert (gst_byte_writer_get_size (&w) == 80);
802 803

      g_value_init (&value, GST_TYPE_BUFFER);
804
      g_value_take_boxed (&value, gst_byte_writer_reset_and_get_buffer (&w));
805
      gst_value_array_append_value (&streamheader, &value);
806
      g_value_unset (&value);
807

808 809
      /* comment part */
      g_value_init (&value, GST_TYPE_BUFFER);
810
      tags = gst_tag_list_new_empty ();
811
      buf = gst_tag_list_to_vorbiscomment_buffer (tags, NULL, 0, "No comments");
812
      gst_tag_list_unref (tags);
813 814
      g_value_take_boxed (&value, buf);
      gst_value_array_append_value (&streamheader, &value);
815
      g_value_unset (&value);
816 817

      gst_structure_take_value (structure, "streamheader", &streamheader);
818 819 820

      channels = 1;
      adjusted_rate = 16000;
821
      break;
822
    }
823 824
    default:
      GST_WARNING_OBJECT (demux, "unsupported audio codec tag %u", codec_tag);
825
      break;
826 827 828 829 830 831 832
  }

  if (G_UNLIKELY (!caps)) {
    GST_WARNING_OBJECT (demux, "failed creating caps for audio pad");
    goto beach;
  }

833 834
  gst_caps_set_simple (caps, "rate", G_TYPE_INT, adjusted_rate,
      "channels", G_TYPE_INT, channels, NULL);
835 836 837 838 839 840

  if (demux->audio_codec_data) {
    gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER,
        demux->audio_codec_data, NULL);
  }

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
  old_caps = gst_pad_get_current_caps (demux->audio_pad);
  if (!old_caps) {
    stream_id =
        gst_pad_create_stream_id (demux->audio_pad, GST_ELEMENT_CAST (demux),
        "audio");

    event = gst_event_new_stream_start (stream_id);
    if (have_group_id (demux))
      gst_event_set_group_id (event, demux->group_id);
    gst_pad_push_event (demux->audio_pad, event);
    g_free (stream_id);
  }
  if (!old_caps || !gst_caps_is_equal (old_caps, caps))
    ret = gst_pad_set_caps (demux->audio_pad, caps);
  else
    ret = TRUE;
857

858 859
  if (old_caps)
    gst_caps_unref (old_caps);
860

861
done:
862
  if (G_LIKELY (ret)) {
863
    /* Store the caps we got from tags */
864 865 866 867 868
    demux->audio_codec_tag = codec_tag;
    demux->rate = rate;
    demux->channels = channels;
    demux->width = width;

869 870
    if (caps) {
      codec_name = gst_pb_utils_get_codec_description (caps);
871

872 873 874 875 876 877 878
      if (codec_name) {
        if (demux->taglist == NULL)
          demux->taglist = gst_tag_list_new_empty ();
        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_AUDIO_CODEC, codec_name, NULL);
        g_free (codec_name);
      }
879

880 881 882 883 884
      GST_DEBUG_OBJECT (demux->audio_pad, "successfully negotiated caps %"
          GST_PTR_FORMAT, caps);
    } else {
      GST_DEBUG_OBJECT (demux->audio_pad, "delayed setting caps");
    }
885 886 887 888 889
  } else {
    GST_WARNING_OBJECT (demux->audio_pad, "failed negotiating caps %"
        GST_PTR_FORMAT, caps);
  }

890 891
  if (caps)
    gst_caps_unref (caps);
892 893 894 895 896

beach:
  return ret;
}

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
static gboolean
gst_flv_demux_push_src_event (GstFlvDemux * demux, GstEvent * event)
{
  gboolean ret = TRUE;

  if (demux->audio_pad)
    ret |= gst_pad_push_event (demux->audio_pad, gst_event_ref (event));

  if (demux->video_pad)
    ret |= gst_pad_push_event (demux->video_pad, gst_event_ref (event));

  gst_event_unref (event);

  return ret;
}

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
static void
gst_flv_demux_push_tags (GstFlvDemux * demux)
{
  if (demux->has_audio && !demux->audio_pad) {
    GST_DEBUG_OBJECT (demux,
        "Waiting for audio stream pad to come up before we can push tags");
    return;
  }
  if (demux->has_video && !demux->video_pad) {
    GST_DEBUG_OBJECT (demux,
        "Waiting for video stream pad to come up before we can push tags");
    return;
  }
  if (demux->taglist) {
    GST_DEBUG_OBJECT (demux, "pushing tags out %" GST_PTR_FORMAT,
        demux->taglist);
929 930
    gst_tag_list_set_scope (demux->taglist, GST_TAG_SCOPE_GLOBAL);
    gst_flv_demux_push_src_event (demux, gst_event_new_tag (demux->taglist));
931
    demux->taglist = gst_tag_list_new_empty ();
932 933 934 935
    demux->push_tags = FALSE;
  }
}

936
static gboolean
937
gst_flv_demux_update_resync (GstFlvDemux * demux, guint32 dts, gboolean discont,
Vincent Penquerc'h's avatar
Vincent Penquerc'h committed
938
    guint32 * last, GstClockTime * offset)
939
{
940
  gboolean ret = FALSE;
941
  gint32 ddts = dts - *last;
942
  if (!discont && ddts <= -RESYNC_THRESHOLD) {
943 944 945
    /* Theoretically, we should use substract the duration of the last buffer,
       but this demuxer sends no durations on buffers, not sure if it cannot
       know, or just does not care to calculate. */
946
    *offset -= ddts * GST_MSECOND;
947
    GST_WARNING_OBJECT (demux,
948 949
        "Large dts gap (%" G_GINT32_FORMAT " ms), assuming resync, offset now %"
        GST_TIME_FORMAT "", ddts, GST_TIME_ARGS (*offset));
950 951

    ret = TRUE;
952
  }
953
  *last = dts;
954 955

  return ret;
956 957
}

958
static GstFlowReturn
959
gst_flv_demux_parse_tag_audio (GstFlvDemux * demux, GstBuffer * buffer)
960 961 962 963 964
{
  GstFlowReturn ret = GST_FLOW_OK;
  guint32 pts = 0, codec_tag = 0, rate = 5512, width = 8, channels = 1;
  guint32 codec_data = 0, pts_ext = 0;
  guint8 flags = 0;
Wim Taymans's avatar
Wim Taymans committed
965
  GstMapInfo map;
966
  GstBuffer *outbuf;
Wim Taymans's avatar
Wim Taymans committed
967
  guint8 *data;
968 969 970

  GST_LOG_OBJECT (demux, "parsing an audio tag");

Vineeth TM's avatar
Vineeth TM committed
971
  if (G_UNLIKELY (!demux->audio_pad && demux->no_more_pads)) {
972
#ifndef GST_DISABLE_DEBUG
Vineeth TM's avatar
Vineeth TM committed
973
    if (G_UNLIKELY (!demux->no_audio_warned)) {
974 975 976
      GST_WARNING_OBJECT (demux,
          "Signaled no-more-pads already but had no audio pad -- ignoring");
      demux->no_audio_warned = TRUE;
Vineeth TM's avatar
Vineeth TM committed
977
    }
978
#endif
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
979
    return GST_FLOW_OK;
Vineeth TM's avatar
Vineeth TM committed
980
  }
981

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
982
  g_return_val_if_fail (gst_buffer_get_size (buffer) == demux->tag_size,
983 984
      GST_FLOW_ERROR);

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
985 986
  /* Error out on tags with too small headers */
  if (gst_buffer_get_size (buffer) < 11) {
987
    GST_ERROR_OBJECT (demux, "Too small tag size (%" G_GSIZE_FORMAT ")",
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
988 989 990 991
        gst_buffer_get_size (buffer));
    return GST_FLOW_ERROR;
  }

Wim Taymans's avatar
Wim Taymans committed
992 993
  gst_buffer_map (buffer, &map, GST_MAP_READ);
  data = map.data;
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
994

995 996 997 998 999 1000 1001
  /* Grab information about audio tag */
  pts = GST_READ_UINT24_BE (data);
  /* read the pts extension to 32 bits integer */
  pts_ext = GST_READ_UINT8 (data + 3);
  /* Combine them */
  pts |= pts_ext << 24;

1002 1003 1004
  GST_LOG_OBJECT (demux, "pts bytes %02X %02X %02X %02X (%d)", data[0], data[1],
      data[2], data[3], pts);

1005 1006 1007
  /* Skip the stream id and go directly to the flags */
  flags = GST_READ_UINT8 (data + 7);

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1008
  /* Silently skip buffers with no data */
Wim Taymans's avatar
Wim Taymans committed
1009
  if (map.size == 11)
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1010 1011
    goto beach;

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  /* Channels */
  if (flags & 0x01) {
    channels = 2;
  }
  /* Width */
  if (flags & 0x02) {
    width = 16;
  }
  /* Sampling rate */
  if ((flags & 0x0C) == 0x0C) {
    rate = 44100;
  } else if ((flags & 0x0C) == 0x08) {
    rate = 22050;
  } else if ((flags & 0x0C) == 0x04) {
    rate = 11025;
  }
  /* Codec tag */
  codec_tag = flags >> 4;
  if (codec_tag == 10) {        /* AAC has an extra byte for packet type */
    codec_data = 2;
  } else {
    codec_data = 1;
  }

  /* codec tags with special rates */
  if (codec_tag == 5 || codec_tag == 14)
    rate = 8000;
1039
  else if ((codec_tag == 4) || (codec_tag == 11))
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    rate = 16000;

  GST_LOG_OBJECT (demux, "audio tag with %d channels, %dHz sampling rate, "
      "%d bits width, codec tag %u (flags %02X)", channels, rate, width,
      codec_tag, flags);

  /* If we don't have our audio pad created, then create it. */
  if (G_UNLIKELY (!demux->audio_pad)) {

    demux->audio_pad =
        gst_pad_new_from_template (gst_element_class_get_pad_template
        (GST_ELEMENT_GET_CLASS (demux), "audio"), "audio");
    if (G_UNLIKELY (!demux->audio_pad)) {
      GST_WARNING_OBJECT (demux, "failed creating audio pad");
      ret = GST_FLOW_ERROR;
      goto beach;
    }

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    /* Set functions on the pad */
    gst_pad_set_query_function (demux->audio_pad,
        GST_DEBUG_FUNCPTR (gst_flv_demux_query));
    gst_pad_set_event_function (demux->audio_pad,
        GST_DEBUG_FUNCPTR (gst_flv_demux_src_event));

    gst_pad_use_fixed_caps (demux->audio_pad);

    /* Make it active */
    gst_pad_set_active (demux->audio_pad, TRUE);

1069 1070 1071 1072 1073 1074 1075 1076
    /* Negotiate caps */
    if (!gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels,
            width)) {
      gst_object_unref (demux->audio_pad);
      demux->audio_pad = NULL;
      ret = GST_FLOW_ERROR;
      goto beach;
    }
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1077 1078 1079
#ifndef GST_DISABLE_GST_DEBUG
    {
      GstCaps *caps;
1080

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1081 1082 1083 1084 1085 1086 1087
      caps = gst_pad_get_current_caps (demux->audio_pad);
      GST_DEBUG_OBJECT (demux, "created audio pad with caps %" GST_PTR_FORMAT,
          caps);
      if (caps)
        gst_caps_unref (caps);
    }
#endif
1088 1089 1090 1091

    /* We need to set caps before adding */
    gst_element_add_pad (GST_ELEMENT (demux),
        gst_object_ref (demux->audio_pad));
1092
    gst_flow_combiner_add_pad (demux->flowcombiner, demux->audio_pad);
1093 1094

    /* We only emit no more pads when we have audio and video. Indeed we can
1095
     * not trust the FLV header to tell us if there will be only audio or
1096 1097 1098 1099 1100
     * only video and we would just break discovery of some files */
    if (demux->audio_pad && demux->video_pad) {
      GST_DEBUG_OBJECT (demux, "emitting no more pads");
      gst_element_no_more_pads (GST_ELEMENT (demux));
      demux->no_more_pads = TRUE;
1101
      demux->push_tags = TRUE;
1102 1103 1104 1105 1106 1107 1108 1109
    }
  }

  /* Check if caps have changed */
  if (G_UNLIKELY (rate != demux->rate || channels != demux->channels ||
          codec_tag != demux->audio_codec_tag || width != demux->width)) {
    GST_DEBUG_OBJECT (demux, "audio settings have changed, changing caps");

1110 1111
    gst_buffer_replace (&demux->audio_codec_data, NULL);

1112 1113 1114 1115 1116 1117 1118 1119 1120
    /* Negotiate caps */
    if (!gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels,
            width)) {
      ret = GST_FLOW_ERROR;
      goto beach;
    }
  }

  /* Push taglist if present */
1121 1122
  if (G_UNLIKELY (demux->push_tags))
    gst_flv_demux_push_tags (demux);
1123 1124 1125 1126 1127 1128 1129 1130

  /* Check if we have anything to push */
  if (demux->tag_data_size <= codec_data) {
    GST_LOG_OBJECT (demux, "Nothing left in this tag, returning");
    goto beach;
  }

  /* Create buffer from pad */
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1131 1132
  outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_MEMORY,
      7 + codec_data, demux->tag_data_size - codec_data);
1133 1134 1135 1136 1137 1138 1139

  if (demux->audio_codec_tag == 10) {
    guint8 aac_packet_type = GST_READ_UINT8 (data + 8);

    switch (aac_packet_type) {
      case 0:
      {
1140
        /* AudioSpecificConfig data */
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
        GST_LOG_OBJECT (demux, "got an AAC codec data packet");
        if (demux->audio_codec_data) {
          gst_buffer_unref (demux->audio_codec_data);
        }
        demux->audio_codec_data = outbuf;
        /* Use that buffer data in the caps */
        gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels, width);
        goto beach;
      }
      case 1:
1151 1152 1153 1154 1155 1156
        if (!demux->audio_codec_data) {
          GST_ERROR_OBJECT (demux, "got AAC audio packet before codec data");
          ret = GST_FLOW_OK;
          gst_buffer_unref (outbuf);
          goto beach;
        }
1157 1158 1159 1160 1161 1162 1163 1164 1165
        /* AAC raw packet */
        GST_LOG_OBJECT (demux, "got a raw AAC audio packet");
        break;
      default:
        GST_WARNING_OBJECT (demux, "invalid AAC packet type %u",
            aac_packet_type);
    }
  }

1166
  /* detect (and deem to be resyncs)  large pts gaps */
1167
  if (gst_flv_demux_update_resync (demux, pts, demux->audio_need_discont,
1168
          &demux->last_audio_pts, &demux->audio_time_offset)) {
1169 1170
    GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
  }
1171

1172
  /* Fill buffer with data */
1173 1174
  GST_BUFFER_PTS (outbuf) = pts * GST_MSECOND + demux->audio_time_offset;
  GST_BUFFER_DTS (outbuf) = GST_BUFFER_PTS (outbuf);
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
  GST_BUFFER_OFFSET (outbuf) = demux->audio_offset++;
  GST_BUFFER_OFFSET_END (outbuf) = demux->audio_offset;

  if (demux->duration == GST_CLOCK_TIME_NONE ||
      demux->duration < GST_BUFFER_TIMESTAMP (outbuf))
    demux->duration = GST_BUFFER_TIMESTAMP (outbuf);

  /* Only add audio frames to the index if we have no video,
   * and if the index is not yet complete */
1185
  if (!demux->has_video && !demux->indexed) {
1186 1187 1188 1189 1190 1191 1192 1193 1194
    gst_flv_demux_parse_and_add_index_entry (demux,
        GST_BUFFER_TIMESTAMP (outbuf), demux->cur_tag_offset, TRUE);
  }

  if (G_UNLIKELY (demux->audio_need_discont)) {
    GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
    demux->audio_need_discont = FALSE;
  }

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1195
  demux->segment.position = GST_BUFFER_TIMESTAMP (outbuf);
1196 1197 1198 1199 1200 1201

  /* Do we need a newsegment event ? */
  if (G_UNLIKELY (demux->audio_need_segment)) {
    if (!demux->new_seg_event) {
      GST_DEBUG_OBJECT (demux, "pushing newsegment from %"
          GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1202
          GST_TIME_ARGS (demux->segment.position),
1203
          GST_TIME_ARGS (demux->segment.stop));
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1204 1205
      demux->segment.start = demux->segment.time = demux->segment.position;
      demux->new_seg_event = gst_event_new_segment (&demux->segment);
1206 1207 1208 1209 1210 1211 1212 1213 1214
    } else {
      GST_DEBUG_OBJECT (demux, "pushing pre-generated newsegment event");
    }

    gst_pad_push_event (demux->audio_pad, gst_event_ref (demux->new_seg_event));

    demux->audio_need_segment = FALSE;
  }

1215 1216
  GST_LOG_OBJECT (demux,
      "pushing %" G_GSIZE_FORMAT " bytes buffer at pts %" GST_TIME_FORMAT
1217
      " with duration %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT,
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1218 1219
      gst_buffer_get_size (outbuf),
      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
      GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf));

  if (!GST_CLOCK_TIME_IS_VALID (demux->audio_start)) {
    demux->audio_start = GST_BUFFER_TIMESTAMP (outbuf);
  }
  if (!GST_CLOCK_TIME_IS_VALID (demux->audio_first_ts)) {
    demux->audio_first_ts = GST_BUFFER_TIMESTAMP (outbuf);
  }

  if (G_UNLIKELY (!demux->no_more_pads
          && (GST_CLOCK_DIFF (demux->audio_start,
1231
                  GST_BUFFER_TIMESTAMP (outbuf)) > NO_MORE_PADS_THRESHOLD))) {
1232 1233 1234 1235 1236
    GST_DEBUG_OBJECT (demux,
        "Signalling no-more-pads because no video stream was found"
        " after 6 seconds of audio");
    gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
    demux->no_more_pads = TRUE;
1237
    demux->push_tags = TRUE;
1238 1239 1240 1241
  }

  /* Push downstream */
  ret = gst_pad_push (demux->audio_pad, outbuf);
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

  if (G_UNLIKELY (ret != GST_FLOW_OK) &&
      demux->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
      demux->segment.position > demux->segment.stop) {
    /* In reverse playback we can get a GST_FLOW_EOS when
     * we are at the end of the segment, so we just need to jump
     * back to the previous section. */
    GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
    demux->audio_done = TRUE;
    ret = GST_FLOW_OK;
    goto beach;
1253 1254
  }

1255 1256
  ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
      demux->audio_pad, ret);
1257 1258

beach:
Wim Taymans's avatar
Wim Taymans committed
1259
  gst_buffer_unmap (buffer, &map);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
1260

1261 1262 1263 1264
  return ret;
}

static gboolean
1265
gst_flv_demux_video_negotiate (GstFlvDemux * demux, guint32 codec_tag)
1266 1267
{
  gboolean ret = FALSE;
1268
  GstCaps *caps = NULL, *old_caps;
1269
  gchar *codec_name = NULL;
1270
  GstEvent *event;
1271
  gchar *stream_id;
1272 1273 1274 1275

  /* Generate caps for that pad */
  switch (codec_tag) {
    case 2:
1276 1277 1278
      caps =
          gst_caps_new_simple ("video/x-flash-video", "flvversion", G_TYPE_INT,
          1, NULL);
1279 1280
      break;
    case 3:
1281
      caps = gst_caps_new_empty_simple ("video/x-flash-screen");
1282 1283
      break;
    case 4:
1284
      caps = gst_caps_new_empty_simple ("video/x-vp6-flash");
1285 1286
      break;
    case 5:
1287
      caps = gst_caps_new_empty_simple ("video/x-vp6-alpha");
1288 1289
      break;
    case 7:
1290 1291 1292 1293 1294
      if (!demux->video_codec_data) {
        GST_DEBUG_OBJECT (demux, "don't have h264 codec data yet");
        ret = TRUE;
        goto done;
      }
1295 1296 1297
      caps =
          gst_caps_new_simple ("video/x-h264", "stream-format", G_TYPE_STRING,
          "avc", NULL);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
      break;
    default:
      GST_WARNING_OBJECT (demux, "unsupported video codec tag %u", codec_tag);
  }

  if (G_UNLIKELY (!caps)) {
    GST_WARNING_OBJECT (demux, "failed creating caps for video pad");
    goto beach;
  }

  gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
      demux->par_x, demux->par_y, NULL);

1311 1312 1313 1314 1315 1316 1317 1318 1319
  if (G_LIKELY (demux->w)) {
    gst_caps_set_simple (caps, "width", G_TYPE_INT, demux->w, NULL);
  }

  if (G_LIKELY (demux->h)) {
    gst_caps_set_simple (caps, "height", G_TYPE_INT, demux->h, NULL);
  }

  if (G_LIKELY (demux->framerate)) {
1320
    gint num = 0, den = 0;
1321

1322
    gst_video_guess_framerate (GST_SECOND / demux->framerate, &num, &den);
1323 1324 1325 1326 1327 1328 1329
    GST_DEBUG_OBJECT (demux->video_pad,
        "fps to be used on caps %f (as a fraction = %d/%d)", demux->framerate,
        num, den);

    gst_caps_set_simple (caps, "framerate", GST_TYPE_FRACTION, num, den, NULL);
  }

1330 1331 1332 1333 1334
  if (demux->video_codec_data) {
    gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER,
        demux->video_codec_data, NULL);
  }

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  old_caps = gst_pad_get_current_caps (demux->video_pad);
  if (!old_caps) {
    stream_id =
        gst_pad_create_stream_id (demux->video_pad, GST_ELEMENT_CAST (demux),
        "video");
    event = gst_event_new_stream_start (stream_id);
    g_free (stream_id);

    if (have_group_id (demux))
      gst_event_set_group_id (event, demux->group_id);
    gst_pad_push_event (demux->video_pad, event);
  }

  if (!old_caps || !gst_caps_is_equal (old_caps, caps))
    ret = gst_pad_set_caps (demux->video_pad, caps);
  else
    ret = TRUE;
1352

1353 1354
  if (old_caps)
    gst_caps_unref (old_caps);
1355

1356
done:
1357 1358 1359 1360
  if (G_LIKELY (ret)) {
    /* Store the caps we have set */
    demux->video_codec_tag = codec_tag;

1361 1362
    if (caps) {
      codec_name = gst_pb_utils_get_codec_description (caps);
1363

1364 1365 1366 1367 1368 1369 1370
      if (codec_name) {
        if (demux->taglist == NULL)
          demux->taglist = gst_tag_list_new_empty ();
        gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
            GST_TAG_VIDEO_CODEC, codec_name, NULL);
        g_free (codec_name);
      }
1371