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