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