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