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