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