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