Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst / flv / gstflvdemux.c
1 /* GStreamer
2  * Copyright (C) <2007> Julien Moutte <julien@moutte.net>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-flvdemux
22  *
23  * flvdemux demuxes an FLV file into the different contained streams.
24  *
25  * <refsect2>
26  * <title>Example launch line</title>
27  * |[
28  * gst-launch -v filesrc location=/path/to/flv ! flvdemux ! audioconvert ! autoaudiosink
29  * ]| This pipeline demuxes an FLV file and outputs the contained raw audio streams.
30  * </refsect2>
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include "gstflvdemux.h"
38 #include "gstflvmux.h"
39
40 #include <string.h>
41 #include <gst/base/gstbytereader.h>
42 #include <gst/pbutils/descriptions.h>
43 #include <gst/pbutils/pbutils.h>
44
45 static GstStaticPadTemplate flv_sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
46     GST_PAD_SINK,
47     GST_PAD_ALWAYS,
48     GST_STATIC_CAPS ("video/x-flv")
49     );
50
51 static GstStaticPadTemplate audio_src_template =
52     GST_STATIC_PAD_TEMPLATE ("audio",
53     GST_PAD_SRC,
54     GST_PAD_SOMETIMES,
55     GST_STATIC_CAPS
56     ("audio/x-adpcm, layout = (string) swf, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
57         "audio/mpeg, mpegversion = (int) 1, layer = (int) 3, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 22050, 44100 }, parsed = (boolean) TRUE; "
58         "audio/mpeg, mpegversion = (int) 4, framed = (boolean) TRUE; "
59         "audio/x-nellymoser, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 16000, 22050, 44100 }; "
60         "audio/x-raw-int, endianness = (int) LITTLE_ENDIAN, channels = (int) { 1, 2 }, width = (int) 8, depth = (int) 8, rate = (int) { 5512, 11025, 22050, 44100 }, signed = (boolean) FALSE; "
61         "audio/x-raw-int, endianness = (int) LITTLE_ENDIAN, channels = (int) { 1, 2 }, width = (int) 16, depth = (int) 16, rate = (int) { 5512, 11025, 22050, 44100 }, signed = (boolean) TRUE; "
62         "audio/x-alaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
63         "audio/x-mulaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
64         "audio/x-speex, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 };")
65     );
66
67 static GstStaticPadTemplate video_src_template =
68     GST_STATIC_PAD_TEMPLATE ("video",
69     GST_PAD_SRC,
70     GST_PAD_SOMETIMES,
71     GST_STATIC_CAPS ("video/x-flash-video; "
72         "video/x-flash-screen; "
73         "video/x-vp6-flash; " "video/x-vp6-alpha; "
74         "video/x-h264, stream-format=avc;")
75     );
76
77 GST_DEBUG_CATEGORY_STATIC (flvdemux_debug);
78 #define GST_CAT_DEFAULT flvdemux_debug
79
80 #define gst_flv_demux_parent_class parent_class
81 G_DEFINE_TYPE (GstFlvDemux, gst_flv_demux, GST_TYPE_ELEMENT);
82
83 /* 9 bytes of header + 4 bytes of first previous tag size */
84 #define FLV_HEADER_SIZE 13
85 /* 1 byte of tag type + 3 bytes of tag data size */
86 #define FLV_TAG_TYPE_SIZE 4
87
88 static gboolean flv_demux_handle_seek_push (GstFlvDemux * demux,
89     GstEvent * event);
90 static gboolean gst_flv_demux_handle_seek_pull (GstFlvDemux * demux,
91     GstEvent * event, gboolean seeking);
92
93 static gboolean gst_flv_demux_query (GstPad * pad, GstQuery * query);
94 static gboolean gst_flv_demux_src_event (GstPad * pad, GstEvent * event);
95
96
97 static void
98 gst_flv_demux_parse_and_add_index_entry (GstFlvDemux * demux, GstClockTime ts,
99     guint64 pos, gboolean keyframe)
100 {
101   static GstIndexAssociation associations[2];
102   static GstIndexEntry *entry;
103
104   GST_LOG_OBJECT (demux,
105       "adding key=%d association %" GST_TIME_FORMAT "-> %" G_GUINT64_FORMAT,
106       keyframe, GST_TIME_ARGS (ts), pos);
107
108   /* if upstream is not seekable there is no point in building an index */
109   if (!demux->upstream_seekable)
110     return;
111
112   /* entry may already have been added before, avoid adding indefinitely */
113   entry = gst_index_get_assoc_entry (demux->index, demux->index_id,
114       GST_INDEX_LOOKUP_EXACT, GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_BYTES, pos);
115
116   if (entry) {
117 #ifndef GST_DISABLE_GST_DEBUG
118     gint64 time;
119     gboolean key;
120
121     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
122     key = ! !(GST_INDEX_ASSOC_FLAGS (entry) & GST_ASSOCIATION_FLAG_KEY_UNIT);
123     GST_LOG_OBJECT (demux, "position already mapped to time %" GST_TIME_FORMAT
124         ", keyframe %d", GST_TIME_ARGS (time), key);
125     /* there is not really a way to delete the existing one */
126     if (time != ts || key != ! !keyframe)
127       GST_DEBUG_OBJECT (demux, "metadata mismatch");
128 #endif
129     return;
130   }
131
132   associations[0].format = GST_FORMAT_TIME;
133   associations[0].value = ts;
134   associations[1].format = GST_FORMAT_BYTES;
135   associations[1].value = pos;
136
137   gst_index_add_associationv (demux->index, demux->index_id,
138       (keyframe) ? GST_ASSOCIATION_FLAG_KEY_UNIT :
139       GST_ASSOCIATION_FLAG_DELTA_UNIT, 2,
140       (const GstIndexAssociation *) &associations);
141
142   if (pos > demux->index_max_pos)
143     demux->index_max_pos = pos;
144   if (ts > demux->index_max_time)
145     demux->index_max_time = ts;
146 }
147
148 static gchar *
149 FLV_GET_STRING (GstByteReader * reader)
150 {
151   guint16 string_size = 0;
152   gchar *string = NULL;
153   const guint8 *str = NULL;
154
155   g_return_val_if_fail (reader != NULL, NULL);
156
157   if (G_UNLIKELY (!gst_byte_reader_get_uint16_be (reader, &string_size)))
158     return NULL;
159
160   if (G_UNLIKELY (string_size > gst_byte_reader_get_remaining (reader)))
161     return NULL;
162
163   string = g_try_malloc0 (string_size + 1);
164   if (G_UNLIKELY (!string)) {
165     return NULL;
166   }
167
168   if (G_UNLIKELY (!gst_byte_reader_get_data (reader, string_size, &str))) {
169     g_free (string);
170     return NULL;
171   }
172
173   memcpy (string, str, string_size);
174   if (!g_utf8_validate (string, string_size, NULL)) {
175     g_free (string);
176     return NULL;
177   }
178
179   return string;
180 }
181
182 static const GstQueryType *
183 gst_flv_demux_query_types (GstPad * pad)
184 {
185   static const GstQueryType query_types[] = {
186     GST_QUERY_DURATION,
187     GST_QUERY_POSITION,
188     GST_QUERY_SEEKING,
189     0
190   };
191
192   return query_types;
193 }
194
195 static void
196 gst_flv_demux_check_seekability (GstFlvDemux * demux)
197 {
198   GstQuery *query;
199   gint64 start = -1, stop = -1;
200
201   demux->upstream_seekable = FALSE;
202
203   query = gst_query_new_seeking (GST_FORMAT_BYTES);
204   if (!gst_pad_peer_query (demux->sinkpad, query)) {
205     GST_DEBUG_OBJECT (demux, "seeking query failed");
206     gst_query_unref (query);
207     return;
208   }
209
210   gst_query_parse_seeking (query, NULL, &demux->upstream_seekable,
211       &start, &stop);
212
213   gst_query_unref (query);
214
215   /* try harder to query upstream size if we didn't get it the first time */
216   if (demux->upstream_seekable && stop == -1) {
217     GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
218     gst_pad_query_peer_duration (demux->sinkpad, GST_FORMAT_BYTES, &stop);
219   }
220
221   /* if upstream doesn't know the size, it's likely that it's not seekable in
222    * practice even if it technically may be seekable */
223   if (demux->upstream_seekable && (start != 0 || stop <= start)) {
224     GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
225     demux->upstream_seekable = FALSE;
226   }
227
228   GST_DEBUG_OBJECT (demux, "upstream seekable: %d", demux->upstream_seekable);
229 }
230
231 static void
232 parse_flv_demux_parse_date_string (GDate * date, const gchar * s)
233 {
234   g_date_set_parse (date, s);
235   if (g_date_valid (date))
236     return;
237
238   /* "Fri Oct 15 15:13:16 2004" needs to be parsed */
239   {
240     static const gchar *months[] = {
241       "Jan", "Feb", "Mar", "Apr",
242       "May", "Jun", "Jul", "Aug",
243       "Sep", "Oct", "Nov", "Dec"
244     };
245     gchar **tokens = g_strsplit (s, " ", -1);
246     guint64 d;
247     gchar *endptr;
248     gint i;
249
250     if (g_strv_length (tokens) != 5)
251       goto out;
252
253     if (strlen (tokens[1]) != 3)
254       goto out;
255     for (i = 0; i < 12; i++) {
256       if (!strcmp (tokens[1], months[i])) {
257         break;
258       }
259     }
260     if (i == 12)
261       goto out;
262     g_date_set_month (date, i + 1);
263
264     d = g_ascii_strtoull (tokens[2], &endptr, 10);
265     if (d == 0 && *endptr != '\0')
266       goto out;
267
268     g_date_set_day (date, d);
269
270     d = g_ascii_strtoull (tokens[4], &endptr, 10);
271     if (d == 0 && *endptr != '\0')
272       goto out;
273
274     g_date_set_year (date, d);
275
276   out:
277     if (tokens)
278       g_strfreev (tokens);
279   }
280 }
281
282 static gboolean
283 gst_flv_demux_parse_metadata_item (GstFlvDemux * demux, GstByteReader * reader,
284     gboolean * end_marker)
285 {
286   gchar *tag_name = NULL;
287   guint8 tag_type = 0;
288
289   /* Initialize the end_marker flag to FALSE */
290   *end_marker = FALSE;
291
292   /* Name of the tag */
293   tag_name = FLV_GET_STRING (reader);
294   if (G_UNLIKELY (!tag_name)) {
295     GST_WARNING_OBJECT (demux, "failed reading tag name");
296     return FALSE;
297   }
298
299   /* What kind of object is that */
300   if (!gst_byte_reader_get_uint8 (reader, &tag_type))
301     goto error;
302
303   GST_DEBUG_OBJECT (demux, "tag name %s, tag type %d", tag_name, tag_type);
304
305   switch (tag_type) {
306     case 0:                    // Double
307     {                           /* Use a union to read the uint64 and then as a double */
308       gdouble d = 0;
309
310       if (!gst_byte_reader_get_float64_be (reader, &d))
311         goto error;
312
313       GST_DEBUG_OBJECT (demux, "%s => (double) %f", tag_name, d);
314
315       if (!strcmp (tag_name, "duration")) {
316         demux->duration = d * GST_SECOND;
317
318         gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
319             GST_TAG_DURATION, demux->duration, NULL);
320       } else if (!strcmp (tag_name, "AspectRatioX")) {
321         demux->par_x = d;
322         demux->got_par = TRUE;
323       } else if (!strcmp (tag_name, "AspectRatioY")) {
324         demux->par_y = d;
325         demux->got_par = TRUE;
326       } else if (!strcmp (tag_name, "width")) {
327         demux->w = d;
328       } else if (!strcmp (tag_name, "height")) {
329         demux->h = d;
330       } else if (!strcmp (tag_name, "framerate")) {
331         demux->framerate = d;
332       } else {
333         GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
334       }
335
336       break;
337     }
338     case 1:                    // Boolean
339     {
340       guint8 b = 0;
341
342       if (!gst_byte_reader_get_uint8 (reader, &b))
343         goto error;
344
345       GST_DEBUG_OBJECT (demux, "%s => (boolean) %d", tag_name, b);
346
347       GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
348
349       break;
350     }
351     case 2:                    // String
352     {
353       gchar *s = NULL;
354
355       s = FLV_GET_STRING (reader);
356       if (s == NULL)
357         goto error;
358
359       GST_DEBUG_OBJECT (demux, "%s => (string) %s", tag_name, s);
360
361       if (!strcmp (tag_name, "creationdate")) {
362         GDate *date = g_date_new ();
363
364         parse_flv_demux_parse_date_string (date, s);
365         if (!g_date_valid (date)) {
366           GST_DEBUG_OBJECT (demux, "Failed to parse string as date");
367         } else {
368           gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
369               GST_TAG_DATE, date, NULL);
370         }
371         g_date_free (date);
372       } else if (!strcmp (tag_name, "creator")) {
373         gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
374             GST_TAG_ARTIST, s, NULL);
375       } else if (!strcmp (tag_name, "title")) {
376         gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
377             GST_TAG_TITLE, s, NULL);
378       } else if (!strcmp (tag_name, "metadatacreator")) {
379         gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
380             GST_TAG_ENCODER, s, NULL);
381       } else {
382         GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
383       }
384
385       g_free (s);
386
387       break;
388     }
389     case 3:                    // Object
390     {
391       gboolean end_of_object_marker = FALSE;
392
393       while (!end_of_object_marker) {
394         gboolean ok = gst_flv_demux_parse_metadata_item (demux, reader,
395             &end_of_object_marker);
396
397         if (G_UNLIKELY (!ok)) {
398           GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
399           goto error;
400         }
401       }
402
403       break;
404     }
405     case 8:                    // ECMA array
406     {
407       guint32 nb_elems = 0;
408       gboolean end_of_object_marker = FALSE;
409
410       if (!gst_byte_reader_get_uint32_be (reader, &nb_elems))
411         goto error;
412
413       GST_DEBUG_OBJECT (demux, "there are approx. %d elements in the array",
414           nb_elems);
415
416       while (!end_of_object_marker) {
417         gboolean ok = gst_flv_demux_parse_metadata_item (demux, reader,
418             &end_of_object_marker);
419
420         if (G_UNLIKELY (!ok)) {
421           GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
422           goto error;
423         }
424       }
425
426       break;
427     }
428     case 9:                    // End marker
429     {
430       GST_DEBUG_OBJECT (demux, "end marker ?");
431       if (tag_name[0] == '\0') {
432
433         GST_DEBUG_OBJECT (demux, "end marker detected");
434
435         *end_marker = TRUE;
436       }
437
438       break;
439     }
440     case 10:                   // Array
441     {
442       guint32 nb_elems = 0;
443
444       if (!gst_byte_reader_get_uint32_be (reader, &nb_elems))
445         goto error;
446
447       GST_DEBUG_OBJECT (demux, "array has %d elements", nb_elems);
448
449       if (!strcmp (tag_name, "times")) {
450         if (demux->times) {
451           g_array_free (demux->times, TRUE);
452         }
453         demux->times = g_array_new (FALSE, TRUE, sizeof (gdouble));
454       } else if (!strcmp (tag_name, "filepositions")) {
455         if (demux->filepositions) {
456           g_array_free (demux->filepositions, TRUE);
457         }
458         demux->filepositions = g_array_new (FALSE, TRUE, sizeof (gdouble));
459       }
460
461       while (nb_elems--) {
462         guint8 elem_type = 0;
463
464         if (!gst_byte_reader_get_uint8 (reader, &elem_type))
465           goto error;
466
467         switch (elem_type) {
468           case 0:
469           {
470             gdouble d;
471
472             if (!gst_byte_reader_get_float64_be (reader, &d))
473               goto error;
474
475             GST_DEBUG_OBJECT (demux, "element is a double %f", d);
476
477             if (!strcmp (tag_name, "times") && demux->times) {
478               g_array_append_val (demux->times, d);
479             } else if (!strcmp (tag_name, "filepositions") &&
480                 demux->filepositions) {
481               g_array_append_val (demux->filepositions, d);
482             }
483             break;
484           }
485           default:
486             GST_WARNING_OBJECT (demux, "unsupported array element type %d",
487                 elem_type);
488         }
489       }
490
491       break;
492     }
493     case 11:                   // Date
494     {
495       gdouble d = 0;
496       gint16 i = 0;
497
498       if (!gst_byte_reader_get_float64_be (reader, &d))
499         goto error;
500
501       if (!gst_byte_reader_get_int16_be (reader, &i))
502         goto error;
503
504       GST_DEBUG_OBJECT (demux,
505           "%s => (date as a double) %f, timezone offset %d", tag_name, d, i);
506
507       GST_INFO_OBJECT (demux, "Tag \'%s\' not handled", tag_name);
508
509       break;
510     }
511     default:
512       GST_WARNING_OBJECT (demux, "unsupported tag type %d", tag_type);
513   }
514
515   g_free (tag_name);
516
517   return TRUE;
518
519 error:
520   g_free (tag_name);
521
522   return FALSE;
523 }
524
525 static GstFlowReturn
526 gst_flv_demux_parse_tag_script (GstFlvDemux * demux, GstBuffer * buffer)
527 {
528   GstFlowReturn ret = GST_FLOW_OK;
529   GstByteReader reader;
530   guint8 type = 0;
531   guint8 *data;
532   gsize size;
533
534   g_return_val_if_fail (gst_buffer_get_size (buffer) >= 7, GST_FLOW_ERROR);
535
536   data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
537   gst_byte_reader_init (&reader, data, size);
538
539   gst_byte_reader_skip (&reader, 7);
540
541   GST_LOG_OBJECT (demux, "parsing a script tag");
542
543   if (!gst_byte_reader_get_uint8 (&reader, &type))
544     goto cleanup;
545
546   /* Must be string */
547   if (type == 2) {
548     gchar *function_name;
549     guint i;
550
551     function_name = FLV_GET_STRING (&reader);
552
553     GST_LOG_OBJECT (demux, "function name is %s", GST_STR_NULL (function_name));
554
555     if (function_name != NULL && strcmp (function_name, "onMetaData") == 0) {
556       gboolean end_marker = FALSE;
557       GST_DEBUG_OBJECT (demux, "we have a metadata script object");
558
559       if (!gst_byte_reader_get_uint8 (&reader, &type)) {
560         g_free (function_name);
561         goto cleanup;
562       }
563
564       switch (type) {
565         case 8:
566         {
567           guint32 nb_elems = 0;
568
569           /* ECMA array */
570           if (!gst_byte_reader_get_uint32_be (&reader, &nb_elems)) {
571             g_free (function_name);
572             goto cleanup;
573           }
574
575           /* The number of elements is just a hint, some files have
576              nb_elements == 0 and actually contain items. */
577           GST_DEBUG_OBJECT (demux, "there are approx. %d elements in the array",
578               nb_elems);
579         }
580           /* fallthrough to read data */
581         case 3:
582         {
583           /* Object */
584           while (!end_marker) {
585             gboolean ok =
586                 gst_flv_demux_parse_metadata_item (demux, &reader, &end_marker);
587
588             if (G_UNLIKELY (!ok)) {
589               GST_WARNING_OBJECT (demux, "failed reading a tag, skipping");
590               break;
591             }
592           }
593         }
594           break;
595         default:
596           GST_DEBUG_OBJECT (demux, "Unhandled script data type : %d", type);
597           g_free (function_name);
598           goto cleanup;
599       }
600
601       demux->push_tags = TRUE;
602     }
603
604     g_free (function_name);
605
606     if (demux->index && demux->times && demux->filepositions) {
607       guint num;
608
609       /* If an index was found, insert associations */
610       num = MIN (demux->times->len, demux->filepositions->len);
611       for (i = 0; i < num; i++) {
612         guint64 time, fileposition;
613
614         time = g_array_index (demux->times, gdouble, i) * GST_SECOND;
615         fileposition = g_array_index (demux->filepositions, gdouble, i);
616         gst_flv_demux_parse_and_add_index_entry (demux, time, fileposition,
617             TRUE);
618       }
619       demux->indexed = TRUE;
620     }
621   }
622
623 cleanup:
624   gst_buffer_unmap (buffer, data, -1);
625
626   return ret;
627 }
628
629 static gboolean
630 gst_flv_demux_audio_negotiate (GstFlvDemux * demux, guint32 codec_tag,
631     guint32 rate, guint32 channels, guint32 width)
632 {
633   GstCaps *caps = NULL;
634   gchar *codec_name = NULL;
635   gboolean ret = FALSE;
636   guint adjusted_rate = rate;
637
638   switch (codec_tag) {
639     case 1:
640       caps = gst_caps_new_simple ("audio/x-adpcm", "layout", G_TYPE_STRING,
641           "swf", NULL);
642       break;
643     case 2:
644     case 14:
645       caps = gst_caps_new_simple ("audio/mpeg",
646           "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, 3,
647           "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
648       break;
649     case 0:
650     case 3:
651       /* Assuming little endian for 0 (aka endianness of the
652        * system on which the file was created) as most people
653        * are probably using little endian machines */
654       caps = gst_caps_new_simple ("audio/x-raw-int",
655           "endianness", G_TYPE_INT, G_LITTLE_ENDIAN,
656           "signed", G_TYPE_BOOLEAN, (width == 8) ? FALSE : TRUE,
657           "width", G_TYPE_INT, width, "depth", G_TYPE_INT, width, NULL);
658       break;
659     case 4:
660     case 5:
661     case 6:
662       caps = gst_caps_new_simple ("audio/x-nellymoser", NULL);
663       break;
664     case 10:
665     {
666       guint8 *data = NULL;
667       gsize size;
668
669       if (demux->audio_codec_data)
670         data = gst_buffer_map (demux->audio_codec_data, &size, NULL,
671             GST_MAP_READ);
672       /* use codec-data to extract and verify samplerate */
673       if (demux->audio_codec_data && size >= 2) {
674         gint freq_index;
675
676         freq_index = GST_READ_UINT16_BE (data);
677         freq_index = (freq_index & 0x0780) >> 7;
678         adjusted_rate =
679             gst_codec_utils_aac_get_sample_rate_from_index (freq_index);
680
681         if (adjusted_rate && (rate != adjusted_rate)) {
682           GST_LOG_OBJECT (demux, "Ajusting AAC sample rate %d -> %d", rate,
683               adjusted_rate);
684         } else {
685           adjusted_rate = rate;
686         }
687       }
688       if (data)
689         gst_buffer_unmap (demux->audio_codec_data, data, -1);
690       caps = gst_caps_new_simple ("audio/mpeg",
691           "mpegversion", G_TYPE_INT, 4, "framed", G_TYPE_BOOLEAN, TRUE,
692           "stream-format", G_TYPE_STRING, "raw", NULL);
693       break;
694     }
695     case 7:
696       caps = gst_caps_new_simple ("audio/x-alaw", NULL);
697       break;
698     case 8:
699       caps = gst_caps_new_simple ("audio/x-mulaw", NULL);
700       break;
701     case 11:
702       caps = gst_caps_new_simple ("audio/x-speex", NULL);
703       break;
704     default:
705       GST_WARNING_OBJECT (demux, "unsupported audio codec tag %u", codec_tag);
706   }
707
708   if (G_UNLIKELY (!caps)) {
709     GST_WARNING_OBJECT (demux, "failed creating caps for audio pad");
710     goto beach;
711   }
712
713   gst_caps_set_simple (caps, "rate", G_TYPE_INT, adjusted_rate,
714       "channels", G_TYPE_INT, channels, NULL);
715
716   if (demux->audio_codec_data) {
717     gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER,
718         demux->audio_codec_data, NULL);
719   }
720
721   ret = gst_pad_set_caps (demux->audio_pad, caps);
722
723   if (G_LIKELY (ret)) {
724     /* Store the caps we got from tags */
725     demux->audio_codec_tag = codec_tag;
726     demux->rate = rate;
727     demux->channels = channels;
728     demux->width = width;
729
730     codec_name = gst_pb_utils_get_codec_description (caps);
731
732     if (codec_name) {
733       if (demux->taglist == NULL)
734         demux->taglist = gst_tag_list_new ();
735       gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
736           GST_TAG_AUDIO_CODEC, codec_name, NULL);
737       g_free (codec_name);
738     }
739
740     GST_DEBUG_OBJECT (demux->audio_pad, "successfully negotiated caps %"
741         GST_PTR_FORMAT, caps);
742   } else {
743     GST_WARNING_OBJECT (demux->audio_pad, "failed negotiating caps %"
744         GST_PTR_FORMAT, caps);
745   }
746
747   gst_caps_unref (caps);
748
749 beach:
750   return ret;
751 }
752
753 static void
754 gst_flv_demux_push_tags (GstFlvDemux * demux)
755 {
756   if (demux->has_audio && !demux->audio_pad) {
757     GST_DEBUG_OBJECT (demux,
758         "Waiting for audio stream pad to come up before we can push tags");
759     return;
760   }
761   if (demux->has_video && !demux->video_pad) {
762     GST_DEBUG_OBJECT (demux,
763         "Waiting for video stream pad to come up before we can push tags");
764     return;
765   }
766   if (demux->taglist) {
767     GST_DEBUG_OBJECT (demux, "pushing tags out %" GST_PTR_FORMAT,
768         demux->taglist);
769     gst_element_found_tags (GST_ELEMENT (demux), demux->taglist);
770     demux->taglist = gst_tag_list_new ();
771     demux->push_tags = FALSE;
772   }
773 }
774
775 static GstFlowReturn
776 gst_flv_demux_parse_tag_audio (GstFlvDemux * demux, GstBuffer * buffer)
777 {
778   GstFlowReturn ret = GST_FLOW_OK;
779   guint32 pts = 0, codec_tag = 0, rate = 5512, width = 8, channels = 1;
780   guint32 codec_data = 0, pts_ext = 0;
781   guint8 flags = 0;
782   guint8 *data;
783   GstBuffer *outbuf;
784   gsize size;
785
786   GST_LOG_OBJECT (demux, "parsing an audio tag");
787
788   if (demux->no_more_pads && !demux->audio_pad) {
789     GST_WARNING_OBJECT (demux,
790         "Signaled no-more-pads already but had no audio pad -- ignoring");
791     return GST_FLOW_OK;
792   }
793
794   g_return_val_if_fail (gst_buffer_get_size (buffer) == demux->tag_size,
795       GST_FLOW_ERROR);
796
797   /* Error out on tags with too small headers */
798   if (gst_buffer_get_size (buffer) < 11) {
799     GST_ERROR_OBJECT (demux, "Too small tag size (%d)",
800         gst_buffer_get_size (buffer));
801     return GST_FLOW_ERROR;
802   }
803
804   data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
805
806   /* Grab information about audio tag */
807   pts = GST_READ_UINT24_BE (data);
808   /* read the pts extension to 32 bits integer */
809   pts_ext = GST_READ_UINT8 (data + 3);
810   /* Combine them */
811   pts |= pts_ext << 24;
812
813   GST_LOG_OBJECT (demux, "pts bytes %02X %02X %02X %02X (%d)", data[0], data[1],
814       data[2], data[3], pts);
815
816   /* Skip the stream id and go directly to the flags */
817   flags = GST_READ_UINT8 (data + 7);
818
819   /* Silently skip buffers with no data */
820   if (size == 11)
821     goto beach;
822
823   /* Channels */
824   if (flags & 0x01) {
825     channels = 2;
826   }
827   /* Width */
828   if (flags & 0x02) {
829     width = 16;
830   }
831   /* Sampling rate */
832   if ((flags & 0x0C) == 0x0C) {
833     rate = 44100;
834   } else if ((flags & 0x0C) == 0x08) {
835     rate = 22050;
836   } else if ((flags & 0x0C) == 0x04) {
837     rate = 11025;
838   }
839   /* Codec tag */
840   codec_tag = flags >> 4;
841   if (codec_tag == 10) {        /* AAC has an extra byte for packet type */
842     codec_data = 2;
843   } else {
844     codec_data = 1;
845   }
846
847   /* codec tags with special rates */
848   if (codec_tag == 5 || codec_tag == 14)
849     rate = 8000;
850   else if (codec_tag == 4)
851     rate = 16000;
852
853   GST_LOG_OBJECT (demux, "audio tag with %d channels, %dHz sampling rate, "
854       "%d bits width, codec tag %u (flags %02X)", channels, rate, width,
855       codec_tag, flags);
856
857   /* If we don't have our audio pad created, then create it. */
858   if (G_UNLIKELY (!demux->audio_pad)) {
859
860     demux->audio_pad =
861         gst_pad_new_from_template (gst_element_class_get_pad_template
862         (GST_ELEMENT_GET_CLASS (demux), "audio"), "audio");
863     if (G_UNLIKELY (!demux->audio_pad)) {
864       GST_WARNING_OBJECT (demux, "failed creating audio pad");
865       ret = GST_FLOW_ERROR;
866       goto beach;
867     }
868
869     /* Negotiate caps */
870     if (!gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels,
871             width)) {
872       gst_object_unref (demux->audio_pad);
873       demux->audio_pad = NULL;
874       ret = GST_FLOW_ERROR;
875       goto beach;
876     }
877 #ifndef GST_DISABLE_GST_DEBUG
878     {
879       GstCaps *caps;
880
881       caps = gst_pad_get_current_caps (demux->audio_pad);
882       GST_DEBUG_OBJECT (demux, "created audio pad with caps %" GST_PTR_FORMAT,
883           caps);
884       if (caps)
885         gst_caps_unref (caps);
886     }
887 #endif
888
889     /* Set functions on the pad */
890     gst_pad_set_query_type_function (demux->audio_pad,
891         GST_DEBUG_FUNCPTR (gst_flv_demux_query_types));
892     gst_pad_set_query_function (demux->audio_pad,
893         GST_DEBUG_FUNCPTR (gst_flv_demux_query));
894     gst_pad_set_event_function (demux->audio_pad,
895         GST_DEBUG_FUNCPTR (gst_flv_demux_src_event));
896
897     gst_pad_use_fixed_caps (demux->audio_pad);
898
899     /* Make it active */
900     gst_pad_set_active (demux->audio_pad, TRUE);
901
902     /* We need to set caps before adding */
903     gst_element_add_pad (GST_ELEMENT (demux),
904         gst_object_ref (demux->audio_pad));
905
906     /* We only emit no more pads when we have audio and video. Indeed we can
907      * not trust the FLV header to tell us if there will be only audio or
908      * only video and we would just break discovery of some files */
909     if (demux->audio_pad && demux->video_pad) {
910       GST_DEBUG_OBJECT (demux, "emitting no more pads");
911       gst_element_no_more_pads (GST_ELEMENT (demux));
912       demux->no_more_pads = TRUE;
913       demux->push_tags = TRUE;
914     }
915   }
916
917   /* Check if caps have changed */
918   if (G_UNLIKELY (rate != demux->rate || channels != demux->channels ||
919           codec_tag != demux->audio_codec_tag || width != demux->width)) {
920     GST_DEBUG_OBJECT (demux, "audio settings have changed, changing caps");
921
922     /* Negotiate caps */
923     if (!gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels,
924             width)) {
925       ret = GST_FLOW_ERROR;
926       goto beach;
927     }
928   }
929
930   /* Push taglist if present */
931   if (G_UNLIKELY (demux->push_tags))
932     gst_flv_demux_push_tags (demux);
933
934   /* Check if we have anything to push */
935   if (demux->tag_data_size <= codec_data) {
936     GST_LOG_OBJECT (demux, "Nothing left in this tag, returning");
937     goto beach;
938   }
939
940   /* Create buffer from pad */
941   outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_MEMORY,
942       7 + codec_data, demux->tag_data_size - codec_data);
943
944   if (demux->audio_codec_tag == 10) {
945     guint8 aac_packet_type = GST_READ_UINT8 (data + 8);
946
947     switch (aac_packet_type) {
948       case 0:
949       {
950         /* AudioSpecificConfig data */
951         GST_LOG_OBJECT (demux, "got an AAC codec data packet");
952         if (demux->audio_codec_data) {
953           gst_buffer_unref (demux->audio_codec_data);
954         }
955         demux->audio_codec_data = outbuf;
956         /* Use that buffer data in the caps */
957         gst_flv_demux_audio_negotiate (demux, codec_tag, rate, channels, width);
958         goto beach;
959         break;
960       }
961       case 1:
962         /* AAC raw packet */
963         GST_LOG_OBJECT (demux, "got a raw AAC audio packet");
964         break;
965       default:
966         GST_WARNING_OBJECT (demux, "invalid AAC packet type %u",
967             aac_packet_type);
968     }
969   }
970
971   /* Fill buffer with data */
972   GST_BUFFER_TIMESTAMP (outbuf) = pts * GST_MSECOND;
973   GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
974   GST_BUFFER_OFFSET (outbuf) = demux->audio_offset++;
975   GST_BUFFER_OFFSET_END (outbuf) = demux->audio_offset;
976
977   if (demux->duration == GST_CLOCK_TIME_NONE ||
978       demux->duration < GST_BUFFER_TIMESTAMP (outbuf))
979     demux->duration = GST_BUFFER_TIMESTAMP (outbuf);
980
981   /* Only add audio frames to the index if we have no video,
982    * and if the index is not yet complete */
983   if (!demux->has_video && demux->index && !demux->indexed) {
984     gst_flv_demux_parse_and_add_index_entry (demux,
985         GST_BUFFER_TIMESTAMP (outbuf), demux->cur_tag_offset, TRUE);
986   }
987
988   if (G_UNLIKELY (demux->audio_need_discont)) {
989     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
990     demux->audio_need_discont = FALSE;
991   }
992
993   demux->segment.position = GST_BUFFER_TIMESTAMP (outbuf);
994
995   /* Do we need a newsegment event ? */
996   if (G_UNLIKELY (demux->audio_need_segment)) {
997     /* FIXME need one segment sent for all stream to maintain a/v sync */
998     if (!demux->new_seg_event) {
999       GST_DEBUG_OBJECT (demux, "pushing newsegment from %"
1000           GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
1001           GST_TIME_ARGS (demux->segment.position),
1002           GST_TIME_ARGS (demux->segment.stop));
1003       demux->segment.start = demux->segment.time = demux->segment.position;
1004       demux->new_seg_event = gst_event_new_segment (&demux->segment);
1005     } else {
1006       GST_DEBUG_OBJECT (demux, "pushing pre-generated newsegment event");
1007     }
1008
1009     gst_pad_push_event (demux->audio_pad, gst_event_ref (demux->new_seg_event));
1010
1011     demux->audio_need_segment = FALSE;
1012   }
1013
1014   GST_LOG_OBJECT (demux, "pushing %d bytes buffer at pts %" GST_TIME_FORMAT
1015       " with duration %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT,
1016       gst_buffer_get_size (outbuf),
1017       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1018       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf));
1019
1020   if (!GST_CLOCK_TIME_IS_VALID (demux->audio_start)) {
1021     demux->audio_start = GST_BUFFER_TIMESTAMP (outbuf);
1022   }
1023   if (!GST_CLOCK_TIME_IS_VALID (demux->audio_first_ts)) {
1024     demux->audio_first_ts = GST_BUFFER_TIMESTAMP (outbuf);
1025   }
1026
1027   if (G_UNLIKELY (!demux->no_more_pads
1028           && (GST_CLOCK_DIFF (demux->audio_start,
1029                   GST_BUFFER_TIMESTAMP (outbuf)) > 6 * GST_SECOND))) {
1030     GST_DEBUG_OBJECT (demux,
1031         "Signalling no-more-pads because no video stream was found"
1032         " after 6 seconds of audio");
1033     gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
1034     demux->no_more_pads = TRUE;
1035     demux->push_tags = TRUE;
1036   }
1037
1038   /* Push downstream */
1039   ret = gst_pad_push (demux->audio_pad, outbuf);
1040   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1041     if (demux->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
1042         demux->segment.position > demux->segment.stop) {
1043       /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
1044        * we are at the end of the segment, so we just need to jump
1045        * back to the previous section. */
1046       GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
1047       demux->audio_done = TRUE;
1048       ret = GST_FLOW_OK;
1049     } else {
1050       GST_WARNING_OBJECT (demux, "failed pushing a %" G_GUINT64_FORMAT
1051           " bytes audio buffer: %s", demux->tag_data_size,
1052           gst_flow_get_name (ret));
1053       if (ret == GST_FLOW_NOT_LINKED) {
1054         demux->audio_linked = FALSE;
1055       }
1056       goto beach;
1057     }
1058   }
1059
1060   demux->audio_linked = TRUE;
1061
1062 beach:
1063   gst_buffer_unmap (buffer, data, -1);
1064
1065   return ret;
1066 }
1067
1068 static gboolean
1069 gst_flv_demux_video_negotiate (GstFlvDemux * demux, guint32 codec_tag)
1070 {
1071   gboolean ret = FALSE;
1072   GstCaps *caps = NULL;
1073   gchar *codec_name = NULL;
1074
1075   /* Generate caps for that pad */
1076   switch (codec_tag) {
1077     case 2:
1078       caps = gst_caps_new_simple ("video/x-flash-video", NULL);
1079       break;
1080     case 3:
1081       caps = gst_caps_new_simple ("video/x-flash-screen", NULL);
1082       break;
1083     case 4:
1084       caps = gst_caps_new_simple ("video/x-vp6-flash", NULL);
1085       break;
1086     case 5:
1087       caps = gst_caps_new_simple ("video/x-vp6-alpha", NULL);
1088       break;
1089     case 7:
1090       caps =
1091           gst_caps_new_simple ("video/x-h264", "stream-format", G_TYPE_STRING,
1092           "avc", NULL);
1093       break;
1094     default:
1095       GST_WARNING_OBJECT (demux, "unsupported video codec tag %u", codec_tag);
1096   }
1097
1098   if (G_UNLIKELY (!caps)) {
1099     GST_WARNING_OBJECT (demux, "failed creating caps for video pad");
1100     goto beach;
1101   }
1102
1103   gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1104       demux->par_x, demux->par_y, NULL);
1105
1106   if (G_LIKELY (demux->w)) {
1107     gst_caps_set_simple (caps, "width", G_TYPE_INT, demux->w, NULL);
1108   }
1109
1110   if (G_LIKELY (demux->h)) {
1111     gst_caps_set_simple (caps, "height", G_TYPE_INT, demux->h, NULL);
1112   }
1113
1114   if (G_LIKELY (demux->framerate)) {
1115     gint num = 0, den = 0;
1116
1117     gst_util_double_to_fraction (demux->framerate, &num, &den);
1118     GST_DEBUG_OBJECT (demux->video_pad,
1119         "fps to be used on caps %f (as a fraction = %d/%d)", demux->framerate,
1120         num, den);
1121
1122     gst_caps_set_simple (caps, "framerate", GST_TYPE_FRACTION, num, den, NULL);
1123   }
1124
1125   if (demux->video_codec_data) {
1126     gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER,
1127         demux->video_codec_data, NULL);
1128   }
1129
1130   ret = gst_pad_set_caps (demux->video_pad, caps);
1131
1132   if (G_LIKELY (ret)) {
1133     /* Store the caps we have set */
1134     demux->video_codec_tag = codec_tag;
1135
1136     codec_name = gst_pb_utils_get_codec_description (caps);
1137
1138     if (codec_name) {
1139       if (demux->taglist == NULL)
1140         demux->taglist = gst_tag_list_new ();
1141       gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
1142           GST_TAG_VIDEO_CODEC, codec_name, NULL);
1143       g_free (codec_name);
1144     }
1145
1146     GST_DEBUG_OBJECT (demux->video_pad, "successfully negotiated caps %"
1147         GST_PTR_FORMAT, caps);
1148   } else {
1149     GST_WARNING_OBJECT (demux->video_pad, "failed negotiating caps %"
1150         GST_PTR_FORMAT, caps);
1151   }
1152
1153   gst_caps_unref (caps);
1154
1155 beach:
1156   return ret;
1157 }
1158
1159 static GstFlowReturn
1160 gst_flv_demux_parse_tag_video (GstFlvDemux * demux, GstBuffer * buffer)
1161 {
1162   GstFlowReturn ret = GST_FLOW_OK;
1163   guint32 pts = 0, codec_data = 1, pts_ext = 0;
1164   gboolean keyframe = FALSE;
1165   guint8 flags = 0, codec_tag = 0;
1166   guint8 *data;
1167   GstBuffer *outbuf;
1168   gsize size;
1169
1170   g_return_val_if_fail (gst_buffer_get_size (buffer) == demux->tag_size,
1171       GST_FLOW_ERROR);
1172
1173   GST_LOG_OBJECT (demux, "parsing a video tag");
1174
1175   if (demux->no_more_pads && !demux->video_pad) {
1176     GST_WARNING_OBJECT (demux,
1177         "Signaled no-more-pads already but had no audio pad -- ignoring");
1178     return GST_FLOW_OK;
1179   }
1180
1181   if (gst_buffer_get_size (buffer) < 12) {
1182     GST_ERROR_OBJECT (demux, "Too small tag size");
1183     return GST_FLOW_ERROR;
1184   }
1185
1186   data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
1187
1188   /* Grab information about video tag */
1189   pts = GST_READ_UINT24_BE (data);
1190   /* read the pts extension to 32 bits integer */
1191   pts_ext = GST_READ_UINT8 (data + 3);
1192   /* Combine them */
1193   pts |= pts_ext << 24;
1194
1195   GST_LOG_OBJECT (demux, "pts bytes %02X %02X %02X %02X (%d)", data[0], data[1],
1196       data[2], data[3], pts);
1197
1198   /* Skip the stream id and go directly to the flags */
1199   flags = GST_READ_UINT8 (data + 7);
1200
1201   /* Keyframe */
1202   if ((flags >> 4) == 1) {
1203     keyframe = TRUE;
1204   }
1205   /* Codec tag */
1206   codec_tag = flags & 0x0F;
1207   if (codec_tag == 4 || codec_tag == 5) {
1208     codec_data = 2;
1209   } else if (codec_tag == 7) {
1210     gint32 cts;
1211
1212     codec_data = 5;
1213
1214     cts = GST_READ_UINT24_BE (data + 9);
1215     cts = (cts + 0xff800000) ^ 0xff800000;
1216
1217     GST_LOG_OBJECT (demux, "got cts %d", cts);
1218
1219     pts = pts + cts;
1220   }
1221
1222   GST_LOG_OBJECT (demux, "video tag with codec tag %u, keyframe (%d) "
1223       "(flags %02X)", codec_tag, keyframe, flags);
1224
1225   /* If we don't have our video pad created, then create it. */
1226   if (G_UNLIKELY (!demux->video_pad)) {
1227     demux->video_pad =
1228         gst_pad_new_from_template (gst_element_class_get_pad_template
1229         (GST_ELEMENT_GET_CLASS (demux), "video"), "video");
1230     if (G_UNLIKELY (!demux->video_pad)) {
1231       GST_WARNING_OBJECT (demux, "failed creating video pad");
1232       ret = GST_FLOW_ERROR;
1233       goto beach;
1234     }
1235
1236     if (!gst_flv_demux_video_negotiate (demux, codec_tag)) {
1237       gst_object_unref (demux->video_pad);
1238       demux->video_pad = NULL;
1239       ret = GST_FLOW_ERROR;
1240       goto beach;
1241     }
1242
1243     /* When we ve set pixel-aspect-ratio we use that boolean to detect a
1244      * metadata tag that would come later and trigger a caps change */
1245     demux->got_par = FALSE;
1246
1247 #ifndef GST_DISABLE_GST_DEBUG
1248     {
1249       GstCaps *caps;
1250
1251       caps = gst_pad_get_current_caps (demux->video_pad);
1252       GST_DEBUG_OBJECT (demux, "created video pad with caps %" GST_PTR_FORMAT,
1253           caps);
1254       if (caps)
1255         gst_caps_unref (caps);
1256     }
1257 #endif
1258
1259     /* Set functions on the pad */
1260     gst_pad_set_query_type_function (demux->video_pad,
1261         GST_DEBUG_FUNCPTR (gst_flv_demux_query_types));
1262     gst_pad_set_query_function (demux->video_pad,
1263         GST_DEBUG_FUNCPTR (gst_flv_demux_query));
1264     gst_pad_set_event_function (demux->video_pad,
1265         GST_DEBUG_FUNCPTR (gst_flv_demux_src_event));
1266
1267     gst_pad_use_fixed_caps (demux->video_pad);
1268
1269     /* Make it active */
1270     gst_pad_set_active (demux->video_pad, TRUE);
1271
1272     /* We need to set caps before adding */
1273     gst_element_add_pad (GST_ELEMENT (demux),
1274         gst_object_ref (demux->video_pad));
1275
1276     /* We only emit no more pads when we have audio and video. Indeed we can
1277      * not trust the FLV header to tell us if there will be only audio or
1278      * only video and we would just break discovery of some files */
1279     if (demux->audio_pad && demux->video_pad) {
1280       GST_DEBUG_OBJECT (demux, "emitting no more pads");
1281       gst_element_no_more_pads (GST_ELEMENT (demux));
1282       demux->no_more_pads = TRUE;
1283       demux->push_tags = TRUE;
1284     }
1285   }
1286
1287   /* Check if caps have changed */
1288   if (G_UNLIKELY (codec_tag != demux->video_codec_tag || demux->got_par)) {
1289
1290     GST_DEBUG_OBJECT (demux, "video settings have changed, changing caps");
1291
1292     if (!gst_flv_demux_video_negotiate (demux, codec_tag)) {
1293       ret = GST_FLOW_ERROR;
1294       goto beach;
1295     }
1296
1297     /* When we ve set pixel-aspect-ratio we use that boolean to detect a
1298      * metadata tag that would come later and trigger a caps change */
1299     demux->got_par = FALSE;
1300   }
1301
1302   /* Push taglist if present */
1303   if (G_UNLIKELY (demux->push_tags))
1304     gst_flv_demux_push_tags (demux);
1305
1306   /* Check if we have anything to push */
1307   if (demux->tag_data_size <= codec_data) {
1308     GST_LOG_OBJECT (demux, "Nothing left in this tag, returning");
1309     goto beach;
1310   }
1311
1312   /* Create buffer from pad */
1313   outbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_MEMORY,
1314       7 + codec_data, demux->tag_data_size - codec_data);
1315
1316   if (demux->video_codec_tag == 7) {
1317     guint8 avc_packet_type = GST_READ_UINT8 (data + 8);
1318
1319     switch (avc_packet_type) {
1320       case 0:
1321       {
1322         /* AVCDecoderConfigurationRecord data */
1323         GST_LOG_OBJECT (demux, "got an H.264 codec data packet");
1324         if (demux->video_codec_data) {
1325           gst_buffer_unref (demux->video_codec_data);
1326         }
1327         demux->video_codec_data = outbuf;
1328         /* Use that buffer data in the caps */
1329         gst_flv_demux_video_negotiate (demux, codec_tag);
1330         goto beach;
1331         break;
1332       }
1333       case 1:
1334         /* H.264 NALU packet */
1335         GST_LOG_OBJECT (demux, "got a H.264 NALU video packet");
1336         break;
1337       default:
1338         GST_WARNING_OBJECT (demux, "invalid video packet type %u",
1339             avc_packet_type);
1340     }
1341   }
1342
1343   /* Fill buffer with data */
1344   GST_BUFFER_TIMESTAMP (outbuf) = pts * GST_MSECOND;
1345   GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
1346   GST_BUFFER_OFFSET (outbuf) = demux->video_offset++;
1347   GST_BUFFER_OFFSET_END (outbuf) = demux->video_offset;
1348
1349   if (demux->duration == GST_CLOCK_TIME_NONE ||
1350       demux->duration < GST_BUFFER_TIMESTAMP (outbuf))
1351     demux->duration = GST_BUFFER_TIMESTAMP (outbuf);
1352
1353   if (!keyframe)
1354     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1355
1356   if (!demux->indexed && demux->index) {
1357     gst_flv_demux_parse_and_add_index_entry (demux,
1358         GST_BUFFER_TIMESTAMP (outbuf), demux->cur_tag_offset, keyframe);
1359   }
1360
1361   if (G_UNLIKELY (demux->video_need_discont)) {
1362     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1363     demux->video_need_discont = FALSE;
1364   }
1365
1366   demux->segment.position = GST_BUFFER_TIMESTAMP (outbuf);
1367
1368   /* Do we need a newsegment event ? */
1369   if (G_UNLIKELY (demux->video_need_segment)) {
1370     /* FIXME need one segment sent for all stream to maintain a/v sync */
1371     if (!demux->new_seg_event) {
1372       GST_DEBUG_OBJECT (demux, "pushing newsegment from %"
1373           GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
1374           GST_TIME_ARGS (demux->segment.position),
1375           GST_TIME_ARGS (demux->segment.stop));
1376       demux->segment.start = demux->segment.time = demux->segment.position;
1377       demux->new_seg_event = gst_event_new_segment (&demux->segment);
1378     } else {
1379       GST_DEBUG_OBJECT (demux, "pushing pre-generated newsegment event");
1380     }
1381
1382     gst_pad_push_event (demux->video_pad, gst_event_ref (demux->new_seg_event));
1383
1384     demux->video_need_segment = FALSE;
1385   }
1386
1387   GST_LOG_OBJECT (demux, "pushing %d bytes buffer at pts %" GST_TIME_FORMAT
1388       " with duration %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
1389       ", keyframe (%d)", gst_buffer_get_size (outbuf),
1390       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1391       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf),
1392       keyframe);
1393
1394   if (!GST_CLOCK_TIME_IS_VALID (demux->video_start)) {
1395     demux->video_start = GST_BUFFER_TIMESTAMP (outbuf);
1396   }
1397   if (!GST_CLOCK_TIME_IS_VALID (demux->audio_first_ts)) {
1398     demux->video_first_ts = GST_BUFFER_TIMESTAMP (outbuf);
1399   }
1400
1401   if (G_UNLIKELY (!demux->no_more_pads
1402           && (GST_CLOCK_DIFF (demux->video_start,
1403                   GST_BUFFER_TIMESTAMP (outbuf)) > 6 * GST_SECOND))) {
1404     GST_DEBUG_OBJECT (demux,
1405         "Signalling no-more-pads because no audio stream was found"
1406         " after 6 seconds of video");
1407     gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
1408     demux->no_more_pads = TRUE;
1409     demux->push_tags = TRUE;
1410   }
1411
1412   /* Push downstream */
1413   ret = gst_pad_push (demux->video_pad, outbuf);
1414
1415   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1416     if (demux->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
1417         demux->segment.position > demux->segment.stop) {
1418       /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
1419        * we are at the end of the segment, so we just need to jump
1420        * back to the previous section. */
1421       GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
1422       demux->video_done = TRUE;
1423       ret = GST_FLOW_OK;
1424     } else {
1425       GST_WARNING_OBJECT (demux, "failed pushing a %" G_GUINT64_FORMAT
1426           " bytes video buffer: %s", demux->tag_data_size,
1427           gst_flow_get_name (ret));
1428       if (ret == GST_FLOW_NOT_LINKED) {
1429         demux->video_linked = FALSE;
1430       }
1431       goto beach;
1432     }
1433   }
1434
1435   demux->video_linked = TRUE;
1436
1437 beach:
1438   gst_buffer_unmap (buffer, data, -1);
1439   return ret;
1440 }
1441
1442 static GstClockTime
1443 gst_flv_demux_parse_tag_timestamp (GstFlvDemux * demux, gboolean index,
1444     GstBuffer * buffer, size_t * tag_size)
1445 {
1446   guint32 pts = 0, pts_ext = 0;
1447   guint32 tag_data_size;
1448   guint8 type;
1449   gboolean keyframe = TRUE;
1450   GstClockTime ret = GST_CLOCK_TIME_NONE;
1451   guint8 *data, *bdata;
1452   gsize size;
1453
1454   g_return_val_if_fail (gst_buffer_get_size (buffer) >= 12,
1455       GST_CLOCK_TIME_NONE);
1456
1457   data = bdata = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
1458
1459   type = data[0];
1460
1461   if (type != 9 && type != 8 && type != 18) {
1462     GST_WARNING_OBJECT (demux, "Unsupported tag type %u", data[0]);
1463     goto exit;
1464   }
1465
1466   if (type == 9)
1467     demux->has_video = TRUE;
1468   else if (type == 8)
1469     demux->has_audio = TRUE;
1470
1471   tag_data_size = GST_READ_UINT24_BE (data + 1);
1472
1473   if (size >= tag_data_size + 11 + 4) {
1474     if (GST_READ_UINT32_BE (data + tag_data_size + 11) != tag_data_size + 11) {
1475       GST_WARNING_OBJECT (demux, "Invalid tag size");
1476       goto exit;
1477     }
1478   }
1479
1480   if (tag_size)
1481     *tag_size = tag_data_size + 11 + 4;
1482
1483   data += 4;
1484
1485   GST_LOG_OBJECT (demux, "pts bytes %02X %02X %02X %02X", data[0], data[1],
1486       data[2], data[3]);
1487
1488   /* Grab timestamp of tag tag */
1489   pts = GST_READ_UINT24_BE (data);
1490   /* read the pts extension to 32 bits integer */
1491   pts_ext = GST_READ_UINT8 (data + 3);
1492   /* Combine them */
1493   pts |= pts_ext << 24;
1494
1495   if (type == 9) {
1496     data += 7;
1497
1498     keyframe = ((data[0] >> 4) == 1);
1499   }
1500
1501   ret = pts * GST_MSECOND;
1502   GST_LOG_OBJECT (demux, "pts: %" GST_TIME_FORMAT, GST_TIME_ARGS (ret));
1503
1504   if (index && demux->index && !demux->indexed && (type == 9 || (type == 8
1505               && !demux->has_video))) {
1506     gst_flv_demux_parse_and_add_index_entry (demux, ret, demux->offset,
1507         keyframe);
1508   }
1509
1510   if (demux->duration == GST_CLOCK_TIME_NONE || demux->duration < ret)
1511     demux->duration = ret;
1512
1513 exit:
1514   gst_buffer_unmap (buffer, bdata, -1);
1515   return ret;
1516 }
1517
1518 static GstFlowReturn
1519 gst_flv_demux_parse_tag_type (GstFlvDemux * demux, GstBuffer * buffer)
1520 {
1521   GstFlowReturn ret = GST_FLOW_OK;
1522   guint8 tag_type = 0;
1523   guint8 *data;
1524
1525   g_return_val_if_fail (gst_buffer_get_size (buffer) >= 4, GST_FLOW_ERROR);
1526
1527   data = gst_buffer_map (buffer, NULL, NULL, GST_MAP_READ);
1528
1529   tag_type = data[0];
1530
1531   switch (tag_type) {
1532     case 9:
1533       demux->state = FLV_STATE_TAG_VIDEO;
1534       demux->has_video = TRUE;
1535       break;
1536     case 8:
1537       demux->state = FLV_STATE_TAG_AUDIO;
1538       demux->has_audio = TRUE;
1539       break;
1540     case 18:
1541       demux->state = FLV_STATE_TAG_SCRIPT;
1542       break;
1543     default:
1544       GST_WARNING_OBJECT (demux, "unsupported tag type %u", tag_type);
1545   }
1546
1547   /* Tag size is 1 byte of type + 3 bytes of size + 7 bytes + tag data size +
1548    * 4 bytes of previous tag size */
1549   demux->tag_data_size = GST_READ_UINT24_BE (data + 1);
1550   demux->tag_size = demux->tag_data_size + 11;
1551
1552   GST_LOG_OBJECT (demux, "tag data size is %" G_GUINT64_FORMAT,
1553       demux->tag_data_size);
1554
1555   gst_buffer_unmap (buffer, data, -1);
1556
1557   return ret;
1558 }
1559
1560 static GstFlowReturn
1561 gst_flv_demux_parse_header (GstFlvDemux * demux, GstBuffer * buffer)
1562 {
1563   GstFlowReturn ret = GST_FLOW_OK;
1564   guint8 *data;
1565
1566   g_return_val_if_fail (gst_buffer_get_size (buffer) >= 9, GST_FLOW_ERROR);
1567
1568   data = gst_buffer_map (buffer, NULL, NULL, GST_MAP_READ);
1569
1570   /* Check for the FLV tag */
1571   if (data[0] == 'F' && data[1] == 'L' && data[2] == 'V') {
1572     GST_DEBUG_OBJECT (demux, "FLV header detected");
1573   } else {
1574     if (G_UNLIKELY (demux->strict)) {
1575       GST_WARNING_OBJECT (demux, "invalid header tag detected");
1576       ret = GST_FLOW_UNEXPECTED;
1577       goto beach;
1578     }
1579   }
1580
1581   /* Now look at audio/video flags */
1582   {
1583     guint8 flags = data[4];
1584
1585     demux->has_video = demux->has_audio = FALSE;
1586
1587     if (flags & 1) {
1588       GST_DEBUG_OBJECT (demux, "there is a video stream");
1589       demux->has_video = TRUE;
1590     }
1591     if (flags & 4) {
1592       GST_DEBUG_OBJECT (demux, "there is an audio stream");
1593       demux->has_audio = TRUE;
1594     }
1595   }
1596
1597   /* do a one-time seekability check */
1598   gst_flv_demux_check_seekability (demux);
1599
1600   /* We don't care about the rest */
1601   demux->need_header = FALSE;
1602
1603 beach:
1604   gst_buffer_unmap (buffer, data, -1);
1605   return ret;
1606 }
1607
1608
1609 static void
1610 gst_flv_demux_flush (GstFlvDemux * demux, gboolean discont)
1611 {
1612   GST_DEBUG_OBJECT (demux, "flushing queued data in the FLV demuxer");
1613
1614   gst_adapter_clear (demux->adapter);
1615
1616   demux->audio_need_discont = TRUE;
1617   demux->video_need_discont = TRUE;
1618
1619   demux->flushing = FALSE;
1620
1621   /* Only in push mode and if we're not during a seek */
1622   if (!demux->random_access && demux->state != FLV_STATE_SEEK) {
1623     /* After a flush we expect a tag_type */
1624     demux->state = FLV_STATE_TAG_TYPE;
1625     /* We reset the offset and will get one from first push */
1626     demux->offset = 0;
1627   }
1628 }
1629
1630 static void
1631 gst_flv_demux_cleanup (GstFlvDemux * demux)
1632 {
1633   GST_DEBUG_OBJECT (demux, "cleaning up FLV demuxer");
1634
1635   demux->state = FLV_STATE_HEADER;
1636
1637   demux->flushing = FALSE;
1638   demux->need_header = TRUE;
1639   demux->audio_need_segment = TRUE;
1640   demux->video_need_segment = TRUE;
1641   demux->audio_need_discont = TRUE;
1642   demux->video_need_discont = TRUE;
1643
1644   /* By default we consider them as linked */
1645   demux->audio_linked = TRUE;
1646   demux->video_linked = TRUE;
1647
1648   demux->has_audio = FALSE;
1649   demux->has_video = FALSE;
1650   demux->push_tags = FALSE;
1651   demux->got_par = FALSE;
1652
1653   demux->indexed = FALSE;
1654   demux->upstream_seekable = FALSE;
1655   demux->file_size = 0;
1656
1657   demux->index_max_pos = 0;
1658   demux->index_max_time = 0;
1659
1660   demux->audio_start = demux->video_start = GST_CLOCK_TIME_NONE;
1661
1662   demux->no_more_pads = FALSE;
1663
1664   gst_segment_init (&demux->segment, GST_FORMAT_TIME);
1665
1666   demux->w = demux->h = 0;
1667   demux->framerate = 0.0;
1668   demux->par_x = demux->par_y = 1;
1669   demux->video_offset = 0;
1670   demux->audio_offset = 0;
1671   demux->offset = demux->cur_tag_offset = 0;
1672   demux->tag_size = demux->tag_data_size = 0;
1673   demux->duration = GST_CLOCK_TIME_NONE;
1674
1675   if (demux->new_seg_event) {
1676     gst_event_unref (demux->new_seg_event);
1677     demux->new_seg_event = NULL;
1678   }
1679
1680   gst_adapter_clear (demux->adapter);
1681
1682   if (demux->audio_codec_data) {
1683     gst_buffer_unref (demux->audio_codec_data);
1684     demux->audio_codec_data = NULL;
1685   }
1686
1687   if (demux->video_codec_data) {
1688     gst_buffer_unref (demux->video_codec_data);
1689     demux->video_codec_data = NULL;
1690   }
1691
1692   if (demux->audio_pad) {
1693     gst_element_remove_pad (GST_ELEMENT (demux), demux->audio_pad);
1694     gst_object_unref (demux->audio_pad);
1695     demux->audio_pad = NULL;
1696   }
1697
1698   if (demux->video_pad) {
1699     gst_element_remove_pad (GST_ELEMENT (demux), demux->video_pad);
1700     gst_object_unref (demux->video_pad);
1701     demux->video_pad = NULL;
1702   }
1703
1704   if (demux->times) {
1705     g_array_free (demux->times, TRUE);
1706     demux->times = NULL;
1707   }
1708
1709   if (demux->filepositions) {
1710     g_array_free (demux->filepositions, TRUE);
1711     demux->filepositions = NULL;
1712   }
1713 }
1714
1715 /*
1716  * Create and push a flushing seek event upstream
1717  */
1718 static gboolean
1719 flv_demux_seek_to_offset (GstFlvDemux * demux, guint64 offset)
1720 {
1721   GstEvent *event;
1722   gboolean res = 0;
1723
1724   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
1725
1726   event =
1727       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1728       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1729       GST_SEEK_TYPE_NONE, -1);
1730
1731   res = gst_pad_push_event (demux->sinkpad, event);
1732
1733   if (res)
1734     demux->offset = offset;
1735   return res;
1736 }
1737
1738 static GstFlowReturn
1739 gst_flv_demux_chain (GstPad * pad, GstBuffer * buffer)
1740 {
1741   GstFlowReturn ret = GST_FLOW_OK;
1742   GstFlvDemux *demux = NULL;
1743
1744   demux = GST_FLV_DEMUX (gst_pad_get_parent (pad));
1745
1746   GST_LOG_OBJECT (demux, "received buffer of %d bytes at offset %"
1747       G_GUINT64_FORMAT, gst_buffer_get_size (buffer),
1748       GST_BUFFER_OFFSET (buffer));
1749
1750   if (G_UNLIKELY (GST_BUFFER_OFFSET (buffer) == 0)) {
1751     GST_DEBUG_OBJECT (demux, "beginning of file, expect header");
1752     demux->state = FLV_STATE_HEADER;
1753     demux->offset = 0;
1754   }
1755
1756   if (G_UNLIKELY (demux->offset == 0 && GST_BUFFER_OFFSET (buffer) != 0)) {
1757     GST_DEBUG_OBJECT (demux, "offset was zero, synchronizing with buffer's");
1758     demux->offset = GST_BUFFER_OFFSET (buffer);
1759   }
1760
1761   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) {
1762     GST_DEBUG_OBJECT (demux, "Discontinuity");
1763     gst_adapter_clear (demux->adapter);
1764   }
1765
1766   gst_adapter_push (demux->adapter, buffer);
1767
1768   if (demux->seeking) {
1769     demux->state = FLV_STATE_SEEK;
1770     GST_OBJECT_LOCK (demux);
1771     demux->seeking = FALSE;
1772     GST_OBJECT_UNLOCK (demux);
1773   }
1774
1775 parse:
1776   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1777     if (ret == GST_FLOW_NOT_LINKED && (demux->audio_linked
1778             || demux->video_linked)) {
1779       ret = GST_FLOW_OK;
1780     } else {
1781       GST_DEBUG_OBJECT (demux, "got flow return %s", gst_flow_get_name (ret));
1782       goto beach;
1783     }
1784   }
1785
1786   if (G_UNLIKELY (demux->flushing)) {
1787     GST_DEBUG_OBJECT (demux, "we are now flushing, exiting parser loop");
1788     ret = GST_FLOW_WRONG_STATE;
1789     goto beach;
1790   }
1791
1792   switch (demux->state) {
1793     case FLV_STATE_HEADER:
1794     {
1795       if (gst_adapter_available (demux->adapter) >= FLV_HEADER_SIZE) {
1796         GstBuffer *buffer;
1797
1798         buffer = gst_adapter_take_buffer (demux->adapter, FLV_HEADER_SIZE);
1799
1800         ret = gst_flv_demux_parse_header (demux, buffer);
1801
1802         gst_buffer_unref (buffer);
1803         demux->offset += FLV_HEADER_SIZE;
1804
1805         demux->state = FLV_STATE_TAG_TYPE;
1806         goto parse;
1807       } else {
1808         goto beach;
1809       }
1810     }
1811     case FLV_STATE_TAG_TYPE:
1812     {
1813       if (gst_adapter_available (demux->adapter) >= FLV_TAG_TYPE_SIZE) {
1814         GstBuffer *buffer;
1815
1816         /* Remember the tag offset in bytes */
1817         demux->cur_tag_offset = demux->offset;
1818
1819         buffer = gst_adapter_take_buffer (demux->adapter, FLV_TAG_TYPE_SIZE);
1820
1821         ret = gst_flv_demux_parse_tag_type (demux, buffer);
1822
1823         gst_buffer_unref (buffer);
1824         demux->offset += FLV_TAG_TYPE_SIZE;
1825
1826         /* last tag is not an index => no index/don't know where the index is
1827          * seek back to the beginning */
1828         if (demux->seek_event && demux->state != FLV_STATE_TAG_SCRIPT)
1829           goto no_index;
1830
1831         goto parse;
1832       } else {
1833         goto beach;
1834       }
1835     }
1836     case FLV_STATE_TAG_VIDEO:
1837     {
1838       if (gst_adapter_available (demux->adapter) >= demux->tag_size) {
1839         GstBuffer *buffer;
1840
1841         buffer = gst_adapter_take_buffer (demux->adapter, demux->tag_size);
1842
1843         ret = gst_flv_demux_parse_tag_video (demux, buffer);
1844
1845         gst_buffer_unref (buffer);
1846         demux->offset += demux->tag_size;
1847
1848         demux->state = FLV_STATE_TAG_TYPE;
1849         goto parse;
1850       } else {
1851         goto beach;
1852       }
1853     }
1854     case FLV_STATE_TAG_AUDIO:
1855     {
1856       if (gst_adapter_available (demux->adapter) >= demux->tag_size) {
1857         GstBuffer *buffer;
1858
1859         buffer = gst_adapter_take_buffer (demux->adapter, demux->tag_size);
1860
1861         ret = gst_flv_demux_parse_tag_audio (demux, buffer);
1862
1863         gst_buffer_unref (buffer);
1864         demux->offset += demux->tag_size;
1865
1866         demux->state = FLV_STATE_TAG_TYPE;
1867         goto parse;
1868       } else {
1869         goto beach;
1870       }
1871     }
1872     case FLV_STATE_TAG_SCRIPT:
1873     {
1874       if (gst_adapter_available (demux->adapter) >= demux->tag_size) {
1875         GstBuffer *buffer;
1876
1877         buffer = gst_adapter_take_buffer (demux->adapter, demux->tag_size);
1878
1879         ret = gst_flv_demux_parse_tag_script (demux, buffer);
1880
1881         gst_buffer_unref (buffer);
1882         demux->offset += demux->tag_size;
1883
1884         demux->state = FLV_STATE_TAG_TYPE;
1885
1886         /* if there's a seek event we're here for the index so if we don't have it
1887          * we seek back to the beginning */
1888         if (demux->seek_event) {
1889           if (demux->indexed)
1890             demux->state = FLV_STATE_SEEK;
1891           else
1892             goto no_index;
1893         }
1894
1895         goto parse;
1896       } else {
1897         goto beach;
1898       }
1899     }
1900     case FLV_STATE_SEEK:
1901     {
1902       GstEvent *event;
1903
1904       ret = GST_FLOW_OK;
1905
1906       if (!demux->indexed) {
1907         if (demux->offset == demux->file_size - sizeof (guint32)) {
1908           guint64 seek_offset;
1909           guint8 *data;
1910
1911           data = gst_adapter_take (demux->adapter, 4);
1912           if (!data)
1913             goto no_index;
1914
1915           seek_offset = demux->file_size - sizeof (guint32) -
1916               GST_READ_UINT32_BE (data);
1917           g_free (data);
1918
1919           GST_INFO_OBJECT (demux,
1920               "Seeking to beginning of last tag at %" G_GUINT64_FORMAT,
1921               seek_offset);
1922           demux->state = FLV_STATE_TAG_TYPE;
1923           flv_demux_seek_to_offset (demux, seek_offset);
1924           goto beach;
1925         } else
1926           goto no_index;
1927       }
1928
1929       GST_OBJECT_LOCK (demux);
1930       event = demux->seek_event;
1931       demux->seek_event = NULL;
1932       GST_OBJECT_UNLOCK (demux);
1933
1934       /* calculate and perform seek */
1935       if (!flv_demux_handle_seek_push (demux, event))
1936         goto seek_failed;
1937
1938       gst_event_unref (event);
1939       demux->state = FLV_STATE_TAG_TYPE;
1940       goto beach;
1941     }
1942     default:
1943       GST_DEBUG_OBJECT (demux, "unexpected demuxer state");
1944   }
1945
1946 beach:
1947   if (G_UNLIKELY (ret == GST_FLOW_NOT_LINKED)) {
1948     /* If either audio or video is linked we return GST_FLOW_OK */
1949     if (demux->audio_linked || demux->video_linked) {
1950       ret = GST_FLOW_OK;
1951     }
1952   }
1953
1954   gst_object_unref (demux);
1955
1956   return ret;
1957
1958 /* ERRORS */
1959 no_index:
1960   {
1961     GST_OBJECT_LOCK (demux);
1962     demux->seeking = FALSE;
1963     gst_event_unref (demux->seek_event);
1964     demux->seek_event = NULL;
1965     GST_OBJECT_UNLOCK (demux);
1966     GST_WARNING_OBJECT (demux,
1967         "failed to find an index, seeking back to beginning");
1968     flv_demux_seek_to_offset (demux, 0);
1969     return GST_FLOW_OK;
1970   }
1971 seek_failed:
1972   {
1973     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("seek failed"));
1974     return GST_FLOW_ERROR;
1975   }
1976
1977 }
1978
1979 static GstFlowReturn
1980 gst_flv_demux_pull_range (GstFlvDemux * demux, GstPad * pad, guint64 offset,
1981     guint size, GstBuffer ** buffer)
1982 {
1983   GstFlowReturn ret;
1984
1985   ret = gst_pad_pull_range (pad, offset, size, buffer);
1986   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1987     GST_WARNING_OBJECT (demux,
1988         "failed when pulling %d bytes from offset %" G_GUINT64_FORMAT ": %s",
1989         size, offset, gst_flow_get_name (ret));
1990     *buffer = NULL;
1991     return ret;
1992   }
1993
1994   if (G_UNLIKELY (*buffer && gst_buffer_get_size (*buffer) != size)) {
1995     GST_WARNING_OBJECT (demux,
1996         "partial pull got %d when expecting %d from offset %" G_GUINT64_FORMAT,
1997         gst_buffer_get_size (*buffer), size, offset);
1998     gst_buffer_unref (*buffer);
1999     ret = GST_FLOW_UNEXPECTED;
2000     *buffer = NULL;
2001     return ret;
2002   }
2003
2004   return ret;
2005 }
2006
2007 static GstFlowReturn
2008 gst_flv_demux_pull_tag (GstPad * pad, GstFlvDemux * demux)
2009 {
2010   GstBuffer *buffer = NULL;
2011   GstFlowReturn ret = GST_FLOW_OK;
2012
2013   /* Store tag offset */
2014   demux->cur_tag_offset = demux->offset;
2015
2016   /* Get the first 4 bytes to identify tag type and size */
2017   if (G_UNLIKELY ((ret = gst_flv_demux_pull_range (demux, pad, demux->offset,
2018                   FLV_TAG_TYPE_SIZE, &buffer)) != GST_FLOW_OK))
2019     goto beach;
2020
2021   /* Identify tag type */
2022   ret = gst_flv_demux_parse_tag_type (demux, buffer);
2023
2024   gst_buffer_unref (buffer);
2025
2026   if (G_UNLIKELY (ret != GST_FLOW_OK))
2027     goto beach;
2028
2029   /* Jump over tag type + size */
2030   demux->offset += FLV_TAG_TYPE_SIZE;
2031
2032   /* Pull the whole tag */
2033   if (G_UNLIKELY ((ret = gst_flv_demux_pull_range (demux, pad, demux->offset,
2034                   demux->tag_size, &buffer)) != GST_FLOW_OK))
2035     goto beach;
2036
2037   switch (demux->state) {
2038     case FLV_STATE_TAG_VIDEO:
2039       ret = gst_flv_demux_parse_tag_video (demux, buffer);
2040       break;
2041     case FLV_STATE_TAG_AUDIO:
2042       ret = gst_flv_demux_parse_tag_audio (demux, buffer);
2043       break;
2044     case FLV_STATE_TAG_SCRIPT:
2045       ret = gst_flv_demux_parse_tag_script (demux, buffer);
2046       break;
2047     default:
2048       GST_WARNING_OBJECT (demux, "unexpected state %d", demux->state);
2049   }
2050
2051   gst_buffer_unref (buffer);
2052
2053   /* Jump over that part we've just parsed */
2054   demux->offset += demux->tag_size;
2055
2056   /* Make sure we reinitialize the tag size */
2057   demux->tag_size = 0;
2058
2059   /* Ready for the next tag */
2060   demux->state = FLV_STATE_TAG_TYPE;
2061
2062   if (G_UNLIKELY (ret == GST_FLOW_NOT_LINKED)) {
2063     /* If either audio or video is linked we return GST_FLOW_OK */
2064     if (demux->audio_linked || demux->video_linked) {
2065       ret = GST_FLOW_OK;
2066     } else {
2067       GST_WARNING_OBJECT (demux, "parsing this tag returned not-linked and "
2068           "neither video nor audio are linked");
2069     }
2070   }
2071
2072 beach:
2073   return ret;
2074 }
2075
2076 static GstFlowReturn
2077 gst_flv_demux_pull_header (GstPad * pad, GstFlvDemux * demux)
2078 {
2079   GstBuffer *buffer = NULL;
2080   GstFlowReturn ret = GST_FLOW_OK;
2081
2082   /* Get the first 9 bytes */
2083   if (G_UNLIKELY ((ret = gst_flv_demux_pull_range (demux, pad, demux->offset,
2084                   FLV_HEADER_SIZE, &buffer)) != GST_FLOW_OK))
2085     goto beach;
2086
2087   ret = gst_flv_demux_parse_header (demux, buffer);
2088
2089   gst_buffer_unref (buffer);
2090
2091   /* Jump over the header now */
2092   demux->offset += FLV_HEADER_SIZE;
2093   demux->state = FLV_STATE_TAG_TYPE;
2094
2095 beach:
2096   return ret;
2097 }
2098
2099 static void
2100 gst_flv_demux_move_to_offset (GstFlvDemux * demux, gint64 offset,
2101     gboolean reset)
2102 {
2103   demux->offset = offset;
2104
2105   /* Tell all the stream we moved to a different position (discont) */
2106   demux->audio_need_discont = TRUE;
2107   demux->video_need_discont = TRUE;
2108
2109   /* next section setup */
2110   demux->from_offset = -1;
2111   demux->audio_done = demux->video_done = FALSE;
2112   demux->audio_first_ts = demux->video_first_ts = GST_CLOCK_TIME_NONE;
2113
2114   if (reset) {
2115     demux->from_offset = -1;
2116     demux->to_offset = G_MAXINT64;
2117   }
2118
2119   /* If we seeked at the beginning of the file parse the header again */
2120   if (G_UNLIKELY (!demux->offset)) {
2121     demux->state = FLV_STATE_HEADER;
2122   } else {                      /* or parse a tag */
2123     demux->state = FLV_STATE_TAG_TYPE;
2124   }
2125 }
2126
2127 static GstFlowReturn
2128 gst_flv_demux_seek_to_prev_keyframe (GstFlvDemux * demux)
2129 {
2130   GstFlowReturn ret = GST_FLOW_UNEXPECTED;
2131   GstIndexEntry *entry = NULL;
2132
2133   GST_DEBUG_OBJECT (demux,
2134       "terminated section started at offset %" G_GINT64_FORMAT,
2135       demux->from_offset);
2136
2137   /* we are done if we got all audio and video */
2138   if ((!GST_CLOCK_TIME_IS_VALID (demux->audio_first_ts) ||
2139           demux->audio_first_ts < demux->segment.start) &&
2140       (!GST_CLOCK_TIME_IS_VALID (demux->video_first_ts) ||
2141           demux->video_first_ts < demux->segment.start))
2142     goto done;
2143
2144   if (demux->from_offset <= 0)
2145     goto done;
2146
2147   GST_DEBUG_OBJECT (demux, "locating previous position");
2148
2149   /* locate index entry before previous start position */
2150   if (demux->index)
2151     entry = gst_index_get_assoc_entry (demux->index, demux->index_id,
2152         GST_INDEX_LOOKUP_BEFORE, GST_ASSOCIATION_FLAG_KEY_UNIT,
2153         GST_FORMAT_BYTES, demux->from_offset - 1);
2154
2155   if (entry) {
2156     gint64 bytes, time;
2157
2158     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
2159     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
2160
2161     GST_DEBUG_OBJECT (demux, "found index entry for %" G_GINT64_FORMAT
2162         " at %" GST_TIME_FORMAT ", seeking to %" G_GINT64_FORMAT,
2163         demux->offset - 1, GST_TIME_ARGS (time), bytes);
2164
2165     /* setup for next section */
2166     demux->to_offset = demux->from_offset;
2167     gst_flv_demux_move_to_offset (demux, bytes, FALSE);
2168     ret = GST_FLOW_OK;
2169   }
2170
2171 done:
2172   return ret;
2173 }
2174
2175 static gboolean
2176 gst_flv_demux_push_src_event (GstFlvDemux * demux, GstEvent * event)
2177 {
2178   gboolean ret = TRUE;
2179
2180   if (demux->audio_pad)
2181     ret |= gst_pad_push_event (demux->audio_pad, gst_event_ref (event));
2182
2183   if (demux->video_pad)
2184     ret |= gst_pad_push_event (demux->video_pad, gst_event_ref (event));
2185
2186   gst_event_unref (event);
2187
2188   return ret;
2189 }
2190
2191 static GstFlowReturn
2192 gst_flv_demux_create_index (GstFlvDemux * demux, gint64 pos, GstClockTime ts)
2193 {
2194   gint64 size;
2195   size_t tag_size;
2196   guint64 old_offset;
2197   GstBuffer *buffer;
2198   GstClockTime tag_time;
2199   GstFlowReturn ret = GST_FLOW_OK;
2200
2201   if (!gst_pad_query_peer_duration (demux->sinkpad, GST_FORMAT_BYTES, &size))
2202     return GST_FLOW_OK;
2203
2204   GST_DEBUG_OBJECT (demux, "building index at %" G_GINT64_FORMAT
2205       " looking for time %" GST_TIME_FORMAT, pos, GST_TIME_ARGS (ts));
2206
2207   old_offset = demux->offset;
2208   demux->offset = pos;
2209
2210   while ((ret = gst_flv_demux_pull_range (demux, demux->sinkpad, demux->offset,
2211               12, &buffer)) == GST_FLOW_OK) {
2212     tag_time =
2213         gst_flv_demux_parse_tag_timestamp (demux, TRUE, buffer, &tag_size);
2214
2215     gst_buffer_unref (buffer);
2216
2217     if (G_UNLIKELY (tag_time == GST_CLOCK_TIME_NONE || tag_time > ts))
2218       goto exit;
2219
2220     demux->offset += tag_size;
2221   }
2222
2223   if (ret == GST_FLOW_UNEXPECTED) {
2224     /* file ran out, so mark we have complete index */
2225     demux->indexed = TRUE;
2226     ret = GST_FLOW_OK;
2227   }
2228
2229 exit:
2230   demux->offset = old_offset;
2231
2232   return ret;
2233 }
2234
2235 static gint64
2236 gst_flv_demux_get_metadata (GstFlvDemux * demux)
2237 {
2238   gint64 ret = 0, offset;
2239   size_t tag_size, size;
2240   GstBuffer *buffer = NULL;
2241   guint8 *data;
2242
2243   if (!gst_pad_query_peer_duration (demux->sinkpad, GST_FORMAT_BYTES, &offset))
2244     goto exit;
2245
2246   ret = offset;
2247   GST_DEBUG_OBJECT (demux, "upstream size: %" G_GINT64_FORMAT, offset);
2248   if (G_UNLIKELY (offset < 4))
2249     goto exit;
2250
2251   offset -= 4;
2252   if (GST_FLOW_OK != gst_flv_demux_pull_range (demux, demux->sinkpad, offset,
2253           4, &buffer))
2254     goto exit;
2255
2256   data = gst_buffer_map (buffer, NULL, NULL, GST_MAP_READ);
2257   tag_size = GST_READ_UINT32_BE (data);
2258   gst_buffer_unmap (buffer, data, -1);
2259   GST_DEBUG_OBJECT (demux, "last tag size: %" G_GSIZE_FORMAT, tag_size);
2260   gst_buffer_unref (buffer);
2261   buffer = NULL;
2262
2263   offset -= tag_size;
2264   if (GST_FLOW_OK != gst_flv_demux_pull_range (demux, demux->sinkpad, offset,
2265           12, &buffer))
2266     goto exit;
2267
2268   /* a consistency check */
2269   data = gst_buffer_map (buffer, NULL, NULL, GST_MAP_READ);
2270   size = GST_READ_UINT24_BE (data + 1);
2271   if (size != tag_size - 11) {
2272     gst_buffer_unmap (buffer, data, -1);
2273     GST_DEBUG_OBJECT (demux,
2274         "tag size %" G_GSIZE_FORMAT ", expected %" G_GSIZE_FORMAT
2275         ", corrupt or truncated file", size, tag_size - 11);
2276     goto exit;
2277   }
2278
2279   /* try to update duration with timestamp in any case */
2280   gst_flv_demux_parse_tag_timestamp (demux, FALSE, buffer, &size);
2281
2282   /* maybe get some more metadata */
2283   if (data[0] == 18) {
2284     gst_buffer_unmap (buffer, data, -1);
2285     gst_buffer_unref (buffer);
2286     buffer = NULL;
2287     GST_DEBUG_OBJECT (demux, "script tag, pulling it to parse");
2288     offset += 4;
2289     if (GST_FLOW_OK == gst_flv_demux_pull_range (demux, demux->sinkpad, offset,
2290             tag_size, &buffer))
2291       gst_flv_demux_parse_tag_script (demux, buffer);
2292   } else {
2293     gst_buffer_unmap (buffer, data, -1);
2294   }
2295
2296 exit:
2297   if (buffer)
2298     gst_buffer_unref (buffer);
2299
2300   return ret;
2301 }
2302
2303 static void
2304 gst_flv_demux_loop (GstPad * pad)
2305 {
2306   GstFlvDemux *demux = NULL;
2307   GstFlowReturn ret = GST_FLOW_OK;
2308
2309   demux = GST_FLV_DEMUX (gst_pad_get_parent (pad));
2310
2311   /* pull in data */
2312   switch (demux->state) {
2313     case FLV_STATE_TAG_TYPE:
2314       if (demux->from_offset == -1)
2315         demux->from_offset = demux->offset;
2316       ret = gst_flv_demux_pull_tag (pad, demux);
2317       /* if we have seen real data, we probably passed a possible metadata
2318        * header located at start.  So if we do not yet have an index,
2319        * try to pick up metadata (index, duration) at the end */
2320       if (G_UNLIKELY (!demux->file_size && !demux->indexed &&
2321               (demux->has_video || demux->has_audio)))
2322         demux->file_size = gst_flv_demux_get_metadata (demux);
2323       break;
2324     case FLV_STATE_DONE:
2325       ret = GST_FLOW_UNEXPECTED;
2326       break;
2327     case FLV_STATE_SEEK:
2328       /* seek issued with insufficient index;
2329        * scan for index in task thread from current maximum offset to
2330        * desired time and then perform seek */
2331       /* TODO maybe some buffering message or so to indicate scan progress */
2332       ret = gst_flv_demux_create_index (demux, demux->index_max_pos,
2333           demux->seek_time);
2334       if (ret != GST_FLOW_OK)
2335         goto pause;
2336       /* position and state arranged by seek,
2337        * also unrefs event */
2338       gst_flv_demux_handle_seek_pull (demux, demux->seek_event, FALSE);
2339       demux->seek_event = NULL;
2340       break;
2341     default:
2342       ret = gst_flv_demux_pull_header (pad, demux);
2343       /* index scans start after header */
2344       demux->index_max_pos = demux->offset;
2345       break;
2346   }
2347
2348   if (demux->segment.rate < 0.0) {
2349     /* check end of section */
2350     if ((gint64) demux->offset >= demux->to_offset ||
2351         demux->segment.position >= demux->segment.stop + 2 * GST_SECOND ||
2352         (demux->audio_done && demux->video_done))
2353       ret = gst_flv_demux_seek_to_prev_keyframe (demux);
2354   } else {
2355     /* check EOS condition */
2356     if ((demux->segment.stop != -1) &&
2357         (demux->segment.position >= demux->segment.stop)) {
2358       ret = GST_FLOW_UNEXPECTED;
2359     }
2360   }
2361
2362   /* pause if something went wrong or at end */
2363   if (G_UNLIKELY (ret != GST_FLOW_OK))
2364     goto pause;
2365
2366   gst_object_unref (demux);
2367
2368   return;
2369
2370 pause:
2371   {
2372     const gchar *reason = gst_flow_get_name (ret);
2373
2374     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
2375     gst_pad_pause_task (pad);
2376
2377     if (ret == GST_FLOW_UNEXPECTED) {
2378       /* handle end-of-stream/segment */
2379       /* so align our position with the end of it, if there is one
2380        * this ensures a subsequent will arrive at correct base/acc time */
2381       if (demux->segment.rate > 0.0 &&
2382           GST_CLOCK_TIME_IS_VALID (demux->segment.stop))
2383         demux->segment.position = demux->segment.stop;
2384       else if (demux->segment.rate < 0.0)
2385         demux->segment.position = demux->segment.start;
2386
2387       /* perform EOS logic */
2388       if (!demux->no_more_pads) {
2389         gst_element_no_more_pads (GST_ELEMENT_CAST (demux));
2390         demux->no_more_pads = TRUE;
2391       }
2392
2393       if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2394         gint64 stop;
2395
2396         /* for segment playback we need to post when (in stream time)
2397          * we stopped, this is either stop (when set) or the duration. */
2398         if ((stop = demux->segment.stop) == -1)
2399           stop = demux->segment.duration;
2400
2401         if (demux->segment.rate >= 0) {
2402           GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
2403           gst_element_post_message (GST_ELEMENT_CAST (demux),
2404               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
2405                   GST_FORMAT_TIME, stop));
2406         } else {                /* Reverse playback */
2407           GST_LOG_OBJECT (demux, "Sending segment done, at beginning of "
2408               "segment");
2409           gst_element_post_message (GST_ELEMENT_CAST (demux),
2410               gst_message_new_segment_done (GST_OBJECT_CAST (demux),
2411                   GST_FORMAT_TIME, demux->segment.start));
2412         }
2413       } else {
2414         /* normal playback, send EOS to all linked pads */
2415         if (!demux->no_more_pads) {
2416           gst_element_no_more_pads (GST_ELEMENT (demux));
2417           demux->no_more_pads = TRUE;
2418         }
2419
2420         GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
2421         if (!gst_flv_demux_push_src_event (demux, gst_event_new_eos ()))
2422           GST_WARNING_OBJECT (demux, "failed pushing EOS on streams");
2423       }
2424     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2425       GST_ELEMENT_ERROR (demux, STREAM, FAILED,
2426           ("Internal data stream error."),
2427           ("stream stopped, reason %s", reason));
2428       gst_flv_demux_push_src_event (demux, gst_event_new_eos ());
2429     }
2430     gst_object_unref (demux);
2431     return;
2432   }
2433 }
2434
2435 static guint64
2436 gst_flv_demux_find_offset (GstFlvDemux * demux, GstSegment * segment)
2437 {
2438   gint64 bytes = 0;
2439   gint64 time = 0;
2440   GstIndexEntry *entry;
2441
2442   g_return_val_if_fail (segment != NULL, 0);
2443
2444   time = segment->position;
2445
2446   if (demux->index) {
2447     /* Let's check if we have an index entry for that seek time */
2448     entry = gst_index_get_assoc_entry (demux->index, demux->index_id,
2449         GST_INDEX_LOOKUP_BEFORE, GST_ASSOCIATION_FLAG_KEY_UNIT,
2450         GST_FORMAT_TIME, time);
2451
2452     if (entry) {
2453       gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
2454       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
2455
2456       GST_DEBUG_OBJECT (demux, "found index entry for %" GST_TIME_FORMAT
2457           " at %" GST_TIME_FORMAT ", seeking to %" G_GINT64_FORMAT,
2458           GST_TIME_ARGS (segment->position), GST_TIME_ARGS (time), bytes);
2459
2460       /* Key frame seeking */
2461       if (segment->flags & GST_SEEK_FLAG_KEY_UNIT) {
2462         /* Adjust the segment so that the keyframe fits in */
2463         if (time < segment->start) {
2464           segment->start = segment->time = time;
2465         }
2466         segment->position = time;
2467       }
2468     } else {
2469       GST_DEBUG_OBJECT (demux, "no index entry found for %" GST_TIME_FORMAT,
2470           GST_TIME_ARGS (segment->start));
2471     }
2472   }
2473
2474   return bytes;
2475 }
2476
2477 static gboolean
2478 flv_demux_handle_seek_push (GstFlvDemux * demux, GstEvent * event)
2479 {
2480   GstFormat format;
2481   GstSeekFlags flags;
2482   GstSeekType start_type, stop_type;
2483   gint64 start, stop;
2484   gdouble rate;
2485   gboolean update, flush, ret;
2486   GstSegment seeksegment;
2487
2488   gst_event_parse_seek (event, &rate, &format, &flags,
2489       &start_type, &start, &stop_type, &stop);
2490
2491   if (format != GST_FORMAT_TIME)
2492     goto wrong_format;
2493
2494   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
2495   /* FIXME : the keyframe flag is never used ! */
2496
2497   /* Work on a copy until we are sure the seek succeeded. */
2498   memcpy (&seeksegment, &demux->segment, sizeof (GstSegment));
2499
2500   GST_DEBUG_OBJECT (demux, "segment before configure %" GST_SEGMENT_FORMAT,
2501       &demux->segment);
2502
2503   /* Apply the seek to our segment */
2504   gst_segment_do_seek (&seeksegment, rate, format, flags,
2505       start_type, start, stop_type, stop, &update);
2506
2507   GST_DEBUG_OBJECT (demux, "segment configured %" GST_SEGMENT_FORMAT,
2508       &seeksegment);
2509
2510   if (flush || seeksegment.position != demux->segment.position) {
2511     /* Do the actual seeking */
2512     guint64 offset = gst_flv_demux_find_offset (demux, &seeksegment);
2513
2514     GST_DEBUG_OBJECT (demux, "generating an upstream seek at position %"
2515         G_GUINT64_FORMAT, offset);
2516     ret = gst_pad_push_event (demux->sinkpad,
2517         gst_event_new_seek (seeksegment.rate, GST_FORMAT_BYTES,
2518             seeksegment.flags | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET,
2519             offset, GST_SEEK_TYPE_NONE, 0));
2520     if (G_UNLIKELY (!ret)) {
2521       GST_WARNING_OBJECT (demux, "upstream seek failed");
2522     }
2523
2524     /* Tell all the stream we moved to a different position (discont) */
2525     demux->audio_need_discont = TRUE;
2526     demux->video_need_discont = TRUE;
2527   } else {
2528     ret = TRUE;
2529   }
2530
2531   if (ret) {
2532     /* Ok seek succeeded, take the newly configured segment */
2533     memcpy (&demux->segment, &seeksegment, sizeof (GstSegment));
2534
2535     /* Tell all the stream a new segment is needed */
2536     demux->audio_need_segment = TRUE;
2537     demux->video_need_segment = TRUE;
2538     /* Clean any potential newsegment event kept for the streams. The first
2539      * stream needing a new segment will create a new one. */
2540     if (G_UNLIKELY (demux->new_seg_event)) {
2541       gst_event_unref (demux->new_seg_event);
2542       demux->new_seg_event = NULL;
2543     }
2544     gst_event_unref (event);
2545   } else {
2546     ret = gst_pad_push_event (demux->sinkpad, event);
2547   }
2548
2549   return ret;
2550
2551 /* ERRORS */
2552 wrong_format:
2553   {
2554     GST_WARNING_OBJECT (demux, "we only support seeking in TIME format");
2555     gst_event_unref (event);
2556     return FALSE;
2557   }
2558 }
2559
2560 static gboolean
2561 gst_flv_demux_handle_seek_push (GstFlvDemux * demux, GstEvent * event)
2562 {
2563   GstFormat format;
2564
2565   gst_event_parse_seek (event, NULL, &format, NULL, NULL, NULL, NULL, NULL);
2566
2567   if (format != GST_FORMAT_TIME) {
2568     GST_WARNING_OBJECT (demux, "we only support seeking in TIME format");
2569     gst_event_unref (event);
2570     return FALSE;
2571   }
2572
2573   /* First try upstream */
2574   if (gst_pad_push_event (demux->sinkpad, gst_event_ref (event))) {
2575     GST_DEBUG_OBJECT (demux, "Upstream successfully seeked");
2576     gst_event_unref (event);
2577     return TRUE;
2578   }
2579
2580   if (!demux->indexed) {
2581     guint64 seek_offset = 0;
2582     gboolean building_index;
2583
2584     GST_OBJECT_LOCK (demux);
2585     /* handle the seek in the chain function */
2586     demux->seeking = TRUE;
2587     demux->state = FLV_STATE_SEEK;
2588
2589     /* copy the event */
2590     if (demux->seek_event)
2591       gst_event_unref (demux->seek_event);
2592     demux->seek_event = gst_event_ref (event);
2593
2594     /* set the building_index flag so that only one thread can setup the
2595      * structures for index seeking. */
2596     building_index = demux->building_index;
2597     if (!building_index) {
2598       demux->building_index = TRUE;
2599       if (!demux->file_size
2600           && !gst_pad_query_peer_duration (demux->sinkpad, GST_FORMAT_BYTES,
2601               &demux->file_size)) {
2602         GST_WARNING_OBJECT (demux, "Failed to query upstream file size");
2603         GST_OBJECT_UNLOCK (demux);
2604         return FALSE;
2605       }
2606
2607       /* we hope the last tag is a scriptdataobject containing an index
2608        * the size of the last tag is given in the last guint32 bits
2609        * then we seek to the beginning of the tag, parse it and hopefully obtain an index */
2610       seek_offset = demux->file_size - sizeof (guint32);
2611       GST_DEBUG_OBJECT (demux,
2612           "File size obtained, seeking to %" G_GUINT64_FORMAT, seek_offset);
2613     }
2614     GST_OBJECT_UNLOCK (demux);
2615
2616     if (!building_index) {
2617       GST_INFO_OBJECT (demux, "Seeking to last 4 bytes at %" G_GUINT64_FORMAT,
2618           seek_offset);
2619       return flv_demux_seek_to_offset (demux, seek_offset);
2620     }
2621
2622     /* FIXME: we have to always return true so that we don't block the seek
2623      * thread.
2624      * Note: maybe it is OK to return true if we're still building the index */
2625     return TRUE;
2626   }
2627
2628   return flv_demux_handle_seek_push (demux, event);
2629 }
2630
2631 static gboolean
2632 gst_flv_demux_handle_seek_pull (GstFlvDemux * demux, GstEvent * event,
2633     gboolean seeking)
2634 {
2635   GstFormat format;
2636   GstSeekFlags flags;
2637   GstSeekType start_type, stop_type;
2638   gint64 start, stop;
2639   gdouble rate;
2640   gboolean update, flush, ret = FALSE;
2641   GstSegment seeksegment;
2642
2643   gst_event_parse_seek (event, &rate, &format, &flags,
2644       &start_type, &start, &stop_type, &stop);
2645
2646   if (format != GST_FORMAT_TIME)
2647     goto wrong_format;
2648
2649   /* mark seeking thread entering flushing/pausing */
2650   GST_OBJECT_LOCK (demux);
2651   if (seeking)
2652     demux->seeking = seeking;
2653   GST_OBJECT_UNLOCK (demux);
2654
2655   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
2656   /* FIXME : the keyframe flag is never used */
2657
2658   if (flush) {
2659     /* Flush start up and downstream to make sure data flow and loops are
2660        idle */
2661     gst_flv_demux_push_src_event (demux, gst_event_new_flush_start ());
2662     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_start ());
2663   } else {
2664     /* Pause the pulling task */
2665     gst_pad_pause_task (demux->sinkpad);
2666   }
2667
2668   /* Take the stream lock */
2669   GST_PAD_STREAM_LOCK (demux->sinkpad);
2670
2671   if (flush) {
2672     /* Stop flushing upstream we need to pull */
2673     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_stop (TRUE));
2674   }
2675
2676   /* Work on a copy until we are sure the seek succeeded. */
2677   memcpy (&seeksegment, &demux->segment, sizeof (GstSegment));
2678
2679   GST_DEBUG_OBJECT (demux, "segment before configure %" GST_SEGMENT_FORMAT,
2680       &demux->segment);
2681
2682   /* Apply the seek to our segment */
2683   gst_segment_do_seek (&seeksegment, rate, format, flags,
2684       start_type, start, stop_type, stop, &update);
2685
2686   GST_DEBUG_OBJECT (demux, "segment configured %" GST_SEGMENT_FORMAT,
2687       &seeksegment);
2688
2689   if (flush || seeksegment.position != demux->segment.position) {
2690     /* Do the actual seeking */
2691     /* index is reliable if it is complete or we do not go to far ahead */
2692     if (seeking && !demux->indexed &&
2693         seeksegment.position > demux->index_max_time + 10 * GST_SECOND) {
2694       GST_DEBUG_OBJECT (demux, "delaying seek to post-scan; "
2695           " index only up to %" GST_TIME_FORMAT,
2696           GST_TIME_ARGS (demux->index_max_time));
2697       /* stop flushing for now */
2698       if (flush)
2699         gst_flv_demux_push_src_event (demux, gst_event_new_flush_stop (TRUE));
2700       /* delegate scanning and index building to task thread to avoid
2701        * occupying main (UI) loop */
2702       if (demux->seek_event)
2703         gst_event_unref (demux->seek_event);
2704       demux->seek_event = gst_event_ref (event);
2705       demux->seek_time = seeksegment.position;
2706       demux->state = FLV_STATE_SEEK;
2707       /* do not know about succes yet, but we did care and handled it */
2708       ret = TRUE;
2709       goto exit;
2710     }
2711     /* now index should be as reliable as it can be for current purpose */
2712     gst_flv_demux_move_to_offset (demux,
2713         gst_flv_demux_find_offset (demux, &seeksegment), TRUE);
2714     ret = TRUE;
2715   } else {
2716     ret = TRUE;
2717   }
2718
2719   if (flush) {
2720     /* Stop flushing, the sinks are at time 0 now */
2721     gst_flv_demux_push_src_event (demux, gst_event_new_flush_stop (TRUE));
2722   }
2723
2724   if (ret) {
2725     /* Ok seek succeeded, take the newly configured segment */
2726     memcpy (&demux->segment, &seeksegment, sizeof (GstSegment));
2727
2728     /* Notify about the start of a new segment */
2729     if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2730       gst_element_post_message (GST_ELEMENT (demux),
2731           gst_message_new_segment_start (GST_OBJECT (demux),
2732               demux->segment.format, demux->segment.position));
2733     }
2734
2735     /* Tell all the stream a new segment is needed */
2736     demux->audio_need_segment = TRUE;
2737     demux->video_need_segment = TRUE;
2738     /* Clean any potential newsegment event kept for the streams. The first
2739      * stream needing a new segment will create a new one. */
2740     if (G_UNLIKELY (demux->new_seg_event)) {
2741       gst_event_unref (demux->new_seg_event);
2742       demux->new_seg_event = NULL;
2743     }
2744     if (demux->segment.rate < 0.0) {
2745       /* we can't generate a segment by locking on
2746        * to the first timestamp we see */
2747       GST_DEBUG_OBJECT (demux, "preparing newsegment from %"
2748           GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2749           GST_TIME_ARGS (demux->segment.start),
2750           GST_TIME_ARGS (demux->segment.stop));
2751       demux->new_seg_event = gst_event_new_segment (&demux->segment);
2752     }
2753   }
2754
2755 exit:
2756   GST_OBJECT_LOCK (demux);
2757   seeking = demux->seeking && !seeking;
2758   demux->seeking = FALSE;
2759   GST_OBJECT_UNLOCK (demux);
2760
2761   /* if we detect an external seek having started (and possibly already having
2762    * flushed), do not restart task to give it a chance.
2763    * Otherwise external one's flushing will take care to pause task */
2764   if (seeking) {
2765     gst_pad_pause_task (demux->sinkpad);
2766   } else {
2767     gst_pad_start_task (demux->sinkpad,
2768         (GstTaskFunction) gst_flv_demux_loop, demux->sinkpad);
2769   }
2770
2771   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
2772
2773   gst_event_unref (event);
2774   return ret;
2775
2776   /* ERRORS */
2777 wrong_format:
2778   {
2779     GST_WARNING_OBJECT (demux, "we only support seeking in TIME format");
2780     gst_event_unref (event);
2781     return ret;
2782   }
2783 }
2784
2785 /* If we can pull that's prefered */
2786 static gboolean
2787 gst_flv_demux_sink_activate (GstPad * sinkpad)
2788 {
2789   GstQuery *query;
2790   gboolean pull_mode;
2791
2792   query = gst_query_new_scheduling ();
2793
2794   if (!gst_pad_peer_query (sinkpad, query)) {
2795     gst_query_unref (query);
2796     goto activate_push;
2797   }
2798
2799   gst_query_parse_scheduling (query, &pull_mode, NULL, NULL, NULL, NULL, NULL);
2800   gst_query_unref (query);
2801
2802   if (!pull_mode)
2803     goto activate_push;
2804
2805   GST_DEBUG_OBJECT (sinkpad, "activating pull");
2806   return gst_pad_activate_pull (sinkpad, TRUE);
2807
2808 activate_push:
2809   {
2810     GST_DEBUG_OBJECT (sinkpad, "activating push");
2811     return gst_pad_activate_push (sinkpad, TRUE);
2812   }
2813 }
2814
2815 /* This function gets called when we activate ourselves in push mode.
2816  * We cannot seek (ourselves) in the stream */
2817 static gboolean
2818 gst_flv_demux_sink_activate_push (GstPad * sinkpad, gboolean active)
2819 {
2820   GstFlvDemux *demux;
2821
2822   demux = GST_FLV_DEMUX (gst_pad_get_parent (sinkpad));
2823
2824   demux->random_access = FALSE;
2825
2826   gst_object_unref (demux);
2827
2828   return TRUE;
2829 }
2830
2831 /* this function gets called when we activate ourselves in pull mode.
2832  * We can perform  random access to the resource and we start a task
2833  * to start reading */
2834 static gboolean
2835 gst_flv_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
2836 {
2837   GstFlvDemux *demux;
2838
2839   demux = GST_FLV_DEMUX (gst_pad_get_parent (sinkpad));
2840
2841   if (active) {
2842     demux->random_access = TRUE;
2843     gst_object_unref (demux);
2844     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_flv_demux_loop,
2845         sinkpad);
2846   } else {
2847     demux->random_access = FALSE;
2848     gst_object_unref (demux);
2849     return gst_pad_stop_task (sinkpad);
2850   }
2851 }
2852
2853 static gboolean
2854 gst_flv_demux_sink_event (GstPad * pad, GstEvent * event)
2855 {
2856   GstFlvDemux *demux;
2857   gboolean ret = FALSE;
2858
2859   demux = GST_FLV_DEMUX (gst_pad_get_parent (pad));
2860
2861   GST_DEBUG_OBJECT (demux, "handling event %s", GST_EVENT_TYPE_NAME (event));
2862
2863   switch (GST_EVENT_TYPE (event)) {
2864     case GST_EVENT_FLUSH_START:
2865       GST_DEBUG_OBJECT (demux, "trying to force chain function to exit");
2866       demux->flushing = TRUE;
2867       ret = gst_flv_demux_push_src_event (demux, event);
2868       break;
2869     case GST_EVENT_FLUSH_STOP:
2870       GST_DEBUG_OBJECT (demux, "flushing FLV demuxer");
2871       gst_flv_demux_flush (demux, TRUE);
2872       ret = gst_flv_demux_push_src_event (demux, event);
2873       break;
2874     case GST_EVENT_EOS:
2875       GST_DEBUG_OBJECT (demux, "received EOS");
2876       if (demux->index) {
2877         GST_DEBUG_OBJECT (demux, "committing index");
2878         gst_index_commit (demux->index, demux->index_id);
2879       }
2880       if (!demux->no_more_pads) {
2881         gst_element_no_more_pads (GST_ELEMENT (demux));
2882         demux->no_more_pads = TRUE;
2883       }
2884
2885       if (!gst_flv_demux_push_src_event (demux, event))
2886         GST_WARNING_OBJECT (demux, "failed pushing EOS on streams");
2887       ret = TRUE;
2888       break;
2889     case GST_EVENT_SEGMENT:
2890     {
2891       GstSegment in_segment;
2892
2893       GST_DEBUG_OBJECT (demux, "received new segment");
2894
2895       gst_event_copy_segment (event, &in_segment);
2896
2897       if (in_segment.format == GST_FORMAT_TIME) {
2898         /* time segment, this is perfect, copy over the values. */
2899         memcpy (&demux->segment, &in_segment, sizeof (in_segment));
2900
2901         GST_DEBUG_OBJECT (demux, "NEWSEGMENT: %" GST_SEGMENT_FORMAT,
2902             &demux->segment);
2903
2904         /* and forward */
2905         ret = gst_flv_demux_push_src_event (demux, event);
2906       } else {
2907         /* non-time format */
2908         demux->audio_need_segment = TRUE;
2909         demux->video_need_segment = TRUE;
2910         ret = TRUE;
2911         gst_event_unref (event);
2912       }
2913       break;
2914     }
2915     default:
2916       ret = gst_flv_demux_push_src_event (demux, event);
2917       break;
2918   }
2919
2920   gst_object_unref (demux);
2921
2922   return ret;
2923 }
2924
2925 static gboolean
2926 gst_flv_demux_src_event (GstPad * pad, GstEvent * event)
2927 {
2928   GstFlvDemux *demux;
2929   gboolean ret = FALSE;
2930
2931   demux = GST_FLV_DEMUX (gst_pad_get_parent (pad));
2932
2933   GST_DEBUG_OBJECT (demux, "handling event %s", GST_EVENT_TYPE_NAME (event));
2934
2935   switch (GST_EVENT_TYPE (event)) {
2936     case GST_EVENT_SEEK:
2937       if (demux->random_access) {
2938         ret = gst_flv_demux_handle_seek_pull (demux, event, TRUE);
2939       } else {
2940         ret = gst_flv_demux_handle_seek_push (demux, event);
2941       }
2942       break;
2943     default:
2944       ret = gst_pad_push_event (demux->sinkpad, event);
2945       break;
2946   }
2947
2948   gst_object_unref (demux);
2949
2950   return ret;
2951 }
2952
2953 static gboolean
2954 gst_flv_demux_query (GstPad * pad, GstQuery * query)
2955 {
2956   gboolean res = TRUE;
2957   GstFlvDemux *demux;
2958
2959   demux = GST_FLV_DEMUX (gst_pad_get_parent (pad));
2960
2961   switch (GST_QUERY_TYPE (query)) {
2962     case GST_QUERY_DURATION:
2963     {
2964       GstFormat format;
2965
2966       gst_query_parse_duration (query, &format, NULL);
2967
2968       /* duration is time only */
2969       if (format != GST_FORMAT_TIME) {
2970         GST_DEBUG_OBJECT (demux, "duration query only supported for time "
2971             "format");
2972         res = FALSE;
2973         goto beach;
2974       }
2975
2976       GST_DEBUG_OBJECT (pad, "duration query, replying %" GST_TIME_FORMAT,
2977           GST_TIME_ARGS (demux->duration));
2978
2979       gst_query_set_duration (query, GST_FORMAT_TIME, demux->duration);
2980
2981       break;
2982     }
2983     case GST_QUERY_POSITION:
2984     {
2985       GstFormat format;
2986
2987       gst_query_parse_position (query, &format, NULL);
2988
2989       /* position is time only */
2990       if (format != GST_FORMAT_TIME) {
2991         GST_DEBUG_OBJECT (demux, "position query only supported for time "
2992             "format");
2993         res = FALSE;
2994         goto beach;
2995       }
2996
2997       GST_DEBUG_OBJECT (pad, "position query, replying %" GST_TIME_FORMAT,
2998           GST_TIME_ARGS (demux->segment.position));
2999
3000       gst_query_set_position (query, GST_FORMAT_TIME, demux->segment.position);
3001
3002       break;
3003     }
3004
3005     case GST_QUERY_SEEKING:{
3006       GstFormat fmt;
3007
3008       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3009
3010       /* First ask upstream */
3011       if (fmt == GST_FORMAT_TIME && gst_pad_peer_query (demux->sinkpad, query)) {
3012         gboolean seekable;
3013
3014         gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
3015         if (seekable) {
3016           res = TRUE;
3017           break;
3018         }
3019       }
3020       res = TRUE;
3021       if (fmt != GST_FORMAT_TIME || !demux->index) {
3022         gst_query_set_seeking (query, fmt, FALSE, -1, -1);
3023       } else if (demux->random_access) {
3024         gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0,
3025             demux->duration);
3026       } else {
3027         GstQuery *peerquery = gst_query_new_seeking (GST_FORMAT_BYTES);
3028         gboolean seekable = gst_pad_peer_query (demux->sinkpad, peerquery);
3029
3030         if (seekable)
3031           gst_query_parse_seeking (peerquery, NULL, &seekable, NULL, NULL);
3032         gst_query_unref (peerquery);
3033
3034         if (seekable)
3035           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0,
3036               demux->duration);
3037         else
3038           gst_query_set_seeking (query, GST_FORMAT_TIME, FALSE, -1, -1);
3039       }
3040       break;
3041     }
3042     case GST_QUERY_LATENCY:
3043     default:
3044     {
3045       GstPad *peer;
3046
3047       if ((peer = gst_pad_get_peer (demux->sinkpad))) {
3048         /* query latency on peer pad */
3049         res = gst_pad_query (peer, query);
3050         gst_object_unref (peer);
3051       } else {
3052         /* no peer, we don't know */
3053         res = FALSE;
3054       }
3055       break;
3056     }
3057   }
3058
3059 beach:
3060   gst_object_unref (demux);
3061
3062   return res;
3063 }
3064
3065 static GstStateChangeReturn
3066 gst_flv_demux_change_state (GstElement * element, GstStateChange transition)
3067 {
3068   GstFlvDemux *demux;
3069   GstStateChangeReturn ret;
3070
3071   demux = GST_FLV_DEMUX (element);
3072
3073   switch (transition) {
3074     case GST_STATE_CHANGE_READY_TO_PAUSED:
3075       /* If this is our own index destroy it as the
3076        * old entries might be wrong for the new stream */
3077       if (demux->own_index) {
3078         gst_object_unref (demux->index);
3079         demux->index = NULL;
3080         demux->own_index = FALSE;
3081       }
3082
3083       /* If no index was created, generate one */
3084       if (G_UNLIKELY (!demux->index)) {
3085         GST_DEBUG_OBJECT (demux, "no index provided creating our own");
3086
3087         demux->index = gst_index_factory_make ("memindex");
3088
3089         gst_index_get_writer_id (demux->index, GST_OBJECT (demux),
3090             &demux->index_id);
3091         demux->own_index = TRUE;
3092       }
3093       gst_flv_demux_cleanup (demux);
3094       break;
3095     default:
3096       break;
3097   }
3098
3099   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3100   if (ret == GST_STATE_CHANGE_FAILURE)
3101     return ret;
3102
3103   switch (transition) {
3104     case GST_STATE_CHANGE_PAUSED_TO_READY:
3105       gst_flv_demux_cleanup (demux);
3106       break;
3107     default:
3108       break;
3109   }
3110
3111   return ret;
3112 }
3113
3114 static void
3115 gst_flv_demux_set_index (GstElement * element, GstIndex * index)
3116 {
3117   GstFlvDemux *demux = GST_FLV_DEMUX (element);
3118
3119   GST_OBJECT_LOCK (demux);
3120   if (demux->index)
3121     gst_object_unref (demux->index);
3122   if (index) {
3123     demux->index = gst_object_ref (index);
3124     demux->own_index = FALSE;
3125   } else
3126     demux->index = NULL;
3127
3128   GST_OBJECT_UNLOCK (demux);
3129   /* object lock might be taken again */
3130   if (index)
3131     gst_index_get_writer_id (index, GST_OBJECT (element), &demux->index_id);
3132   GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT, demux->index);
3133
3134 }
3135
3136 static GstIndex *
3137 gst_flv_demux_get_index (GstElement * element)
3138 {
3139   GstIndex *result = NULL;
3140
3141   GstFlvDemux *demux = GST_FLV_DEMUX (element);
3142
3143   GST_OBJECT_LOCK (demux);
3144   if (demux->index)
3145     result = gst_object_ref (demux->index);
3146   GST_OBJECT_UNLOCK (demux);
3147
3148   return result;
3149 }
3150
3151 static void
3152 gst_flv_demux_dispose (GObject * object)
3153 {
3154   GstFlvDemux *demux = GST_FLV_DEMUX (object);
3155
3156   GST_DEBUG_OBJECT (demux, "disposing FLV demuxer");
3157
3158   if (demux->adapter) {
3159     gst_adapter_clear (demux->adapter);
3160     g_object_unref (demux->adapter);
3161     demux->adapter = NULL;
3162   }
3163
3164   if (demux->taglist) {
3165     gst_tag_list_free (demux->taglist);
3166     demux->taglist = NULL;
3167   }
3168
3169   if (demux->new_seg_event) {
3170     gst_event_unref (demux->new_seg_event);
3171     demux->new_seg_event = NULL;
3172   }
3173
3174   if (demux->audio_codec_data) {
3175     gst_buffer_unref (demux->audio_codec_data);
3176     demux->audio_codec_data = NULL;
3177   }
3178
3179   if (demux->video_codec_data) {
3180     gst_buffer_unref (demux->video_codec_data);
3181     demux->video_codec_data = NULL;
3182   }
3183
3184   if (demux->audio_pad) {
3185     gst_object_unref (demux->audio_pad);
3186     demux->audio_pad = NULL;
3187   }
3188
3189   if (demux->video_pad) {
3190     gst_object_unref (demux->video_pad);
3191     demux->video_pad = NULL;
3192   }
3193
3194   if (demux->index) {
3195     gst_object_unref (demux->index);
3196     demux->index = NULL;
3197   }
3198
3199   if (demux->times) {
3200     g_array_free (demux->times, TRUE);
3201     demux->times = NULL;
3202   }
3203
3204   if (demux->filepositions) {
3205     g_array_free (demux->filepositions, TRUE);
3206     demux->filepositions = NULL;
3207   }
3208
3209   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
3210 }
3211
3212 static void
3213 gst_flv_demux_class_init (GstFlvDemuxClass * klass)
3214 {
3215   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
3216   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
3217
3218   gobject_class->dispose = gst_flv_demux_dispose;
3219
3220   gstelement_class->change_state =
3221       GST_DEBUG_FUNCPTR (gst_flv_demux_change_state);
3222   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_flv_demux_set_index);
3223   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_flv_demux_get_index);
3224
3225   gst_element_class_add_pad_template (gstelement_class,
3226       gst_static_pad_template_get (&flv_sink_template));
3227   gst_element_class_add_pad_template (gstelement_class,
3228       gst_static_pad_template_get (&audio_src_template));
3229   gst_element_class_add_pad_template (gstelement_class,
3230       gst_static_pad_template_get (&video_src_template));
3231   gst_element_class_set_details_simple (gstelement_class, "FLV Demuxer",
3232       "Codec/Demuxer",
3233       "Demux FLV feeds into digital streams",
3234       "Julien Moutte <julien@moutte.net>");
3235 }
3236
3237 static void
3238 gst_flv_demux_init (GstFlvDemux * demux)
3239 {
3240   demux->sinkpad =
3241       gst_pad_new_from_static_template (&flv_sink_template, "sink");
3242
3243   gst_pad_set_event_function (demux->sinkpad,
3244       GST_DEBUG_FUNCPTR (gst_flv_demux_sink_event));
3245   gst_pad_set_chain_function (demux->sinkpad,
3246       GST_DEBUG_FUNCPTR (gst_flv_demux_chain));
3247   gst_pad_set_activate_function (demux->sinkpad,
3248       GST_DEBUG_FUNCPTR (gst_flv_demux_sink_activate));
3249   gst_pad_set_activatepull_function (demux->sinkpad,
3250       GST_DEBUG_FUNCPTR (gst_flv_demux_sink_activate_pull));
3251   gst_pad_set_activatepush_function (demux->sinkpad,
3252       GST_DEBUG_FUNCPTR (gst_flv_demux_sink_activate_push));
3253
3254   gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);
3255
3256   demux->adapter = gst_adapter_new ();
3257   demux->taglist = gst_tag_list_new ();
3258   gst_segment_init (&demux->segment, GST_FORMAT_TIME);
3259
3260   demux->own_index = FALSE;
3261
3262   gst_flv_demux_cleanup (demux);
3263 }
3264
3265 static gboolean
3266 plugin_init (GstPlugin * plugin)
3267 {
3268   GST_DEBUG_CATEGORY_INIT (flvdemux_debug, "flvdemux", 0, "FLV demuxer");
3269
3270   if (!gst_element_register (plugin, "flvdemux", GST_RANK_PRIMARY,
3271           gst_flv_demux_get_type ()) ||
3272       !gst_element_register (plugin, "flvmux", GST_RANK_PRIMARY,
3273           gst_flv_mux_get_type ()))
3274     return FALSE;
3275
3276   return TRUE;
3277 }
3278
3279 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR,
3280     "flv", "FLV muxing and demuxing plugin",
3281     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)