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