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