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