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