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