flvmux: don't try to push already-freed buffers
[platform/upstream/gst-plugins-good.git] / gst / flv / gstflvmux.c
1 /* GStreamer
2  *
3  * Copyright (c) 2008,2009 Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-flvmux
23  *
24  * flvmux muxes different streams into an FLV file.
25  *
26  * <refsect2>
27  * <title>Example launch line</title>
28  * |[
29  * gst-launch -v filesrc location=/path/to/audio ! decodebin2 ! queue ! flvmux name=m ! filesink location=file.flv   filesrc location=/path/to/video ! decodebin2 ! queue ! m.
30  * ]| This pipeline muxes an audio and video file into a single FLV file.
31  * </refsect2>
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #include <math.h>
39 #include <string.h>
40
41 #include "gstflvmux.h"
42 #include "amfdefs.h"
43
44 GST_DEBUG_CATEGORY_STATIC (flvmux_debug);
45 #define GST_CAT_DEFAULT flvmux_debug
46
47 enum
48 {
49   PROP_0,
50   PROP_STREAMABLE
51 };
52
53 #define DEFAULT_STREAMABLE FALSE
54 #define MAX_INDEX_ENTRIES 128
55
56 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
57     GST_PAD_SRC,
58     GST_PAD_ALWAYS,
59     GST_STATIC_CAPS ("video/x-flv")
60     );
61
62 static GstStaticPadTemplate videosink_templ = GST_STATIC_PAD_TEMPLATE ("video",
63     GST_PAD_SINK,
64     GST_PAD_REQUEST,
65     GST_STATIC_CAPS ("video/x-flash-video; "
66         "video/x-flash-screen; "
67         "video/x-vp6-flash; " "video/x-vp6-alpha; "
68         "video/x-h264, stream-format=avc;")
69     );
70
71 static GstStaticPadTemplate audiosink_templ = GST_STATIC_PAD_TEMPLATE ("audio",
72     GST_PAD_SINK,
73     GST_PAD_REQUEST,
74     GST_STATIC_CAPS
75     ("audio/x-adpcm, layout = (string) swf, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
76         "audio/mpeg, mpegversion = (int) 1, layer = (int) 3, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 22050, 44100 }, parsed = (boolean) TRUE; "
77         "audio/mpeg, mpegversion = (int) { 2, 4 }, framed = (boolean) TRUE; "
78         "audio/x-nellymoser, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 16000, 22050, 44100 }; "
79         "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; "
80         "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; "
81         "audio/x-alaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
82         "audio/x-mulaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
83         "audio/x-speex, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 };")
84     );
85
86 #define _do_init(type)                                                          \
87   G_STMT_START{                                                                 \
88     static const GInterfaceInfo tag_setter_info = {                             \
89       NULL,                                                                     \
90       NULL,                                                                     \
91       NULL                                                                      \
92     };                                                                          \
93     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER,                     \
94                                  &tag_setter_info);                             \
95   }G_STMT_END
96
97 GST_BOILERPLATE_FULL (GstFlvMux, gst_flv_mux, GstElement, GST_TYPE_ELEMENT,
98     _do_init);
99
100 static void gst_flv_mux_finalize (GObject * object);
101 static GstFlowReturn
102 gst_flv_mux_handle_buffer (GstCollectPads2 * pads, GstCollectData2 * cdata,
103     GstBuffer * buf, gpointer user_data);
104 static gboolean
105 gst_flv_mux_handle_sink_event (GstCollectPads2 * pads, GstCollectData2 * data,
106     GstEvent * event, gpointer user_data);
107
108 static gboolean gst_flv_mux_handle_src_event (GstPad * pad, GstEvent * event);
109 static GstPad *gst_flv_mux_request_new_pad (GstElement * element,
110     GstPadTemplate * templ, const gchar * name);
111 static void gst_flv_mux_release_pad (GstElement * element, GstPad * pad);
112
113 static void gst_flv_mux_get_property (GObject * object,
114     guint prop_id, GValue * value, GParamSpec * pspec);
115 static void gst_flv_mux_set_property (GObject * object,
116     guint prop_id, const GValue * value, GParamSpec * pspec);
117
118 static GstStateChangeReturn
119 gst_flv_mux_change_state (GstElement * element, GstStateChange transition);
120
121 static void gst_flv_mux_reset (GstElement * element);
122 static void gst_flv_mux_reset_pad (GstFlvMux * mux, GstFlvPad * pad,
123     gboolean video);
124
125 typedef struct
126 {
127   gdouble position;
128   gdouble time;
129 } GstFlvMuxIndexEntry;
130
131 static void
132 gst_flv_mux_index_entry_free (GstFlvMuxIndexEntry * entry)
133 {
134   g_slice_free (GstFlvMuxIndexEntry, entry);
135 }
136
137 static void
138 gst_flv_mux_base_init (gpointer g_class)
139 {
140   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
141
142   gst_element_class_add_static_pad_template (element_class,
143       &videosink_templ);
144   gst_element_class_add_static_pad_template (element_class,
145       &audiosink_templ);
146   gst_element_class_add_static_pad_template (element_class, &src_templ);
147   gst_element_class_set_details_simple (element_class, "FLV muxer",
148       "Codec/Muxer",
149       "Muxes video/audio streams into a FLV stream",
150       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
151
152   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
153 }
154
155 static void
156 gst_flv_mux_class_init (GstFlvMuxClass * klass)
157 {
158   GObjectClass *gobject_class;
159   GstElementClass *gstelement_class;
160
161   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
162
163   gobject_class = (GObjectClass *) klass;
164   gstelement_class = (GstElementClass *) klass;
165
166   gobject_class->get_property = gst_flv_mux_get_property;
167   gobject_class->set_property = gst_flv_mux_set_property;
168   gobject_class->finalize = gst_flv_mux_finalize;
169
170   /* FIXME: ideally the right mode of operation should be detected
171    * automatically using queries when parameter not specified. */
172   /**
173    * GstFlvMux:streamable
174    *
175    * If True, the output will be streaming friendly. (ie without indexes and
176    * duration)
177    *
178    * Since: 0.10.24
179    **/
180   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
181       g_param_spec_boolean ("streamable", "streamable",
182           "If set to true, the output should be as if it is to be streamed "
183           "and hence no indexes written or duration written.",
184           DEFAULT_STREAMABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
185
186   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_flv_mux_change_state);
187   gstelement_class->request_new_pad =
188       GST_DEBUG_FUNCPTR (gst_flv_mux_request_new_pad);
189   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_flv_mux_release_pad);
190 }
191
192 static void
193 gst_flv_mux_init (GstFlvMux * mux, GstFlvMuxClass * g_class)
194 {
195   mux->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
196   gst_pad_set_event_function (mux->srcpad, gst_flv_mux_handle_src_event);
197   gst_element_add_pad (GST_ELEMENT (mux), mux->srcpad);
198
199   /* property */
200   mux->streamable = DEFAULT_STREAMABLE;
201
202   mux->new_tags = FALSE;
203
204   mux->collect = gst_collect_pads2_new ();
205   gst_collect_pads2_set_buffer_function (mux->collect,
206       GST_DEBUG_FUNCPTR (gst_flv_mux_handle_buffer), mux);
207   gst_collect_pads2_set_event_function (mux->collect,
208       GST_DEBUG_FUNCPTR (gst_flv_mux_handle_sink_event), mux);
209   gst_collect_pads2_set_clip_function (mux->collect,
210       GST_DEBUG_FUNCPTR (gst_collect_pads2_clip_running_time), mux);
211
212   gst_flv_mux_reset (GST_ELEMENT (mux));
213 }
214
215 static void
216 gst_flv_mux_finalize (GObject * object)
217 {
218   GstFlvMux *mux = GST_FLV_MUX (object);
219
220   gst_object_unref (mux->collect);
221
222   G_OBJECT_CLASS (parent_class)->finalize (object);
223 }
224
225 static void
226 gst_flv_mux_reset (GstElement * element)
227 {
228   GstFlvMux *mux = GST_FLV_MUX (element);
229   GSList *sl;
230
231   for (sl = mux->collect->data; sl != NULL; sl = g_slist_next (sl)) {
232     GstFlvPad *cpad = (GstFlvPad *) sl->data;
233
234     gst_flv_mux_reset_pad (mux, cpad, cpad->video);
235   }
236
237   g_list_foreach (mux->index, (GFunc) gst_flv_mux_index_entry_free, NULL);
238   g_list_free (mux->index);
239   mux->index = NULL;
240   mux->byte_count = 0;
241
242   mux->have_audio = mux->have_video = FALSE;
243   mux->duration = GST_CLOCK_TIME_NONE;
244   mux->new_tags = FALSE;
245
246   mux->state = GST_FLV_MUX_STATE_HEADER;
247
248   /* tags */
249   gst_tag_setter_reset_tags (GST_TAG_SETTER (mux));
250 }
251
252 static gboolean
253 gst_flv_mux_handle_src_event (GstPad * pad, GstEvent * event)
254 {
255   GstEventType type;
256
257   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
258
259   switch (type) {
260     case GST_EVENT_SEEK:
261       /* disable seeking for now */
262       return FALSE;
263     default:
264       break;
265   }
266
267   return gst_pad_event_default (pad, event);
268 }
269
270 static gboolean
271 gst_flv_mux_handle_sink_event (GstCollectPads2 * pads, GstCollectData2 * data,
272     GstEvent * event, gpointer user_data)
273 {
274   GstFlvMux *mux = GST_FLV_MUX (user_data);
275
276   switch (GST_EVENT_TYPE (event)) {
277     case GST_EVENT_TAG:{
278       GstTagList *list;
279       GstTagSetter *setter = GST_TAG_SETTER (mux);
280       const GstTagMergeMode mode = gst_tag_setter_get_tag_merge_mode (setter);
281
282       gst_event_parse_tag (event, &list);
283       gst_tag_setter_merge_tags (setter, list, mode);
284       mux->new_tags = TRUE;
285       break;
286     }
287     default:
288       break;
289   }
290
291   /* now GstCollectPads2 can take care of the rest, e.g. EOS */
292   return FALSE;
293 }
294
295 static gboolean
296 gst_flv_mux_video_pad_setcaps (GstPad * pad, GstCaps * caps)
297 {
298   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
299   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
300   gboolean ret = TRUE;
301   GstStructure *s;
302
303   s = gst_caps_get_structure (caps, 0);
304
305   if (strcmp (gst_structure_get_name (s), "video/x-flash-video") == 0) {
306     cpad->video_codec = 2;
307   } else if (strcmp (gst_structure_get_name (s), "video/x-flash-screen") == 0) {
308     cpad->video_codec = 3;
309   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-flash") == 0) {
310     cpad->video_codec = 4;
311   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-alpha") == 0) {
312     cpad->video_codec = 5;
313   } else if (strcmp (gst_structure_get_name (s), "video/x-h264") == 0) {
314     cpad->video_codec = 7;
315   } else {
316     ret = FALSE;
317   }
318
319   if (ret && gst_structure_has_field (s, "codec_data")) {
320     const GValue *val = gst_structure_get_value (s, "codec_data");
321
322     if (val)
323       cpad->video_codec_data = gst_buffer_ref (gst_value_get_buffer (val));
324   }
325
326   gst_object_unref (mux);
327
328   return ret;
329 }
330
331 static gboolean
332 gst_flv_mux_audio_pad_setcaps (GstPad * pad, GstCaps * caps)
333 {
334   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
335   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
336   gboolean ret = TRUE;
337   GstStructure *s;
338
339   s = gst_caps_get_structure (caps, 0);
340
341   if (strcmp (gst_structure_get_name (s), "audio/x-adpcm") == 0) {
342     const gchar *layout = gst_structure_get_string (s, "layout");
343     if (layout && strcmp (layout, "swf") == 0) {
344       cpad->audio_codec = 1;
345     } else {
346       ret = FALSE;
347     }
348   } else if (strcmp (gst_structure_get_name (s), "audio/mpeg") == 0) {
349     gint mpegversion;
350
351     if (gst_structure_get_int (s, "mpegversion", &mpegversion)) {
352       if (mpegversion == 1) {
353         gint layer;
354
355         if (gst_structure_get_int (s, "layer", &layer) && layer == 3) {
356           gint rate;
357
358           if (gst_structure_get_int (s, "rate", &rate) && rate == 8000)
359             cpad->audio_codec = 14;
360           else
361             cpad->audio_codec = 2;
362         } else {
363           ret = FALSE;
364         }
365       } else if (mpegversion == 4 || mpegversion == 2) {
366         cpad->audio_codec = 10;
367       } else {
368         ret = FALSE;
369       }
370     } else {
371       ret = FALSE;
372     }
373   } else if (strcmp (gst_structure_get_name (s), "audio/x-nellymoser") == 0) {
374     gint rate, channels;
375
376     if (gst_structure_get_int (s, "rate", &rate)
377         && gst_structure_get_int (s, "channels", &channels)) {
378       if (channels == 1 && rate == 16000)
379         cpad->audio_codec = 4;
380       else if (channels == 1 && rate == 8000)
381         cpad->audio_codec = 5;
382       else
383         cpad->audio_codec = 6;
384     } else {
385       cpad->audio_codec = 6;
386     }
387   } else if (strcmp (gst_structure_get_name (s), "audio/x-raw-int") == 0) {
388     gint endianness;
389
390     if (gst_structure_get_int (s, "endianness", &endianness)
391         && endianness == G_LITTLE_ENDIAN)
392       cpad->audio_codec = 3;
393     else
394       ret = FALSE;
395   } else if (strcmp (gst_structure_get_name (s), "audio/x-alaw") == 0) {
396     cpad->audio_codec = 7;
397   } else if (strcmp (gst_structure_get_name (s), "audio/x-mulaw") == 0) {
398     cpad->audio_codec = 8;
399   } else if (strcmp (gst_structure_get_name (s), "audio/x-speex") == 0) {
400     cpad->audio_codec = 11;
401   } else {
402     ret = FALSE;
403   }
404
405   if (ret) {
406     gint rate, channels, width;
407
408     if (gst_structure_get_int (s, "rate", &rate)) {
409       if (cpad->audio_codec == 10)
410         cpad->rate = 3;
411       else if (rate == 5512)
412         cpad->rate = 0;
413       else if (rate == 11025)
414         cpad->rate = 1;
415       else if (rate == 22050)
416         cpad->rate = 2;
417       else if (rate == 44100)
418         cpad->rate = 3;
419       else if (rate == 8000 && (cpad->audio_codec == 5
420               || cpad->audio_codec == 14))
421         cpad->rate = 0;
422       else if (rate == 16000 && cpad->audio_codec == 4)
423         cpad->rate = 0;
424       else
425         ret = FALSE;
426     } else if (cpad->audio_codec == 10) {
427       cpad->rate = 3;
428     } else {
429       ret = FALSE;
430     }
431
432     if (gst_structure_get_int (s, "channels", &channels)) {
433       if (cpad->audio_codec == 4 || cpad->audio_codec == 5
434           || cpad->audio_codec == 6)
435         cpad->channels = 0;
436       else if (cpad->audio_codec == 10)
437         cpad->channels = 1;
438       else if (channels == 1)
439         cpad->channels = 0;
440       else if (channels == 2)
441         cpad->channels = 1;
442       else
443         ret = FALSE;
444     } else if (cpad->audio_codec == 4 || cpad->audio_codec == 5
445         || cpad->audio_codec == 6) {
446       cpad->channels = 0;
447     } else if (cpad->audio_codec == 10) {
448       cpad->channels = 1;
449     } else {
450       ret = FALSE;
451     }
452
453     if (gst_structure_get_int (s, "width", &width)) {
454       if (cpad->audio_codec != 3)
455         cpad->width = 1;
456       else if (width == 8)
457         cpad->width = 0;
458       else if (width == 16)
459         cpad->width = 1;
460       else
461         ret = FALSE;
462     } else if (cpad->audio_codec != 3) {
463       cpad->width = 1;
464     } else {
465       ret = FALSE;
466     }
467   }
468
469   if (ret && gst_structure_has_field (s, "codec_data")) {
470     const GValue *val = gst_structure_get_value (s, "codec_data");
471
472     if (val)
473       cpad->audio_codec_data = gst_buffer_ref (gst_value_get_buffer (val));
474   }
475
476   gst_object_unref (mux);
477
478   return ret;
479 }
480
481 static void
482 gst_flv_mux_reset_pad (GstFlvMux * mux, GstFlvPad * cpad, gboolean video)
483 {
484   cpad->video = video;
485
486   if (cpad->audio_codec_data)
487     gst_buffer_unref (cpad->audio_codec_data);
488   cpad->audio_codec_data = NULL;
489   cpad->audio_codec = G_MAXUINT;
490   cpad->rate = G_MAXUINT;
491   cpad->width = G_MAXUINT;
492   cpad->channels = G_MAXUINT;
493
494   if (cpad->video_codec_data)
495     gst_buffer_unref (cpad->video_codec_data);
496   cpad->video_codec_data = NULL;
497   cpad->video_codec = G_MAXUINT;
498   cpad->last_timestamp = 0;
499 }
500
501 static GstPad *
502 gst_flv_mux_request_new_pad (GstElement * element,
503     GstPadTemplate * templ, const gchar * pad_name)
504 {
505   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
506   GstFlvMux *mux = GST_FLV_MUX (element);
507   GstFlvPad *cpad;
508   GstPad *pad = NULL;
509   const gchar *name = NULL;
510   GstPadSetCapsFunction setcapsfunc = NULL;
511   gboolean video;
512
513   if (mux->state != GST_FLV_MUX_STATE_HEADER) {
514     GST_WARNING_OBJECT (mux, "Can't request pads after writing header");
515     return NULL;
516   }
517
518   if (templ == gst_element_class_get_pad_template (klass, "audio")) {
519     if (mux->have_audio) {
520       GST_WARNING_OBJECT (mux, "Already have an audio pad");
521       return NULL;
522     }
523     mux->have_audio = TRUE;
524     name = "audio";
525     video = FALSE;
526     setcapsfunc = GST_DEBUG_FUNCPTR (gst_flv_mux_audio_pad_setcaps);
527   } else if (templ == gst_element_class_get_pad_template (klass, "video")) {
528     if (mux->have_video) {
529       GST_WARNING_OBJECT (mux, "Already have a video pad");
530       return NULL;
531     }
532     mux->have_video = TRUE;
533     name = "video";
534     video = TRUE;
535     setcapsfunc = GST_DEBUG_FUNCPTR (gst_flv_mux_video_pad_setcaps);
536   } else {
537     GST_WARNING_OBJECT (mux, "Invalid template");
538     return NULL;
539   }
540
541   pad = gst_pad_new_from_template (templ, name);
542   cpad = (GstFlvPad *)
543       gst_collect_pads2_add_pad (mux->collect, pad, sizeof (GstFlvPad));
544
545   cpad->audio_codec_data = NULL;
546   cpad->video_codec_data = NULL;
547   gst_flv_mux_reset_pad (mux, cpad, video);
548
549   gst_pad_set_setcaps_function (pad, setcapsfunc);
550   gst_pad_set_active (pad, TRUE);
551   gst_element_add_pad (element, pad);
552
553   return pad;
554 }
555
556 static void
557 gst_flv_mux_release_pad (GstElement * element, GstPad * pad)
558 {
559   GstFlvMux *mux = GST_FLV_MUX (GST_PAD_PARENT (pad));
560   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
561
562   gst_flv_mux_reset_pad (mux, cpad, cpad->video);
563   gst_collect_pads2_remove_pad (mux->collect, pad);
564   gst_element_remove_pad (element, pad);
565 }
566
567 static GstFlowReturn
568 gst_flv_mux_push (GstFlvMux * mux, GstBuffer * buffer)
569 {
570   buffer = gst_buffer_make_metadata_writable (buffer);
571   gst_buffer_set_caps (buffer, GST_PAD_CAPS (mux->srcpad));
572   /* pushing the buffer that rewrites the header will make it no longer be the
573    * total output size in bytes, but it doesn't matter at that point */
574   mux->byte_count += GST_BUFFER_SIZE (buffer);
575
576   return gst_pad_push (mux->srcpad, buffer);
577 }
578
579 static GstBuffer *
580 gst_flv_mux_create_header (GstFlvMux * mux)
581 {
582   GstBuffer *header;
583   guint8 *data;
584
585   header = gst_buffer_new_and_alloc (9 + 4);
586   data = GST_BUFFER_DATA (header);
587
588   data[0] = 'F';
589   data[1] = 'L';
590   data[2] = 'V';
591   data[3] = 0x01;               /* Version */
592
593   data[4] = (mux->have_audio << 2) | mux->have_video;   /* flags */
594   GST_WRITE_UINT32_BE (data + 5, 9);    /* data offset */
595   GST_WRITE_UINT32_BE (data + 9, 0);    /* previous tag size */
596
597   return header;
598 }
599
600 static GstBuffer *
601 gst_flv_mux_preallocate_index (GstFlvMux * mux)
602 {
603   GstBuffer *tmp;
604   guint8 *data;
605   gint preallocate_size;
606
607   /* preallocate index of size:
608    *  - 'keyframes' ECMA array key: 2 + 9 = 11 bytes
609    *  - nested ECMA array header, length and end marker: 8 bytes
610    *  - 'times' and 'filepositions' keys: 22 bytes
611    *  - two strict arrays headers and lengths: 10 bytes
612    *  - each index entry: 18 bytes
613    */
614   preallocate_size = 11 + 8 + 22 + 10 + MAX_INDEX_ENTRIES * 18;
615   GST_DEBUG_OBJECT (mux, "preallocating %d bytes for the index",
616       preallocate_size);
617
618   tmp = gst_buffer_new_and_alloc (preallocate_size);
619   data = GST_BUFFER_DATA (tmp);
620
621   /* prefill the space with a gstfiller: <spaces> script tag variable */
622   GST_WRITE_UINT16_BE (data, 9);        /* 9 characters */
623   memcpy (data + 2, "gstfiller", 9);
624   GST_WRITE_UINT8 (data + 11, AMF0_STRING_MARKER);      /* a string value */
625   GST_WRITE_UINT16_BE (data + 12, preallocate_size - 14);
626   memset (data + 14, ' ', preallocate_size - 14);       /* the rest is spaces */
627   return tmp;
628 }
629
630 static GstBuffer *
631 gst_flv_mux_create_number_script_value (const gchar * name, gdouble value)
632 {
633   GstBuffer *tmp = gst_buffer_new_and_alloc (2 + strlen (name) + 1 + 8);
634   guint8 *data = GST_BUFFER_DATA (tmp);
635   gsize len = strlen (name);
636
637   GST_WRITE_UINT16_BE (data, len);
638   data += 2;                    /* name length */
639   memcpy (data, name, len);
640   data += len;
641   *data++ = AMF0_NUMBER_MARKER; /* double type */
642   GST_WRITE_DOUBLE_BE (data, value);
643
644   return tmp;
645 }
646
647 static GstBuffer *
648 gst_flv_mux_create_metadata (GstFlvMux * mux, gboolean full)
649 {
650   const GstTagList *tags;
651   GstBuffer *script_tag, *tmp;
652   guint8 *data;
653   gint i, n_tags, tags_written = 0;
654
655   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
656
657   GST_DEBUG_OBJECT (mux, "tags = %" GST_PTR_FORMAT, tags);
658
659   script_tag = gst_buffer_new_and_alloc (11);
660   data = GST_BUFFER_DATA (script_tag);
661
662   data[0] = 18;
663
664   /* Data size, unknown for now */
665   data[1] = 0;
666   data[2] = 0;
667   data[3] = 0;
668
669   /* Timestamp */
670   data[4] = data[5] = data[6] = data[7] = 0;
671
672   /* Stream ID */
673   data[8] = data[9] = data[10] = 0;
674
675   tmp = gst_buffer_new_and_alloc (13);
676   data = GST_BUFFER_DATA (tmp);
677   data[0] = AMF0_STRING_MARKER; /* string */
678   data[1] = 0;
679   data[2] = 10;                 /* length 10 */
680   memcpy (&data[3], "onMetaData", 10);
681
682   script_tag = gst_buffer_join (script_tag, tmp);
683
684   n_tags = (tags) ? gst_structure_n_fields ((GstStructure *) tags) : 0;
685   tmp = gst_buffer_new_and_alloc (5);
686   data = GST_BUFFER_DATA (tmp);
687   data[0] = 8;                  /* ECMA array */
688   GST_WRITE_UINT32_BE (data + 1, n_tags);
689   script_tag = gst_buffer_join (script_tag, tmp);
690
691   if (!full)
692     goto tags;
693
694   /* Some players expect the 'duration' to be always set. Fill it out later,
695      after querying the pads or after getting EOS */
696   if (!mux->streamable) {
697     tmp = gst_flv_mux_create_number_script_value ("duration", 86400);
698     script_tag = gst_buffer_join (script_tag, tmp);
699     tags_written++;
700
701     /* Sometimes the information about the total file size is useful for the
702        player. It will be filled later, after getting EOS */
703     tmp = gst_flv_mux_create_number_script_value ("filesize", 0);
704     script_tag = gst_buffer_join (script_tag, tmp);
705     tags_written++;
706
707     /* Preallocate space for the index to be written at EOS */
708     tmp = gst_flv_mux_preallocate_index (mux);
709     script_tag = gst_buffer_join (script_tag, tmp);
710   } else {
711     GST_DEBUG_OBJECT (mux, "not preallocating index, streamable mode");
712   }
713
714 tags:
715   for (i = 0; tags && i < n_tags; i++) {
716     const gchar *tag_name =
717         gst_structure_nth_field_name ((const GstStructure *) tags, i);
718     if (!strcmp (tag_name, GST_TAG_DURATION)) {
719       guint64 dur;
720
721       if (!gst_tag_list_get_uint64 (tags, GST_TAG_DURATION, &dur))
722         continue;
723       mux->duration = dur;
724     } else if (!strcmp (tag_name, GST_TAG_ARTIST) ||
725         !strcmp (tag_name, GST_TAG_TITLE)) {
726       gchar *s;
727       const gchar *t = NULL;
728
729       if (!strcmp (tag_name, GST_TAG_ARTIST))
730         t = "creator";
731       else if (!strcmp (tag_name, GST_TAG_TITLE))
732         t = "title";
733
734       if (!gst_tag_list_get_string (tags, tag_name, &s))
735         continue;
736
737       tmp = gst_buffer_new_and_alloc (2 + strlen (t) + 1 + 2 + strlen (s));
738       data = GST_BUFFER_DATA (tmp);
739       data[0] = 0;              /* tag name length */
740       data[1] = strlen (t);
741       memcpy (&data[2], t, strlen (t));
742       data[2 + strlen (t)] = 2; /* string */
743       data[3 + strlen (t)] = (strlen (s) >> 8) & 0xff;
744       data[4 + strlen (t)] = (strlen (s)) & 0xff;
745       memcpy (&data[5 + strlen (t)], s, strlen (s));
746       script_tag = gst_buffer_join (script_tag, tmp);
747
748       g_free (s);
749       tags_written++;
750     }
751   }
752
753   if (!full)
754     goto end;
755
756   if (mux->duration == GST_CLOCK_TIME_NONE) {
757     GSList *l;
758
759     GstFormat fmt = GST_FORMAT_TIME;
760     guint64 dur;
761
762     for (l = mux->collect->data; l; l = l->next) {
763       GstCollectData2 *cdata = l->data;
764
765       fmt = GST_FORMAT_TIME;
766
767       if (gst_pad_query_peer_duration (cdata->pad, &fmt, (gint64 *) & dur) &&
768           fmt == GST_FORMAT_TIME && dur != GST_CLOCK_TIME_NONE) {
769         if (mux->duration == GST_CLOCK_TIME_NONE)
770           mux->duration = dur;
771         else
772           mux->duration = MAX (dur, mux->duration);
773       }
774     }
775   }
776
777   if (!mux->streamable && mux->duration != GST_CLOCK_TIME_NONE) {
778     gdouble d;
779     d = gst_guint64_to_gdouble (mux->duration);
780     d /= (gdouble) GST_SECOND;
781
782     GST_DEBUG_OBJECT (mux, "determined the duration to be %f", d);
783     data = GST_BUFFER_DATA (script_tag);
784     GST_WRITE_DOUBLE_BE (data + 29 + 2 + 8 + 1, d);
785   }
786
787   if (mux->have_video) {
788     GstPad *video_pad = NULL;
789     GstFlvPad *cpad;
790     GSList *l = mux->collect->data;
791
792     for (; l; l = l->next) {
793       cpad = l->data;
794       if (cpad && cpad->video) {
795         video_pad = cpad->collect.pad;
796         break;
797       }
798     }
799
800     if (video_pad && GST_PAD_CAPS (video_pad)) {
801       GstStructure *s = gst_caps_get_structure (GST_PAD_CAPS (video_pad), 0);
802       gint size;
803       gint num, den;
804
805       GST_DEBUG_OBJECT (mux, "putting videocodecid %d in the metadata",
806           cpad->video_codec);
807
808       tmp = gst_flv_mux_create_number_script_value ("videocodecid",
809           cpad->video_codec);
810       script_tag = gst_buffer_join (script_tag, tmp);
811       tags_written++;
812
813       if (gst_structure_get_int (s, "width", &size)) {
814         GST_DEBUG_OBJECT (mux, "putting width %d in the metadata", size);
815
816         tmp = gst_flv_mux_create_number_script_value ("width", size);
817         script_tag = gst_buffer_join (script_tag, tmp);
818         tags_written++;
819       }
820
821       if (gst_structure_get_int (s, "height", &size)) {
822         GST_DEBUG_OBJECT (mux, "putting height %d in the metadata", size);
823
824         tmp = gst_flv_mux_create_number_script_value ("height", size);
825         script_tag = gst_buffer_join (script_tag, tmp);
826         tags_written++;
827       }
828
829       if (gst_structure_get_fraction (s, "pixel-aspect-ratio", &num, &den)) {
830         gdouble d;
831
832         d = num;
833         GST_DEBUG_OBJECT (mux, "putting AspectRatioX %f in the metadata", d);
834
835         tmp = gst_flv_mux_create_number_script_value ("AspectRatioX", d);
836         script_tag = gst_buffer_join (script_tag, tmp);
837         tags_written++;
838
839         d = den;
840         GST_DEBUG_OBJECT (mux, "putting AspectRatioY %f in the metadata", d);
841
842         tmp = gst_flv_mux_create_number_script_value ("AspectRatioY", d);
843         script_tag = gst_buffer_join (script_tag, tmp);
844         tags_written++;
845       }
846
847       if (gst_structure_get_fraction (s, "framerate", &num, &den)) {
848         gdouble d;
849
850         gst_util_fraction_to_double (num, den, &d);
851         GST_DEBUG_OBJECT (mux, "putting framerate %f in the metadata", d);
852
853         tmp = gst_flv_mux_create_number_script_value ("framerate", d);
854         script_tag = gst_buffer_join (script_tag, tmp);
855         tags_written++;
856       }
857     }
858   }
859
860   if (mux->have_audio) {
861     GstPad *audio_pad = NULL;
862     GstFlvPad *cpad;
863     GSList *l = mux->collect->data;
864
865     for (; l; l = l->next) {
866       cpad = l->data;
867       if (cpad && !cpad->video) {
868         audio_pad = cpad->collect.pad;
869         break;
870       }
871     }
872
873     if (audio_pad) {
874       GST_DEBUG_OBJECT (mux, "putting audiocodecid %d in the metadata",
875           cpad->audio_codec);
876
877       tmp = gst_flv_mux_create_number_script_value ("audiocodecid",
878           cpad->audio_codec);
879       script_tag = gst_buffer_join (script_tag, tmp);
880       tags_written++;
881     }
882   }
883
884   {
885     const gchar *s = "GStreamer FLV muxer";
886
887     tmp = gst_buffer_new_and_alloc (2 + 15 + 1 + 2 + strlen (s));
888     data = GST_BUFFER_DATA (tmp);
889     data[0] = 0;                /* 15 bytes name */
890     data[1] = 15;
891     memcpy (&data[2], "metadatacreator", 15);
892     data[17] = 2;               /* string */
893     data[18] = (strlen (s) >> 8) & 0xff;
894     data[19] = (strlen (s)) & 0xff;
895     memcpy (&data[20], s, strlen (s));
896     script_tag = gst_buffer_join (script_tag, tmp);
897
898     tags_written++;
899   }
900
901   {
902     GTimeVal tv = { 0, };
903     time_t secs;
904     struct tm *tm;
905     gchar *s;
906     static const gchar *weekdays[] = {
907       "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
908     };
909     static const gchar *months[] = {
910       "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
911       "Aug", "Sep", "Oct", "Nov", "Dec"
912     };
913
914     g_get_current_time (&tv);
915     secs = tv.tv_sec;
916     tm = gmtime (&secs);
917
918     s = g_strdup_printf ("%s %s %d %d:%d:%d %d", weekdays[tm->tm_wday],
919         months[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
920         tm->tm_year + 1900);
921
922     tmp = gst_buffer_new_and_alloc (2 + 12 + 1 + 2 + strlen (s));
923     data = GST_BUFFER_DATA (tmp);
924     data[0] = 0;                /* 12 bytes name */
925     data[1] = 12;
926     memcpy (&data[2], "creationdate", 12);
927     data[14] = 2;               /* string */
928     data[15] = (strlen (s) >> 8) & 0xff;
929     data[16] = (strlen (s)) & 0xff;
930     memcpy (&data[17], s, strlen (s));
931     script_tag = gst_buffer_join (script_tag, tmp);
932
933     g_free (s);
934     tags_written++;
935   }
936
937 end:
938
939   if (!tags_written) {
940     gst_buffer_unref (script_tag);
941     script_tag = NULL;
942     goto exit;
943   }
944
945   tmp = gst_buffer_new_and_alloc (2 + 0 + 1);
946   data = GST_BUFFER_DATA (tmp);
947   data[0] = 0;                  /* 0 byte size */
948   data[1] = 0;
949   data[2] = 9;                  /* end marker */
950   script_tag = gst_buffer_join (script_tag, tmp);
951   tags_written++;
952
953   tmp = gst_buffer_new_and_alloc (4);
954   data = GST_BUFFER_DATA (tmp);
955   GST_WRITE_UINT32_BE (data, GST_BUFFER_SIZE (script_tag));
956   script_tag = gst_buffer_join (script_tag, tmp);
957
958   data = GST_BUFFER_DATA (script_tag);
959   data[1] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 16) & 0xff;
960   data[2] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 8) & 0xff;
961   data[3] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 0) & 0xff;
962
963   GST_WRITE_UINT32_BE (data + 11 + 13 + 1, tags_written);
964
965 exit:
966   return script_tag;
967 }
968
969 static GstBuffer *
970 gst_flv_mux_buffer_to_tag_internal (GstFlvMux * mux, GstBuffer * buffer,
971     GstFlvPad * cpad, gboolean is_codec_data)
972 {
973   GstBuffer *tag;
974   guint8 *data;
975   guint size;
976   guint32 timestamp =
977       (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) ? GST_BUFFER_TIMESTAMP (buffer) /
978       GST_MSECOND : cpad->last_timestamp / GST_MSECOND;
979
980   size = 11;
981   if (cpad->video) {
982     size += 1;
983     if (cpad->video_codec == 7)
984       size += 4 + GST_BUFFER_SIZE (buffer);
985     else
986       size += GST_BUFFER_SIZE (buffer);
987   } else {
988     size += 1;
989     if (cpad->audio_codec == 10)
990       size += 1 + GST_BUFFER_SIZE (buffer);
991     else
992       size += GST_BUFFER_SIZE (buffer);
993   }
994   size += 4;
995
996   tag = gst_buffer_new_and_alloc (size);
997   GST_BUFFER_TIMESTAMP (tag) = timestamp * GST_MSECOND;
998   data = GST_BUFFER_DATA (tag);
999   memset (data, 0, size);
1000
1001   data[0] = (cpad->video) ? 9 : 8;
1002
1003   data[1] = ((size - 11 - 4) >> 16) & 0xff;
1004   data[2] = ((size - 11 - 4) >> 8) & 0xff;
1005   data[3] = ((size - 11 - 4) >> 0) & 0xff;
1006
1007   /* wrap the timestamp every G_MAXINT32 miliseconds */
1008   timestamp &= 0x7fffffff;
1009   data[4] = (timestamp >> 16) & 0xff;
1010   data[5] = (timestamp >> 8) & 0xff;
1011   data[6] = (timestamp >> 0) & 0xff;
1012   data[7] = (timestamp >> 24) & 0xff;
1013
1014   data[8] = data[9] = data[10] = 0;
1015
1016   if (cpad->video) {
1017     if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
1018       data[11] |= 2 << 4;
1019     else
1020       data[11] |= 1 << 4;
1021
1022     data[11] |= cpad->video_codec & 0x0f;
1023
1024     if (cpad->video_codec == 7) {
1025       data[12] = is_codec_data ? 0 : 1;
1026
1027       /* FIXME: what to do about composition time */
1028       data[13] = data[14] = data[15] = 0;
1029
1030       memcpy (data + 11 + 1 + 4, GST_BUFFER_DATA (buffer),
1031           GST_BUFFER_SIZE (buffer));
1032     } else {
1033       memcpy (data + 11 + 1, GST_BUFFER_DATA (buffer),
1034           GST_BUFFER_SIZE (buffer));
1035     }
1036   } else {
1037     data[11] |= (cpad->audio_codec << 4) & 0xf0;
1038     data[11] |= (cpad->rate << 2) & 0x0c;
1039     data[11] |= (cpad->width << 1) & 0x02;
1040     data[11] |= (cpad->channels << 0) & 0x01;
1041
1042     if (cpad->audio_codec == 10) {
1043       data[12] = is_codec_data ? 0 : 1;
1044
1045       memcpy (data + 11 + 1 + 1, GST_BUFFER_DATA (buffer),
1046           GST_BUFFER_SIZE (buffer));
1047     } else {
1048       memcpy (data + 11 + 1, GST_BUFFER_DATA (buffer),
1049           GST_BUFFER_SIZE (buffer));
1050     }
1051   }
1052
1053   GST_WRITE_UINT32_BE (data + size - 4, size - 4);
1054
1055   gst_buffer_copy_metadata (tag, buffer, GST_BUFFER_COPY_TIMESTAMPS);
1056   /* mark the buffer if it's an audio buffer and there's also video being muxed
1057    * or it's a video interframe */
1058   if ((mux->have_video && !cpad->video) ||
1059       GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
1060     GST_BUFFER_FLAG_SET (tag, GST_BUFFER_FLAG_DELTA_UNIT);
1061
1062   GST_BUFFER_OFFSET (tag) = GST_BUFFER_OFFSET_END (tag) =
1063       GST_BUFFER_OFFSET_NONE;
1064
1065   return tag;
1066 }
1067
1068 static inline GstBuffer *
1069 gst_flv_mux_buffer_to_tag (GstFlvMux * mux, GstBuffer * buffer,
1070     GstFlvPad * cpad)
1071 {
1072   return gst_flv_mux_buffer_to_tag_internal (mux, buffer, cpad, FALSE);
1073 }
1074
1075 static inline GstBuffer *
1076 gst_flv_mux_codec_data_buffer_to_tag (GstFlvMux * mux, GstBuffer * buffer,
1077     GstFlvPad * cpad)
1078 {
1079   return gst_flv_mux_buffer_to_tag_internal (mux, buffer, cpad, TRUE);
1080 }
1081
1082 static void
1083 gst_flv_mux_put_buffer_in_streamheader (GValue * streamheader,
1084     GstBuffer * buffer)
1085 {
1086   GValue value = { 0 };
1087   GstBuffer *buf;
1088
1089   g_value_init (&value, GST_TYPE_BUFFER);
1090   buf = gst_buffer_copy (buffer);
1091   gst_value_set_buffer (&value, buf);
1092   gst_buffer_unref (buf);
1093   gst_value_array_append_value (streamheader, &value);
1094   g_value_unset (&value);
1095 }
1096
1097 static GstFlowReturn
1098 gst_flv_mux_write_header (GstFlvMux * mux)
1099 {
1100   GstBuffer *header, *metadata;
1101   GstBuffer *video_codec_data, *audio_codec_data;
1102   GstCaps *caps;
1103   GstStructure *structure;
1104   GValue streamheader = { 0 };
1105   GSList *l;
1106   GstFlowReturn ret;
1107
1108   header = gst_flv_mux_create_header (mux);
1109   metadata = gst_flv_mux_create_metadata (mux, TRUE);
1110   video_codec_data = NULL;
1111   audio_codec_data = NULL;
1112
1113   for (l = mux->collect->data; l != NULL; l = l->next) {
1114     GstFlvPad *cpad = l->data;
1115
1116     /* Get H.264 and AAC codec data, if present */
1117     if (cpad && cpad->video && cpad->video_codec == 7) {
1118       if (cpad->video_codec_data == NULL)
1119         GST_WARNING_OBJECT (mux, "Codec data for video stream not found, "
1120             "output might not be playable");
1121       else
1122         video_codec_data =
1123             gst_flv_mux_codec_data_buffer_to_tag (mux, cpad->video_codec_data,
1124             cpad);
1125     } else if (cpad && !cpad->video && cpad->audio_codec == 10) {
1126       if (cpad->audio_codec_data == NULL)
1127         GST_WARNING_OBJECT (mux, "Codec data for audio stream not found, "
1128             "output might not be playable");
1129       else
1130         audio_codec_data =
1131             gst_flv_mux_codec_data_buffer_to_tag (mux, cpad->audio_codec_data,
1132             cpad);
1133     }
1134   }
1135
1136   /* mark buffers that will go in the streamheader */
1137   GST_BUFFER_FLAG_SET (header, GST_BUFFER_FLAG_IN_CAPS);
1138   GST_BUFFER_FLAG_SET (metadata, GST_BUFFER_FLAG_IN_CAPS);
1139   if (video_codec_data != NULL) {
1140     GST_BUFFER_FLAG_SET (video_codec_data, GST_BUFFER_FLAG_IN_CAPS);
1141     /* mark as a delta unit, so downstream will not try to synchronize on that
1142      * buffer - to actually start playback you need a real video keyframe */
1143     GST_BUFFER_FLAG_SET (video_codec_data, GST_BUFFER_FLAG_DELTA_UNIT);
1144   }
1145   if (audio_codec_data != NULL) {
1146     GST_BUFFER_FLAG_SET (audio_codec_data, GST_BUFFER_FLAG_IN_CAPS);
1147   }
1148
1149   /* put buffers in streamheader */
1150   g_value_init (&streamheader, GST_TYPE_ARRAY);
1151   gst_flv_mux_put_buffer_in_streamheader (&streamheader, header);
1152   gst_flv_mux_put_buffer_in_streamheader (&streamheader, metadata);
1153   if (video_codec_data != NULL)
1154     gst_flv_mux_put_buffer_in_streamheader (&streamheader, video_codec_data);
1155   if (audio_codec_data != NULL)
1156     gst_flv_mux_put_buffer_in_streamheader (&streamheader, audio_codec_data);
1157
1158   /* create the caps and put the streamheader in them */
1159   caps = gst_caps_new_simple ("video/x-flv", NULL);
1160   caps = gst_caps_make_writable (caps);
1161   structure = gst_caps_get_structure (caps, 0);
1162   gst_structure_set_value (structure, "streamheader", &streamheader);
1163   g_value_unset (&streamheader);
1164
1165   if (GST_PAD_CAPS (mux->srcpad) == NULL)
1166     gst_pad_set_caps (mux->srcpad, caps);
1167
1168   gst_caps_unref (caps);
1169
1170   /* push the header buffer, the metadata and the codec info, if any */
1171   ret = gst_flv_mux_push (mux, header);
1172   if (ret != GST_FLOW_OK)
1173     return ret;
1174   ret = gst_flv_mux_push (mux, metadata);
1175   if (ret != GST_FLOW_OK)
1176     return ret;
1177   if (video_codec_data != NULL) {
1178     ret = gst_flv_mux_push (mux, video_codec_data);
1179     if (ret != GST_FLOW_OK)
1180       return ret;
1181   }
1182   if (audio_codec_data != NULL) {
1183     ret = gst_flv_mux_push (mux, audio_codec_data);
1184     if (ret != GST_FLOW_OK)
1185       return ret;
1186   }
1187   return GST_FLOW_OK;
1188 }
1189
1190 static void
1191 gst_flv_mux_update_index (GstFlvMux * mux, GstBuffer * buffer, GstFlvPad * cpad)
1192 {
1193   /*
1194    * Add the tag byte offset and to the index if it's a valid seek point, which
1195    * means it's either a video keyframe or if there is no video pad (in that
1196    * case every FLV tag is a valid seek point)
1197    */
1198   if (mux->have_video &&
1199       (!cpad->video ||
1200           GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)))
1201     return;
1202
1203   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1204     GstFlvMuxIndexEntry *entry = g_slice_new (GstFlvMuxIndexEntry);
1205     entry->position = mux->byte_count;
1206     entry->time =
1207         gst_guint64_to_gdouble (GST_BUFFER_TIMESTAMP (buffer)) / GST_SECOND;
1208     mux->index = g_list_prepend (mux->index, entry);
1209   }
1210 }
1211
1212 static GstFlowReturn
1213 gst_flv_mux_write_buffer (GstFlvMux * mux, GstFlvPad * cpad, GstBuffer * buffer)
1214 {
1215   GstBuffer *tag;
1216   GstFlowReturn ret;
1217
1218   /* clipping function arranged for running_time */
1219
1220   if (!mux->streamable)
1221     gst_flv_mux_update_index (mux, buffer, cpad);
1222
1223   tag = gst_flv_mux_buffer_to_tag (mux, buffer, cpad);
1224
1225   gst_buffer_unref (buffer);
1226
1227   ret = gst_flv_mux_push (mux, tag);
1228
1229   if (ret == GST_FLOW_OK && GST_BUFFER_TIMESTAMP_IS_VALID (tag))
1230     cpad->last_timestamp = GST_BUFFER_TIMESTAMP (tag);
1231
1232   return ret;
1233 }
1234
1235 static guint64
1236 gst_flv_mux_determine_duration (GstFlvMux * mux)
1237 {
1238   GSList *l;
1239   GstClockTime duration = GST_CLOCK_TIME_NONE;
1240
1241   GST_DEBUG_OBJECT (mux, "trying to determine the duration "
1242       "from pad timestamps");
1243
1244   for (l = mux->collect->data; l != NULL; l = l->next) {
1245     GstFlvPad *cpad = l->data;
1246
1247     if (cpad && (cpad->last_timestamp != GST_CLOCK_TIME_NONE)) {
1248       if (duration == GST_CLOCK_TIME_NONE)
1249         duration = cpad->last_timestamp;
1250       else
1251         duration = MAX (duration, cpad->last_timestamp);
1252     }
1253   }
1254
1255   return duration;
1256 }
1257
1258 static GstFlowReturn
1259 gst_flv_mux_rewrite_header (GstFlvMux * mux)
1260 {
1261   GstBuffer *rewrite, *index, *tmp;
1262   GstEvent *event;
1263   guint8 *data;
1264   gdouble d;
1265   GList *l;
1266   guint32 index_len, allocate_size;
1267   guint32 i, index_skip;
1268   GstClockTime dur;
1269
1270   if (mux->streamable)
1271     return GST_FLOW_OK;
1272
1273   /* seek back to the preallocated index space */
1274   event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1275       13 + 29, GST_CLOCK_TIME_NONE, 13 + 29);
1276   if (!gst_pad_push_event (mux->srcpad, event)) {
1277     GST_WARNING_OBJECT (mux, "Seek to rewrite header failed");
1278     return GST_FLOW_OK;
1279   }
1280
1281   /* determine duration now based on our own timestamping,
1282    * so that it is likely many times better and consistent
1283    * than whatever obtained by some query */
1284   dur = gst_flv_mux_determine_duration (mux);
1285   if (dur != GST_CLOCK_TIME_NONE)
1286     mux->duration = dur;
1287
1288   /* rewrite the duration tag */
1289   d = gst_guint64_to_gdouble (mux->duration);
1290   d /= (gdouble) GST_SECOND;
1291
1292   GST_DEBUG_OBJECT (mux, "determined the final duration to be %f", d);
1293
1294   rewrite = gst_flv_mux_create_number_script_value ("duration", d);
1295
1296   /* rewrite the filesize tag */
1297   d = gst_guint64_to_gdouble (mux->byte_count);
1298
1299   GST_DEBUG_OBJECT (mux, "putting total filesize %f in the metadata", d);
1300
1301   tmp = gst_flv_mux_create_number_script_value ("filesize", d);
1302   rewrite = gst_buffer_join (rewrite, tmp);
1303
1304   if (!mux->index) {
1305     /* no index, so push buffer and return */
1306     return gst_flv_mux_push (mux, rewrite);
1307   }
1308
1309   /* rewrite the index */
1310   mux->index = g_list_reverse (mux->index);
1311   index_len = g_list_length (mux->index);
1312
1313   /* We write at most MAX_INDEX_ENTRIES elements */
1314   if (index_len > MAX_INDEX_ENTRIES) {
1315     index_skip = 1 + index_len / MAX_INDEX_ENTRIES;
1316     index_len = (index_len + index_skip - 1) / index_skip;
1317   } else {
1318     index_skip = 1;
1319   }
1320
1321   GST_DEBUG_OBJECT (mux, "Index length is %d", index_len);
1322   /* see size calculation in gst_flv_mux_preallocate_index */
1323   allocate_size = 11 + 8 + 22 + 10 + index_len * 18;
1324   GST_DEBUG_OBJECT (mux, "Allocating %d bytes for index", allocate_size);
1325   index = gst_buffer_new_and_alloc (allocate_size);
1326   data = GST_BUFFER_DATA (index);
1327
1328   GST_WRITE_UINT16_BE (data, 9);        /* the 'keyframes' key */
1329   memcpy (data + 2, "keyframes", 9);
1330   GST_WRITE_UINT8 (data + 11, 8);       /* nested ECMA array */
1331   GST_WRITE_UINT32_BE (data + 12, 2);   /* two elements */
1332   GST_WRITE_UINT16_BE (data + 16, 5);   /* first string key: 'times' */
1333   memcpy (data + 18, "times", 5);
1334   GST_WRITE_UINT8 (data + 23, 10);      /* strict array */
1335   GST_WRITE_UINT32_BE (data + 24, index_len);
1336   data += 28;
1337
1338   /* the keyframes' times */
1339   for (i = 0, l = mux->index; l; l = l->next, i++) {
1340     GstFlvMuxIndexEntry *entry = l->data;
1341
1342     if (i % index_skip != 0)
1343       continue;
1344     GST_WRITE_UINT8 (data, 0);  /* numeric (aka double) */
1345     GST_WRITE_DOUBLE_BE (data + 1, entry->time);
1346     data += 9;
1347   }
1348
1349   GST_WRITE_UINT16_BE (data, 13);       /* second string key: 'filepositions' */
1350   memcpy (data + 2, "filepositions", 13);
1351   GST_WRITE_UINT8 (data + 15, 10);      /* strict array */
1352   GST_WRITE_UINT32_BE (data + 16, index_len);
1353   data += 20;
1354
1355   /* the keyframes' file positions */
1356   for (i = 0, l = mux->index; l; l = l->next, i++) {
1357     GstFlvMuxIndexEntry *entry = l->data;
1358
1359     if (i % index_skip != 0)
1360       continue;
1361     GST_WRITE_UINT8 (data, 0);
1362     GST_WRITE_DOUBLE_BE (data + 1, entry->position);
1363     data += 9;
1364   }
1365
1366   GST_WRITE_UINT24_BE (data, 9);        /* finish the ECMA array */
1367
1368   /* If there is space left in the prefilled area, reinsert the filler.
1369      There is at least 18  bytes free, so it will always fit. */
1370   if (index_len < MAX_INDEX_ENTRIES) {
1371     GstBuffer *tmp;
1372     guint8 *data;
1373     guint32 remaining_filler_size;
1374
1375     tmp = gst_buffer_new_and_alloc (14);
1376     data = GST_BUFFER_DATA (tmp);
1377     GST_WRITE_UINT16_BE (data, 9);
1378     memcpy (data + 2, "gstfiller", 9);
1379     GST_WRITE_UINT8 (data + 11, 2);     /* string */
1380
1381     /* There is 18 bytes per remaining index entry minus what is used for
1382      * the'gstfiller' key. The rest is already filled with spaces, so just need
1383      * to update length. */
1384     remaining_filler_size = (MAX_INDEX_ENTRIES - index_len) * 18 - 14;
1385     GST_DEBUG_OBJECT (mux, "Remaining filler size is %d bytes",
1386         remaining_filler_size);
1387     GST_WRITE_UINT16_BE (data + 12, remaining_filler_size);
1388     index = gst_buffer_join (index, tmp);
1389   }
1390
1391   rewrite = gst_buffer_join (rewrite, index);
1392
1393   gst_buffer_set_caps (rewrite, GST_PAD_CAPS (mux->srcpad));
1394   return gst_flv_mux_push (mux, rewrite);
1395 }
1396
1397 static GstFlowReturn
1398 gst_flv_mux_handle_buffer (GstCollectPads2 * pads, GstCollectData2 * cdata,
1399     GstBuffer * buffer, gpointer user_data)
1400 {
1401   GstFlvMux *mux = GST_FLV_MUX (user_data);
1402   GstFlvPad *best;
1403   GstClockTime best_time;
1404   GstFlowReturn ret;
1405
1406   if (mux->state == GST_FLV_MUX_STATE_HEADER) {
1407     if (mux->collect->data == NULL) {
1408       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1409           ("No input streams configured"));
1410       return GST_FLOW_ERROR;
1411     }
1412
1413     if (gst_pad_push_event (mux->srcpad,
1414             gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES, 0, -1, 0)))
1415       ret = gst_flv_mux_write_header (mux);
1416     else
1417       ret = GST_FLOW_ERROR;
1418
1419     if (ret != GST_FLOW_OK)
1420       return ret;
1421     mux->state = GST_FLV_MUX_STATE_DATA;
1422   }
1423
1424   if (mux->new_tags) {
1425     GstBuffer *buf = gst_flv_mux_create_metadata (mux, FALSE);
1426     if (buf)
1427       gst_flv_mux_push (mux, buf);
1428     mux->new_tags = FALSE;
1429   }
1430
1431   best = (GstFlvPad *) cdata;
1432   if (best) {
1433     g_assert (buffer);
1434     best_time = GST_BUFFER_TIMESTAMP (buffer);
1435   } else {
1436     best_time = GST_CLOCK_TIME_NONE;
1437   }
1438
1439   /* The FLV timestamp is an int32 field. For non-live streams error out if a
1440      bigger timestamp is seen, for live the timestamp will get wrapped in
1441      gst_flv_mux_buffer_to_tag */
1442   if (!mux->streamable && GST_CLOCK_TIME_IS_VALID (best_time)
1443       && best_time / GST_MSECOND > G_MAXINT32) {
1444     GST_WARNING_OBJECT (mux, "Timestamp larger than FLV supports - EOS");
1445     gst_buffer_unref (buffer);
1446     buffer = NULL;
1447     best = NULL;
1448   }
1449
1450   if (best) {
1451     return gst_flv_mux_write_buffer (mux, best, buffer);
1452   } else {
1453     gst_flv_mux_rewrite_header (mux);
1454     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
1455     return GST_FLOW_UNEXPECTED;
1456   }
1457 }
1458
1459 static void
1460 gst_flv_mux_get_property (GObject * object,
1461     guint prop_id, GValue * value, GParamSpec * pspec)
1462 {
1463   GstFlvMux *mux = GST_FLV_MUX (object);
1464
1465   switch (prop_id) {
1466     case PROP_STREAMABLE:
1467       g_value_set_boolean (value, mux->streamable);
1468       break;
1469     default:
1470       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1471       break;
1472   }
1473 }
1474
1475 static void
1476 gst_flv_mux_set_property (GObject * object,
1477     guint prop_id, const GValue * value, GParamSpec * pspec)
1478 {
1479   GstFlvMux *mux = GST_FLV_MUX (object);
1480
1481   switch (prop_id) {
1482     case PROP_STREAMABLE:
1483       mux->streamable = g_value_get_boolean (value);
1484       if (mux->streamable)
1485         gst_tag_setter_set_tag_merge_mode (GST_TAG_SETTER (mux),
1486             GST_TAG_MERGE_REPLACE);
1487       else
1488         gst_tag_setter_set_tag_merge_mode (GST_TAG_SETTER (mux),
1489             GST_TAG_MERGE_KEEP);
1490       break;
1491     default:
1492       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1493       break;
1494   }
1495 }
1496
1497 static GstStateChangeReturn
1498 gst_flv_mux_change_state (GstElement * element, GstStateChange transition)
1499 {
1500   GstStateChangeReturn ret;
1501   GstFlvMux *mux = GST_FLV_MUX (element);
1502
1503   switch (transition) {
1504     case GST_STATE_CHANGE_NULL_TO_READY:
1505       break;
1506     case GST_STATE_CHANGE_READY_TO_PAUSED:
1507       gst_collect_pads2_start (mux->collect);
1508       break;
1509     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1510       break;
1511     case GST_STATE_CHANGE_PAUSED_TO_READY:
1512       gst_collect_pads2_stop (mux->collect);
1513       break;
1514     default:
1515       break;
1516   }
1517
1518   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1519
1520   switch (transition) {
1521     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1522       break;
1523     case GST_STATE_CHANGE_PAUSED_TO_READY:
1524       gst_flv_mux_reset (GST_ELEMENT (mux));
1525       break;
1526     case GST_STATE_CHANGE_READY_TO_NULL:
1527       break;
1528     default:
1529       break;
1530   }
1531
1532   return ret;
1533 }