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