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