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