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