flvmux: Get the max duration from upstream if there's no duration tag
[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 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
47     GST_PAD_SRC,
48     GST_PAD_ALWAYS,
49     GST_STATIC_CAPS ("video/x-flv")
50     );
51
52 static GstStaticPadTemplate videosink_templ = GST_STATIC_PAD_TEMPLATE ("video",
53     GST_PAD_SINK,
54     GST_PAD_REQUEST,
55     GST_STATIC_CAPS ("video/x-flash-video; "
56         "video/x-flash-screen; "
57         "video/x-vp6-flash; " "video/x-vp6-alpha; " "video/x-h264;")
58     );
59
60 static GstStaticPadTemplate audiosink_templ = GST_STATIC_PAD_TEMPLATE ("audio",
61     GST_PAD_SINK,
62     GST_PAD_REQUEST,
63     GST_STATIC_CAPS
64     ("audio/x-adpcm, layout = (string) swf, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
65         "audio/mpeg, mpegversion = (int) 1, layer = (int) 3, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 22050, 44100 }, parsed = (boolean) TRUE; "
66         "audio/mpeg, mpegversion = (int) 4, framed = (boolean) TRUE; "
67         "audio/x-nellymoser, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 16000, 22050, 44100 }; "
68         "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; "
69         "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; "
70         "audio/x-alaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
71         "audio/x-mulaw, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
72         "audio/x-speex, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 };")
73     );
74
75 #define _do_init(type)                                                          \
76   G_STMT_START{                                                                 \
77     static const GInterfaceInfo tag_setter_info = {                             \
78       NULL,                                                                     \
79       NULL,                                                                     \
80       NULL                                                                      \
81     };                                                                          \
82     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER,                     \
83                                  &tag_setter_info);                             \
84   }G_STMT_END
85
86 GST_BOILERPLATE_FULL (GstFlvMux, gst_flv_mux, GstElement, GST_TYPE_ELEMENT,
87     _do_init);
88
89 static void gst_flv_mux_finalize (GObject * object);
90 static GstFlowReturn
91 gst_flv_mux_collected (GstCollectPads * pads, gpointer user_data);
92
93 static gboolean gst_flv_mux_handle_src_event (GstPad * pad, GstEvent * event);
94 static GstPad *gst_flv_mux_request_new_pad (GstElement * element,
95     GstPadTemplate * templ, const gchar * name);
96 static void gst_flv_mux_release_pad (GstElement * element, GstPad * pad);
97
98 static GstStateChangeReturn
99 gst_flv_mux_change_state (GstElement * element, GstStateChange transition);
100
101 static void gst_flv_mux_reset (GstElement * element);
102
103 typedef struct
104 {
105   gdouble position;
106   gdouble time;
107 } GstFlvMuxIndexEntry;
108
109 static void
110 gst_flv_mux_index_entry_free (GstFlvMuxIndexEntry * entry)
111 {
112   g_slice_free (GstFlvMuxIndexEntry, entry);
113 }
114
115 static void
116 gst_flv_mux_base_init (gpointer g_class)
117 {
118   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
119
120   gst_element_class_add_pad_template (element_class,
121       gst_static_pad_template_get (&videosink_templ));
122   gst_element_class_add_pad_template (element_class,
123       gst_static_pad_template_get (&audiosink_templ));
124   gst_element_class_add_pad_template (element_class,
125       gst_static_pad_template_get (&src_templ));
126   gst_element_class_set_details_simple (element_class, "FLV muxer",
127       "Codec/Muxer",
128       "Muxes video/audio streams into a FLV stream",
129       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
130
131   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
132 }
133
134 static void
135 gst_flv_mux_class_init (GstFlvMuxClass * klass)
136 {
137   GObjectClass *gobject_class;
138   GstElementClass *gstelement_class;
139
140   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
141
142   gobject_class = (GObjectClass *) klass;
143   gstelement_class = (GstElementClass *) klass;
144
145   gobject_class->finalize = gst_flv_mux_finalize;
146
147   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_flv_mux_change_state);
148   gstelement_class->request_new_pad =
149       GST_DEBUG_FUNCPTR (gst_flv_mux_request_new_pad);
150   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_flv_mux_release_pad);
151 }
152
153 static void
154 gst_flv_mux_init (GstFlvMux * mux, GstFlvMuxClass * g_class)
155 {
156   mux->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
157   gst_pad_set_event_function (mux->srcpad, gst_flv_mux_handle_src_event);
158   gst_element_add_pad (GST_ELEMENT (mux), mux->srcpad);
159
160   mux->collect = gst_collect_pads_new ();
161   gst_collect_pads_set_function (mux->collect,
162       (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_flv_mux_collected), mux);
163
164   gst_flv_mux_reset (GST_ELEMENT (mux));
165 }
166
167 static void
168 gst_flv_mux_finalize (GObject * object)
169 {
170   GstFlvMux *mux = GST_FLV_MUX (object);
171
172   gst_object_unref (mux->collect);
173
174   G_OBJECT_CLASS (parent_class)->finalize (object);
175 }
176
177 static void
178 gst_flv_mux_reset (GstElement * element)
179 {
180   GstFlvMux *mux = GST_FLV_MUX (element);
181   GSList *sl;
182
183   while ((sl = mux->collect->data) != NULL) {
184     GstFlvPad *cpad = (GstFlvPad *) sl->data;
185
186     if (cpad->audio_codec_data)
187       gst_buffer_unref (cpad->audio_codec_data);
188     if (cpad->video_codec_data)
189       gst_buffer_unref (cpad->video_codec_data);
190
191     gst_collect_pads_remove_pad (mux->collect, cpad->collect.pad);
192   }
193
194   if (mux->tags)
195     gst_tag_list_free (mux->tags);
196   mux->tags = NULL;
197
198   g_list_foreach (mux->index, (GFunc) gst_flv_mux_index_entry_free, NULL);
199   g_list_free (mux->index);
200   mux->index = NULL;
201   mux->byte_count = 0;
202
203   mux->state = GST_FLV_MUX_STATE_HEADER;
204 }
205
206 static gboolean
207 gst_flv_mux_handle_src_event (GstPad * pad, GstEvent * event)
208 {
209   GstEventType type;
210
211   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
212
213   switch (type) {
214     case GST_EVENT_SEEK:
215       /* disable seeking for now */
216       return FALSE;
217     default:
218       break;
219   }
220
221   return gst_pad_event_default (pad, event);
222 }
223
224 static gboolean
225 gst_flv_mux_handle_sink_event (GstPad * pad, GstEvent * event)
226 {
227   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
228   gboolean ret = TRUE;
229
230   switch (GST_EVENT_TYPE (event)) {
231     case GST_EVENT_TAG:{
232       GstTagList *tags;
233
234       if (!mux->tags)
235         mux->tags = gst_tag_list_new ();
236
237       gst_event_parse_tag (event, &tags);
238       if (tags) {
239         gst_tag_list_insert (mux->tags, tags,
240             gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (mux)));
241       }
242
243       break;
244     }
245     case GST_EVENT_NEWSEGMENT:
246       /* We don't support NEWSEGMENT events */
247       ret = FALSE;
248       gst_event_unref (event);
249       break;
250     default:
251       break;
252   }
253
254   /* now GstCollectPads can take care of the rest, e.g. EOS */
255   if (ret)
256     ret = mux->collect_event (pad, event);
257   gst_object_unref (mux);
258
259   return ret;
260 }
261
262 static gboolean
263 gst_flv_mux_video_pad_setcaps (GstPad * pad, GstCaps * caps)
264 {
265   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
266   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
267   gboolean ret = TRUE;
268   GstStructure *s;
269
270   s = gst_caps_get_structure (caps, 0);
271
272   if (strcmp (gst_structure_get_name (s), "video/x-flash-video") == 0) {
273     cpad->video_codec = 2;
274   } else if (strcmp (gst_structure_get_name (s), "video/x-flash-screen") == 0) {
275     cpad->video_codec = 3;
276   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-flash") == 0) {
277     cpad->video_codec = 4;
278   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-alpha") == 0) {
279     cpad->video_codec = 5;
280   } else if (strcmp (gst_structure_get_name (s), "video/x-h264") == 0) {
281     cpad->video_codec = 7;
282   } else {
283     ret = FALSE;
284   }
285
286   if (ret && gst_structure_has_field (s, "codec_data")) {
287     const GValue *val = gst_structure_get_value (s, "codec_data");
288
289     if (val) {
290       cpad->video_codec_data = gst_buffer_ref (gst_value_get_buffer (val));
291       cpad->sent_codec_data = FALSE;
292     } else {
293       cpad->sent_codec_data = TRUE;
294     }
295   } else {
296     cpad->sent_codec_data = TRUE;
297   }
298
299   gst_object_unref (mux);
300
301   return ret;
302 }
303
304 static gboolean
305 gst_flv_mux_audio_pad_setcaps (GstPad * pad, GstCaps * caps)
306 {
307   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
308   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
309   gboolean ret = TRUE;
310   GstStructure *s;
311
312   s = gst_caps_get_structure (caps, 0);
313
314   if (strcmp (gst_structure_get_name (s), "audio/x-adpcm") == 0) {
315     const gchar *layout = gst_structure_get_string (s, "layout");
316     if (layout && strcmp (layout, "swf") == 0) {
317       cpad->audio_codec = 1;
318     } else {
319       ret = FALSE;
320     }
321   } else if (strcmp (gst_structure_get_name (s), "audio/mpeg") == 0) {
322     gint mpegversion;
323
324     if (gst_structure_get_int (s, "mpegversion", &mpegversion)) {
325       if (mpegversion == 1) {
326         gint layer;
327
328         if (gst_structure_get_int (s, "layer", &layer) && layer == 3) {
329           gint rate;
330
331           if (gst_structure_get_int (s, "rate", &rate) && rate == 8000)
332             cpad->audio_codec = 14;
333           else
334             cpad->audio_codec = 2;
335         } else {
336           ret = FALSE;
337         }
338       } else if (mpegversion == 4) {
339         cpad->audio_codec = 10;
340       } else {
341         ret = FALSE;
342       }
343     } else {
344       ret = FALSE;
345     }
346   } else if (strcmp (gst_structure_get_name (s), "audio/x-nellymoser") == 0) {
347     gint rate, channels;
348
349     if (gst_structure_get_int (s, "rate", &rate)
350         && gst_structure_get_int (s, "channels", &channels)) {
351       if (channels == 1 && rate == 16000)
352         cpad->audio_codec = 4;
353       else if (channels == 1 && rate == 8000)
354         cpad->audio_codec = 5;
355     } else {
356       cpad->audio_codec = 6;
357     }
358   } else if (strcmp (gst_structure_get_name (s), "audio/x-raw-int") == 0) {
359     gint endianness;
360
361     if (gst_structure_get_int (s, "endianness", &endianness)
362         && endianness == G_LITTLE_ENDIAN)
363       cpad->audio_codec = 3;
364     else
365       ret = FALSE;
366   } else if (strcmp (gst_structure_get_name (s), "audio/x-alaw") == 0) {
367     cpad->audio_codec = 7;
368   } else if (strcmp (gst_structure_get_name (s), "audio/x-mulaw") == 0) {
369     cpad->audio_codec = 8;
370   } else if (strcmp (gst_structure_get_name (s), "audio/x-speex") == 0) {
371     cpad->audio_codec = 11;
372   } else {
373     ret = FALSE;
374   }
375
376   if (ret) {
377     gint rate, channels, width;
378
379     if (gst_structure_get_int (s, "rate", &rate)) {
380       if (cpad->audio_codec == 10)
381         cpad->rate = 3;
382       else if (rate == 5512)
383         cpad->rate = 0;
384       else if (rate == 11025)
385         cpad->rate = 1;
386       else if (rate == 22050)
387         cpad->rate = 2;
388       else if (rate == 44100)
389         cpad->rate = 3;
390       else if (rate == 8000 && (cpad->audio_codec == 5
391               || cpad->audio_codec == 14))
392         cpad->rate = 0;
393       else if (rate == 16000 && cpad->audio_codec == 4)
394         cpad->rate = 0;
395       else
396         ret = FALSE;
397     } else if (cpad->audio_codec == 10) {
398       cpad->rate = 3;
399     } else {
400       ret = FALSE;
401     }
402
403     if (gst_structure_get_int (s, "channels", &channels)) {
404       if (cpad->audio_codec == 4 || cpad->audio_codec == 5
405           || cpad->audio_codec == 6)
406         cpad->channels = 0;
407       else if (cpad->audio_codec == 10)
408         cpad->channels = 1;
409       else if (channels == 1)
410         cpad->channels = 0;
411       else if (channels == 2)
412         cpad->channels = 1;
413       else
414         ret = FALSE;
415     } else if (cpad->audio_codec == 4 || cpad->audio_codec == 5
416         || cpad->audio_codec == 6) {
417       cpad->channels = 0;
418     } else if (cpad->audio_codec == 10) {
419       cpad->channels = 1;
420     } else {
421       ret = FALSE;
422     }
423
424     if (gst_structure_get_int (s, "width", &width)) {
425       if (cpad->audio_codec != 3)
426         cpad->width = 1;
427       else if (width == 8)
428         cpad->width = 0;
429       else if (width == 16)
430         cpad->width = 1;
431       else
432         ret = FALSE;
433     } else if (cpad->audio_codec != 3) {
434       cpad->width = 1;
435     } else {
436       ret = FALSE;
437     }
438   }
439
440   if (ret && gst_structure_has_field (s, "codec_data")) {
441     const GValue *val = gst_structure_get_value (s, "codec_data");
442
443     if (val) {
444       cpad->audio_codec_data = gst_buffer_ref (gst_value_get_buffer (val));
445       cpad->sent_codec_data = FALSE;
446     } else {
447       cpad->sent_codec_data = TRUE;
448     }
449   } else {
450     cpad->sent_codec_data = TRUE;
451   }
452
453   gst_object_unref (mux);
454
455   return ret;
456 }
457
458 static GstPad *
459 gst_flv_mux_request_new_pad (GstElement * element,
460     GstPadTemplate * templ, const gchar * pad_name)
461 {
462   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
463   GstFlvMux *mux = GST_FLV_MUX (element);
464   GstFlvPad *cpad;
465   GstPad *pad = NULL;
466   const gchar *name = NULL;
467   GstPadSetCapsFunction setcapsfunc = NULL;
468   gboolean video;
469
470   if (mux->state != GST_FLV_MUX_STATE_HEADER) {
471     GST_WARNING_OBJECT (mux, "Can't request pads after writing header");
472     return NULL;
473   }
474
475   if (templ == gst_element_class_get_pad_template (klass, "audio")) {
476     if (mux->have_audio) {
477       GST_WARNING_OBJECT (mux, "Already have an audio pad");
478       return NULL;
479     }
480     mux->have_audio = TRUE;
481     name = "audio";
482     video = FALSE;
483     setcapsfunc = GST_DEBUG_FUNCPTR (gst_flv_mux_audio_pad_setcaps);
484   } else if (templ == gst_element_class_get_pad_template (klass, "video")) {
485     if (mux->have_video) {
486       GST_WARNING_OBJECT (mux, "Already have a video pad");
487       return NULL;
488     }
489     mux->have_video = TRUE;
490     name = "video";
491     video = TRUE;
492     setcapsfunc = GST_DEBUG_FUNCPTR (gst_flv_mux_video_pad_setcaps);
493   } else {
494     GST_WARNING_OBJECT (mux, "Invalid template");
495     return NULL;
496   }
497
498   pad = gst_pad_new_from_template (templ, name);
499   cpad = (GstFlvPad *)
500       gst_collect_pads_add_pad (mux->collect, pad, sizeof (GstFlvPad));
501
502   cpad->video = video;
503
504   cpad->audio_codec = G_MAXUINT;
505   cpad->rate = G_MAXUINT;
506   cpad->width = G_MAXUINT;
507   cpad->channels = G_MAXUINT;
508   cpad->audio_codec_data = NULL;
509
510   cpad->video_codec = G_MAXUINT;
511   cpad->video_codec_data = NULL;
512
513   cpad->sent_codec_data = FALSE;
514
515   cpad->last_timestamp = 0;
516
517   /* FIXME: hacked way to override/extend the event function of
518    * GstCollectPads; because it sets its own event function giving the
519    * element no access to events.
520    */
521   mux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (pad);
522   gst_pad_set_event_function (pad,
523       GST_DEBUG_FUNCPTR (gst_flv_mux_handle_sink_event));
524
525   gst_pad_set_setcaps_function (pad, setcapsfunc);
526   gst_pad_set_active (pad, TRUE);
527   gst_element_add_pad (element, pad);
528
529   return pad;
530 }
531
532 static void
533 gst_flv_mux_release_pad (GstElement * element, GstPad * pad)
534 {
535   GstFlvMux *mux = GST_FLV_MUX (GST_PAD_PARENT (pad));
536   GstFlvPad *cpad = (GstFlvPad *) gst_pad_get_element_private (pad);
537
538   if (cpad && cpad->audio_codec_data)
539     gst_buffer_unref (cpad->audio_codec_data);
540   if (cpad && cpad->video_codec_data)
541     gst_buffer_unref (cpad->video_codec_data);
542
543   gst_collect_pads_remove_pad (mux->collect, pad);
544   gst_element_remove_pad (element, pad);
545 }
546
547 static GstFlowReturn
548 gst_flv_mux_push (GstFlvMux * mux, GstBuffer * buffer)
549 {
550   mux->byte_count += GST_BUFFER_SIZE (buffer);
551
552   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
553     GstFlvMuxIndexEntry *entry = g_slice_new (GstFlvMuxIndexEntry);
554     entry->position = mux->byte_count;
555     entry->time =
556         gst_guint64_to_gdouble (GST_BUFFER_TIMESTAMP (buffer)) / GST_MSECOND;
557     mux->index = g_list_prepend (mux->index, entry);
558   }
559
560   return gst_pad_push (mux->srcpad, buffer);
561 }
562
563 static GstFlowReturn
564 gst_flv_mux_write_metadata (GstFlvMux * mux)
565 {
566   GstTagList *merged_tags;
567   const GstTagList *user_tags;
568   GstFlowReturn ret = GST_FLOW_OK;
569   GstBuffer *script_tag, *tmp;
570   guint8 *data;
571   gint i, n_tags, tags_written = 0;
572   GstClockTime duration = GST_CLOCK_TIME_NONE;
573
574   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
575   GST_DEBUG_OBJECT (mux, "upstream tags = %" GST_PTR_FORMAT, mux->tags);
576   GST_DEBUG_OBJECT (mux, "user-set tags = %" GST_PTR_FORMAT, user_tags);
577
578   merged_tags = gst_tag_list_merge (user_tags, mux->tags,
579       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (mux)));
580
581   GST_DEBUG_OBJECT (mux, "merged tags = %" GST_PTR_FORMAT, merged_tags);
582
583   script_tag = gst_buffer_new_and_alloc (11);
584   data = GST_BUFFER_DATA (script_tag);
585
586   data[0] = 18;
587
588   /* Data size, unknown for now */
589   data[1] = 0;
590   data[2] = 0;
591   data[3] = 0;
592
593   /* Timestamp */
594   data[4] = data[5] = data[6] = data[7] = 0;
595
596   /* Stream ID */
597   data[8] = data[9] = data[10] = 0;
598
599   tmp = gst_buffer_new_and_alloc (13);
600   data = GST_BUFFER_DATA (tmp);
601   data[0] = 2;                  /* string */
602   data[1] = 0;
603   data[2] = 0x0a;               /* length 10 */
604   memcpy (&data[3], "onMetaData", sizeof ("onMetaData"));
605
606   script_tag = gst_buffer_join (script_tag, tmp);
607
608   n_tags =
609       (merged_tags) ? gst_structure_n_fields ((GstStructure *) merged_tags) : 0;
610   tmp = gst_buffer_new_and_alloc (5);
611   data = GST_BUFFER_DATA (tmp);
612   data[0] = 8;                  /* ECMA array */
613   GST_WRITE_UINT32_BE (data + 1, n_tags);
614   script_tag = gst_buffer_join (script_tag, tmp);
615
616   for (i = 0; merged_tags && i < n_tags; i++) {
617     const gchar *tag_name =
618         gst_structure_nth_field_name ((const GstStructure *) merged_tags, i);
619     if (!strcmp (tag_name, GST_TAG_DURATION)) {
620       guint64 dur;
621
622       if (!gst_tag_list_get_uint64 (merged_tags, GST_TAG_DURATION, &dur))
623         continue;
624       duration = dur;
625     } else if (!strcmp (tag_name, GST_TAG_ARTIST) ||
626         !strcmp (tag_name, GST_TAG_TITLE)) {
627       gchar *s;
628       const gchar *t = NULL;
629
630       if (!strcmp (tag_name, GST_TAG_ARTIST))
631         t = "creator";
632       else if (!strcmp (tag_name, GST_TAG_TITLE))
633         t = "title";
634
635       if (!gst_tag_list_get_string (merged_tags, tag_name, &s))
636         continue;
637
638       tmp = gst_buffer_new_and_alloc (2 + strlen (t) + 1 + 2 + strlen (s));
639       data = GST_BUFFER_DATA (tmp);
640       data[0] = 0;              /* tag name length */
641       data[1] = strlen (t);
642       memcpy (&data[2], t, strlen (t));
643       data[2 + strlen (t)] = 2; /* string */
644       data[3 + strlen (t)] = (strlen (s) >> 8) & 0xff;
645       data[4 + strlen (t)] = (strlen (s)) & 0xff;
646       memcpy (&data[5 + strlen (t)], s, strlen (s));
647       script_tag = gst_buffer_join (script_tag, tmp);
648
649       g_free (s);
650       tags_written++;
651     }
652   }
653
654
655   if (duration == GST_CLOCK_TIME_NONE) {
656     GSList *l;
657
658     GstFormat fmt = GST_FORMAT_TIME;
659     guint64 dur;
660
661     for (l = mux->collect->data; l; l = l->next) {
662       GstCollectData *cdata = l->data;
663
664       fmt = GST_FORMAT_TIME;
665
666       if (gst_pad_query_peer_duration (cdata->pad, &fmt, (gint64 *) & dur) &&
667           fmt == GST_FORMAT_TIME && dur != GST_CLOCK_TIME_NONE) {
668         if (duration == GST_CLOCK_TIME_NONE)
669           duration = dur;
670         else
671           duration = MAX (dur, duration);
672       }
673     }
674   }
675
676   if (duration != GST_CLOCK_TIME_NONE) {
677     gdouble d;
678     d = gst_guint64_to_gdouble (duration);
679     d /= (gdouble) GST_SECOND;
680
681     tmp = gst_buffer_new_and_alloc (2 + 8 + 1 + 8);
682     data = GST_BUFFER_DATA (tmp);
683     data[0] = 0;                /* 8 bytes name */
684     data[1] = 8;
685     memcpy (&data[2], "duration", sizeof ("duration"));
686     data[10] = 0;               /* double */
687     GST_WRITE_DOUBLE_BE (data + 11, d);
688     script_tag = gst_buffer_join (script_tag, tmp);
689     tags_written++;
690   }
691
692   if (mux->have_video) {
693     GstPad *video_pad = NULL;
694     GSList *l = mux->collect->data;
695
696     for (; l; l = l->next) {
697       GstFlvPad *cpad = l->data;
698       if (cpad && cpad->video) {
699         video_pad = cpad->collect.pad;
700         break;
701       }
702     }
703
704     if (video_pad && GST_PAD_CAPS (video_pad)) {
705       GstStructure *s = gst_caps_get_structure (GST_PAD_CAPS (video_pad), 0);
706       gint par_x, par_y;
707
708       if (gst_structure_get_fraction (s, "pixel-aspect-ratio", &par_x, &par_y)) {
709         gdouble d;
710
711         d = par_x;
712         tmp = gst_buffer_new_and_alloc (2 + 12 + 1 + 8);
713         data = GST_BUFFER_DATA (tmp);
714         data[0] = 0;            /* 12 bytes name */
715         data[1] = 12;
716         memcpy (&data[2], "AspectRatioX", sizeof ("AspectRatioX"));
717         data[14] = 0;           /* double */
718         GST_WRITE_DOUBLE_BE (data + 15, d);
719         script_tag = gst_buffer_join (script_tag, tmp);
720         tags_written++;
721
722         d = par_y;
723         tmp = gst_buffer_new_and_alloc (2 + 12 + 1 + 8);
724         data = GST_BUFFER_DATA (tmp);
725         data[0] = 0;            /* 12 bytes name */
726         data[1] = 12;
727         memcpy (&data[2], "AspectRatioY", sizeof ("AspectRatioY"));
728         data[14] = 0;           /* double */
729         GST_WRITE_DOUBLE_BE (data + 15, d);
730         script_tag = gst_buffer_join (script_tag, tmp);
731         tags_written++;
732       }
733     }
734   }
735
736   {
737     const gchar *s = "GStreamer FLV muxer";
738
739     tmp = gst_buffer_new_and_alloc (2 + 15 + 1 + 2 + strlen (s));
740     data = GST_BUFFER_DATA (tmp);
741     data[0] = 0;                /* 15 bytes name */
742     data[1] = 15;
743     memcpy (&data[2], "metadatacreator", sizeof ("metadatacreator"));
744     data[17] = 2;               /* string */
745     data[18] = (strlen (s) >> 8) & 0xff;
746     data[19] = (strlen (s)) & 0xff;
747     memcpy (&data[20], s, strlen (s));
748     script_tag = gst_buffer_join (script_tag, tmp);
749
750     tags_written++;
751   }
752
753   {
754     GTimeVal tv = { 0, };
755     time_t secs;
756     struct tm *tm;
757     gchar *s;
758     static const gchar *weekdays[] = {
759       "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
760     };
761     static const gchar *months[] = {
762       "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
763       "Aug", "Sep", "Oct", "Nov", "Dec"
764     };
765
766     g_get_current_time (&tv);
767     secs = tv.tv_sec;
768     tm = gmtime (&secs);
769
770     s = g_strdup_printf ("%s %s %d %d:%d:%d %d", weekdays[tm->tm_wday],
771         months[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
772         tm->tm_year + 1900);
773
774     tmp = gst_buffer_new_and_alloc (2 + 12 + 1 + 2 + strlen (s));
775     data = GST_BUFFER_DATA (tmp);
776     data[0] = 0;                /* 12 bytes name */
777     data[1] = 12;
778     memcpy (&data[2], "creationdate", sizeof ("creationdate"));
779     data[14] = 2;               /* string */
780     data[15] = (strlen (s) >> 8) & 0xff;
781     data[16] = (strlen (s)) & 0xff;
782     memcpy (&data[17], s, strlen (s));
783     script_tag = gst_buffer_join (script_tag, tmp);
784
785     g_free (s);
786     tags_written++;
787   }
788
789   tmp = gst_buffer_new_and_alloc (2 + 0 + 1);
790   data = GST_BUFFER_DATA (tmp);
791   data[0] = 0;                  /* 0 byte size */
792   data[1] = 0;
793   data[2] = 9;                  /* end marker */
794   script_tag = gst_buffer_join (script_tag, tmp);
795   tags_written++;
796
797
798   tmp = gst_buffer_new_and_alloc (4);
799   data = GST_BUFFER_DATA (tmp);
800   GST_WRITE_UINT32_BE (data, GST_BUFFER_SIZE (script_tag));
801   script_tag = gst_buffer_join (script_tag, tmp);
802
803   data = GST_BUFFER_DATA (script_tag);
804   data[1] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 16) & 0xff;
805   data[2] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 8) & 0xff;
806   data[3] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 0) & 0xff;
807
808   GST_WRITE_UINT32_BE (data + 11 + 13 + 1, tags_written);
809
810   gst_buffer_set_caps (script_tag, GST_PAD_CAPS (mux->srcpad));
811   ret = gst_flv_mux_push (mux, script_tag);
812
813   if (merged_tags)
814     gst_tag_list_free (merged_tags);
815
816   return ret;
817 }
818
819 static GstFlowReturn
820 gst_flv_mux_write_header (GstFlvMux * mux)
821 {
822   GstBuffer *header = gst_buffer_new_and_alloc (9 + 4);
823   guint8 *data = GST_BUFFER_DATA (header);
824   GstFlowReturn ret;
825
826   if (GST_PAD_CAPS (mux->srcpad) == NULL) {
827     GstCaps *caps = gst_caps_new_simple ("video/x-flv", NULL);
828
829     gst_pad_set_caps (mux->srcpad, caps);
830     gst_caps_unref (caps);
831   }
832   gst_buffer_set_caps (header, GST_PAD_CAPS (mux->srcpad));
833
834   data[0] = 'F';
835   data[1] = 'L';
836   data[2] = 'V';
837   data[3] = 0x01;               /* Version */
838
839   data[4] = (mux->have_audio << 2) | mux->have_video;   /* flags */
840   GST_WRITE_UINT32_BE (data + 5, 9);    /* data offset */
841
842   GST_WRITE_UINT32_BE (data + 9, 0);    /* previous tag size */
843
844   ret = gst_flv_mux_push (mux, header);
845   if (ret != GST_FLOW_OK)
846     return ret;
847
848   return gst_flv_mux_write_metadata (mux);
849 }
850
851 static GstFlowReturn
852 gst_flv_mux_write_buffer (GstFlvMux * mux, GstFlvPad * cpad)
853 {
854   GstBuffer *tag;
855   guint8 *data;
856   guint size;
857   GstBuffer *buffer =
858       gst_collect_pads_pop (mux->collect, (GstCollectData *) cpad);
859   guint32 timestamp =
860       (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) ? GST_BUFFER_TIMESTAMP (buffer) /
861       GST_MSECOND : cpad->last_timestamp / GST_MSECOND;
862   gboolean second_run = FALSE;
863   GstFlowReturn ret;
864
865 next:
866   size = 11;
867   if (cpad->video) {
868     size += 1;
869     if (cpad->video_codec == 7 && !cpad->sent_codec_data)
870       size += 4 + GST_BUFFER_SIZE (cpad->video_codec_data);
871     else if (cpad->video_codec == 7)
872       size += 4 + GST_BUFFER_SIZE (buffer);
873     else
874       size += GST_BUFFER_SIZE (buffer);
875   } else {
876     size += 1;
877     if (cpad->audio_codec == 10 && !cpad->sent_codec_data)
878       size += 1 + GST_BUFFER_SIZE (cpad->audio_codec_data);
879     else if (cpad->audio_codec == 10)
880       size += 1 + GST_BUFFER_SIZE (buffer);
881     else
882       size += GST_BUFFER_SIZE (buffer);
883   }
884   size += 4;
885
886   tag = gst_buffer_new_and_alloc (size);
887   GST_BUFFER_TIMESTAMP (tag) = timestamp * GST_MSECOND;
888   data = GST_BUFFER_DATA (tag);
889   memset (data, 0, size);
890
891   data[0] = (cpad->video) ? 9 : 8;
892
893   data[1] = ((size - 11 - 4) >> 16) & 0xff;
894   data[2] = ((size - 11 - 4) >> 8) & 0xff;
895   data[3] = ((size - 11 - 4) >> 0) & 0xff;
896
897   data[4] = (timestamp >> 16) & 0xff;
898   data[5] = (timestamp >> 8) & 0xff;
899   data[6] = (timestamp >> 0) & 0xff;
900   data[7] = (timestamp >> 24) & 0xff;
901
902   data[8] = data[9] = data[10] = 0;
903
904   if (cpad->video) {
905     if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
906       data[11] |= 2 << 4;
907     else
908       data[11] |= 1 << 4;
909
910     data[11] |= cpad->video_codec & 0x0f;
911
912     if (cpad->video_codec == 7 && !cpad->sent_codec_data) {
913       data[12] = 0;
914       data[13] = data[14] = data[15] = 0;
915
916       memcpy (data + 11 + 1 + 4, GST_BUFFER_DATA (cpad->video_codec_data),
917           GST_BUFFER_SIZE (cpad->video_codec_data));
918       second_run = TRUE;
919     } else if (cpad->video_codec == 7) {
920       data[12] = 1;
921
922       /* FIXME: what to do about composition time */
923       data[13] = data[14] = data[15] = 0;
924
925       memcpy (data + 11 + 1 + 4, GST_BUFFER_DATA (buffer),
926           GST_BUFFER_SIZE (buffer));
927     } else {
928       memcpy (data + 11 + 1, GST_BUFFER_DATA (buffer),
929           GST_BUFFER_SIZE (buffer));
930     }
931   } else {
932     data[11] |= (cpad->audio_codec << 4) & 0xf0;
933     data[11] |= (cpad->rate << 2) & 0x0c;
934     data[11] |= (cpad->width << 1) & 0x02;
935     data[11] |= (cpad->channels << 0) & 0x01;
936
937     if (cpad->audio_codec == 10 && !cpad->sent_codec_data) {
938       data[12] = 0;
939
940       memcpy (data + 11 + 1 + 1, GST_BUFFER_DATA (cpad->audio_codec_data),
941           GST_BUFFER_SIZE (cpad->audio_codec_data));
942       second_run = TRUE;
943     } else if (cpad->audio_codec == 10) {
944       data[12] = 1;
945
946       memcpy (data + 11 + 1 + 1, GST_BUFFER_DATA (buffer),
947           GST_BUFFER_SIZE (buffer));
948     } else {
949       memcpy (data + 11 + 1, GST_BUFFER_DATA (buffer),
950           GST_BUFFER_SIZE (buffer));
951     }
952   }
953
954   GST_WRITE_UINT32_BE (data + size - 4, size - 4);
955
956   gst_buffer_set_caps (tag, GST_PAD_CAPS (mux->srcpad));
957
958   if (second_run) {
959     second_run = FALSE;
960     cpad->sent_codec_data = TRUE;
961
962     ret = gst_flv_mux_push (mux, tag);
963     if (ret != GST_FLOW_OK) {
964       gst_buffer_unref (buffer);
965       return ret;
966     }
967
968     cpad->last_timestamp = timestamp;
969
970     tag = NULL;
971     goto next;
972   }
973
974   gst_buffer_copy_metadata (tag, buffer, GST_BUFFER_COPY_TIMESTAMPS);
975   GST_BUFFER_OFFSET (tag) = GST_BUFFER_OFFSET_END (tag) =
976       GST_BUFFER_OFFSET_NONE;
977
978   gst_buffer_unref (buffer);
979
980   ret = gst_flv_mux_push (mux, tag);
981
982   if (ret == GST_FLOW_OK)
983     cpad->last_timestamp = timestamp;
984
985   return ret;
986 }
987
988 static GstFlowReturn
989 gst_flv_mux_write_index (GstFlvMux * mux)
990 {
991   GstFlowReturn ret = GST_FLOW_OK;
992   GstBuffer *script_tag, *tmp;
993   guint8 *data;
994   GList *l;
995   guint32 index_len;
996   guint32 i, index_skip;
997
998   if (!mux->index)
999     return GST_FLOW_OK;
1000
1001   script_tag = gst_buffer_new_and_alloc (11);
1002   data = GST_BUFFER_DATA (script_tag);
1003
1004   data[0] = 18;
1005
1006   /* Data size, unknown for now */
1007   data[1] = 0;
1008   data[2] = 0;
1009   data[3] = 0;
1010
1011   /* Timestamp */
1012   data[4] = data[5] = data[6] = data[7] = 0;
1013
1014   /* Stream ID */
1015   data[8] = data[9] = data[10] = 0;
1016
1017   tmp = gst_buffer_new_and_alloc (13);
1018   data = GST_BUFFER_DATA (tmp);
1019   data[0] = 2;                  /* string */
1020   data[1] = 0;
1021   data[2] = 0x0a;               /* length 10 */
1022   memcpy (&data[3], "onMetaData", sizeof ("onMetaData"));
1023
1024   script_tag = gst_buffer_join (script_tag, tmp);
1025
1026   tmp = gst_buffer_new_and_alloc (5);
1027   data = GST_BUFFER_DATA (tmp);
1028   data[0] = 8;                  /* ECMA array */
1029   GST_WRITE_UINT32_BE (data + 1, 2);
1030   script_tag = gst_buffer_join (script_tag, tmp);
1031
1032   mux->index = g_list_reverse (mux->index);
1033   index_len = g_list_length (mux->index);
1034
1035   /* We write at most 128 elements */
1036   index_skip = (index_len > 128) ? 1 + index_len / 128 : 1;
1037   index_len =
1038       (index_len <= 128) ? 1 : (index_len + index_skip - 1) / index_skip;
1039
1040   tmp = gst_buffer_new_and_alloc (2 + 5 + 1 + 4 + index_len * (1 + 8));
1041   data = GST_BUFFER_DATA (tmp);
1042   data[0] = 0;                  /* 5 bytes name */
1043   data[1] = 5;
1044   memcpy (&data[2], "times", 5);
1045   data[7] = 10;                 /* array */
1046   GST_WRITE_UINT32_BE (&data[8], index_len);
1047   data += 12;
1048
1049   for (i = 0, l = mux->index; l; l = l->next, i++) {
1050     GstFlvMuxIndexEntry *entry = l->data;
1051
1052     if (i % index_skip != 0)
1053       continue;
1054
1055     data[0] = 0;
1056     GST_WRITE_DOUBLE_BE (&data[1], entry->time);
1057     data += 9;
1058   }
1059   script_tag = gst_buffer_join (script_tag, tmp);
1060
1061   tmp = gst_buffer_new_and_alloc (2 + 13 + 1 + 4 + index_len * (1 + 8));
1062   data = GST_BUFFER_DATA (tmp);
1063   data[0] = 0;                  /* 13 bytes name */
1064   data[1] = 13;
1065   memcpy (&data[2], "filepositions", 13);
1066   data[15] = 10;                /* array */
1067   GST_WRITE_UINT32_BE (&data[16], index_len);
1068   data += 20;
1069
1070   for (i = 0, l = mux->index; l; l = l->next, i++) {
1071     GstFlvMuxIndexEntry *entry = l->data;
1072
1073     if (i % index_skip != 0)
1074       continue;
1075     data[0] = 0;
1076     GST_WRITE_DOUBLE_BE (&data[1], entry->position);
1077     data += 9;
1078   }
1079   script_tag = gst_buffer_join (script_tag, tmp);
1080
1081   tmp = gst_buffer_new_and_alloc (4);
1082   data = GST_BUFFER_DATA (tmp);
1083   GST_WRITE_UINT32_BE (data, GST_BUFFER_SIZE (script_tag));
1084   script_tag = gst_buffer_join (script_tag, tmp);
1085
1086   data = GST_BUFFER_DATA (script_tag);
1087   data[1] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 16) & 0xff;
1088   data[2] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 8) & 0xff;
1089   data[3] = ((GST_BUFFER_SIZE (script_tag) - 11 - 4) >> 0) & 0xff;
1090
1091   gst_buffer_set_caps (script_tag, GST_PAD_CAPS (mux->srcpad));
1092   ret = gst_flv_mux_push (mux, script_tag);
1093
1094   return ret;
1095 }
1096
1097 static GstFlowReturn
1098 gst_flv_mux_collected (GstCollectPads * pads, gpointer user_data)
1099 {
1100   GstFlvMux *mux = GST_FLV_MUX (user_data);
1101   GstFlvPad *best;
1102   GstClockTime best_time;
1103   GstFlowReturn ret;
1104   GSList *sl;
1105   gboolean eos = TRUE;
1106
1107   if (mux->state == GST_FLV_MUX_STATE_HEADER) {
1108     if (mux->collect->data == NULL) {
1109       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1110           ("No input streams configured"));
1111       return GST_FLOW_ERROR;
1112     }
1113
1114     if (gst_pad_push_event (mux->srcpad,
1115             gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES, 0, -1, 0)))
1116       ret = gst_flv_mux_write_header (mux);
1117     else
1118       ret = GST_FLOW_ERROR;
1119
1120     if (ret != GST_FLOW_OK)
1121       return ret;
1122     mux->state = GST_FLV_MUX_STATE_DATA;
1123   }
1124
1125   best = NULL;
1126   best_time = GST_CLOCK_TIME_NONE;
1127   for (sl = mux->collect->data; sl; sl = sl->next) {
1128     GstFlvPad *cpad = sl->data;
1129     GstBuffer *buffer = gst_collect_pads_peek (pads, (GstCollectData *) cpad);
1130     GstClockTime time;
1131
1132     if (!buffer)
1133       continue;
1134
1135     eos = FALSE;
1136
1137     time = GST_BUFFER_TIMESTAMP (buffer);
1138     gst_buffer_unref (buffer);
1139
1140     /* Use buffers without valid timestamp first */
1141     if (!GST_CLOCK_TIME_IS_VALID (time)) {
1142       GST_WARNING_OBJECT (pads, "Buffer without valid timestamp");
1143
1144       best_time = cpad->last_timestamp;
1145       best = cpad;
1146       break;
1147     }
1148
1149
1150     if (best == NULL || (GST_CLOCK_TIME_IS_VALID (best_time)
1151             && time < best_time)) {
1152       best = cpad;
1153       best_time = time;
1154     }
1155   }
1156
1157   if (GST_CLOCK_TIME_IS_VALID (best_time)
1158       && best_time / GST_MSECOND > G_MAXUINT32) {
1159     GST_WARNING_OBJECT (mux, "Timestamp larger than FLV supports - EOS");
1160     eos = TRUE;
1161   }
1162
1163   if (!eos && best) {
1164     return gst_flv_mux_write_buffer (mux, best);
1165   } else if (eos) {
1166     gst_flv_mux_write_index (mux);
1167     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
1168     return GST_FLOW_UNEXPECTED;
1169   } else {
1170     return GST_FLOW_OK;
1171   }
1172 }
1173
1174 static GstStateChangeReturn
1175 gst_flv_mux_change_state (GstElement * element, GstStateChange transition)
1176 {
1177   GstStateChangeReturn ret;
1178   GstFlvMux *mux = GST_FLV_MUX (element);
1179
1180   switch (transition) {
1181     case GST_STATE_CHANGE_NULL_TO_READY:
1182       break;
1183     case GST_STATE_CHANGE_READY_TO_PAUSED:
1184       gst_collect_pads_start (mux->collect);
1185       break;
1186     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1187       break;
1188     case GST_STATE_CHANGE_PAUSED_TO_READY:
1189       gst_collect_pads_stop (mux->collect);
1190       break;
1191     default:
1192       break;
1193   }
1194
1195   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1196
1197   switch (transition) {
1198     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1199       break;
1200     case GST_STATE_CHANGE_PAUSED_TO_READY:
1201       gst_flv_mux_reset (GST_ELEMENT (mux));
1202       break;
1203     case GST_STATE_CHANGE_READY_TO_NULL:
1204       break;
1205     default:
1206       break;
1207   }
1208
1209   return ret;
1210 }