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