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