flvmux: Support rollover in timestamp
[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  * Copyright (c) 2008-2017 Collabora Ltd
5  *  @author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  *  @author: Vincent Penquerc'h <vincent.penquerch@collabora.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:element-flvmux
26  * @title: flvmux
27  *
28  * flvmux muxes different streams into an FLV file.
29  *
30  * ## Example launch line
31  * |[
32  * 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.
33  * ]| This pipeline encodes a test audio and video stream and muxes both into an FLV file.
34  *
35  */
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include <math.h>
42 #include <string.h>
43
44 #include <gst/audio/audio.h>
45
46 #include "gstflvmux.h"
47 #include "amfdefs.h"
48
49 GST_DEBUG_CATEGORY_STATIC (flvmux_debug);
50 #define GST_CAT_DEFAULT flvmux_debug
51
52 enum
53 {
54   PROP_0,
55   PROP_STREAMABLE,
56   PROP_METADATACREATOR,
57   PROP_ENCODER
58 };
59
60 #define DEFAULT_STREAMABLE FALSE
61 #define MAX_INDEX_ENTRIES 128
62 #define DEFAULT_METADATACREATOR "GStreamer " PACKAGE_VERSION " FLV muxer"
63
64 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
65     GST_PAD_SRC,
66     GST_PAD_ALWAYS,
67     GST_STATIC_CAPS ("video/x-flv")
68     );
69
70 static GstStaticPadTemplate videosink_templ = GST_STATIC_PAD_TEMPLATE ("video",
71     GST_PAD_SINK,
72     GST_PAD_REQUEST,
73     GST_STATIC_CAPS ("video/x-flash-video; "
74         "video/x-flash-screen; "
75         "video/x-vp6-flash; " "video/x-vp6-alpha; "
76         "video/x-h264, stream-format=avc;")
77     );
78
79 static GstStaticPadTemplate audiosink_templ = GST_STATIC_PAD_TEMPLATE ("audio",
80     GST_PAD_SINK,
81     GST_PAD_REQUEST,
82     GST_STATIC_CAPS
83     ("audio/x-adpcm, layout = (string) swf, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
84         "audio/mpeg, mpegversion = (int) 1, layer = (int) 3, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 22050, 44100 }, parsed = (boolean) TRUE; "
85         "audio/mpeg, mpegversion = (int) { 4, 2 }, stream-format = (string) raw; "
86         "audio/x-nellymoser, channels = (int) { 1, 2 }, rate = (int) { 5512, 8000, 11025, 16000, 22050, 44100 }; "
87         "audio/x-raw, format = (string) { U8, S16LE}, layout = (string) interleaved, channels = (int) { 1, 2 }, rate = (int) { 5512, 11025, 22050, 44100 }; "
88         "audio/x-alaw, channels = (int) { 1, 2 }, rate = (int) 8000; "
89         "audio/x-mulaw, channels = (int) { 1, 2 }, rate = (int) 8000; "
90         "audio/x-speex, channels = (int) 1, rate = (int) 16000;")
91     );
92
93 G_DEFINE_TYPE (GstFlvMuxPad, gst_flv_mux_pad, GST_TYPE_AGGREGATOR_PAD);
94
95 #define gst_flv_mux_parent_class parent_class
96 G_DEFINE_TYPE_WITH_CODE (GstFlvMux, gst_flv_mux, GST_TYPE_AGGREGATOR,
97     G_IMPLEMENT_INTERFACE (GST_TYPE_TAG_SETTER, NULL));
98
99 static GstFlowReturn
100 gst_flv_mux_aggregate (GstAggregator * aggregator, gboolean timeout);
101 static gboolean
102 gst_flv_mux_sink_event (GstAggregator * aggregator, GstAggregatorPad * pad,
103     GstEvent * event);
104
105 static GstAggregatorPad *gst_flv_mux_create_new_pad (GstAggregator * agg,
106     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps);
107 static void gst_flv_mux_release_pad (GstElement * element, GstPad * pad);
108
109 static gboolean gst_flv_mux_video_pad_setcaps (GstFlvMuxPad * pad,
110     GstCaps * caps);
111 static gboolean gst_flv_mux_audio_pad_setcaps (GstFlvMuxPad * pad,
112     GstCaps * caps);
113
114 static void gst_flv_mux_get_property (GObject * object,
115     guint prop_id, GValue * value, GParamSpec * pspec);
116 static void gst_flv_mux_set_property (GObject * object,
117     guint prop_id, const GValue * value, GParamSpec * pspec);
118 static void gst_flv_mux_finalize (GObject * object);
119
120 static void gst_flv_mux_reset (GstElement * element);
121 static void gst_flv_mux_reset_pad (GstFlvMuxPad * pad);
122
123 static void gst_flv_mux_pad_finalize (GObject * object);
124
125 static gboolean gst_flv_mux_start (GstAggregator * aggregator);
126 static GstFlowReturn gst_flv_mux_flush (GstAggregator * aggregator);
127 static GstClockTime gst_flv_mux_get_next_time (GstAggregator * aggregator);
128 static GstFlowReturn gst_flv_mux_write_eos (GstFlvMux * mux);
129 static GstFlowReturn gst_flv_mux_write_header (GstFlvMux * mux);
130 static GstFlowReturn gst_flv_mux_rewrite_header (GstFlvMux * mux);
131 static gboolean gst_flv_mux_are_all_pads_eos (GstFlvMux * mux);
132 static GstFlowReturn gst_flv_mux_update_src_caps (GstAggregator * aggregator,
133     GstCaps * caps, GstCaps ** ret);
134
135 static GstFlowReturn
136 gst_flv_mux_pad_flush (GstAggregatorPad * pad, GstAggregator * aggregator)
137 {
138   GstFlvMuxPad *flvpad = GST_FLV_MUX_PAD (pad);
139
140   flvpad->last_timestamp = 0;
141   flvpad->pts = GST_CLOCK_STIME_NONE;
142   flvpad->dts = GST_CLOCK_STIME_NONE;
143
144   return GST_FLOW_OK;
145 }
146
147 static void
148 gst_flv_mux_pad_class_init (GstFlvMuxPadClass * klass)
149 {
150   GstAggregatorPadClass *aggregatorpad_class = (GstAggregatorPadClass *) klass;
151   GObjectClass *gobject_class = (GObjectClass *) klass;
152
153   gobject_class->finalize = gst_flv_mux_pad_finalize;
154
155   aggregatorpad_class->flush = GST_DEBUG_FUNCPTR (gst_flv_mux_pad_flush);
156 }
157
158 static void
159 gst_flv_mux_pad_init (GstFlvMuxPad * pad)
160 {
161   gst_flv_mux_reset_pad (pad);
162 }
163
164 typedef struct
165 {
166   gdouble position;
167   gdouble time;
168 } GstFlvMuxIndexEntry;
169
170 static void
171 gst_flv_mux_index_entry_free (GstFlvMuxIndexEntry * entry)
172 {
173   g_slice_free (GstFlvMuxIndexEntry, entry);
174 }
175
176 static GstBuffer *
177 _gst_buffer_new_wrapped (gpointer mem, gsize size, GFreeFunc free_func)
178 {
179   GstBuffer *buf;
180
181   buf = gst_buffer_new ();
182   gst_buffer_append_memory (buf,
183       gst_memory_new_wrapped (free_func ? 0 : GST_MEMORY_FLAG_READONLY,
184           mem, size, 0, size, mem, free_func));
185
186   return buf;
187 }
188
189 static void
190 _gst_buffer_new_and_alloc (gsize size, GstBuffer ** buffer, guint8 ** data)
191 {
192   g_return_if_fail (data != NULL);
193   g_return_if_fail (buffer != NULL);
194
195   *data = g_malloc (size);
196   *buffer = _gst_buffer_new_wrapped (*data, size, g_free);
197 }
198
199 static void
200 gst_flv_mux_class_init (GstFlvMuxClass * klass)
201 {
202   GObjectClass *gobject_class;
203   GstElementClass *gstelement_class;
204   GstAggregatorClass *gstaggregator_class;
205
206   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
207
208   gobject_class = (GObjectClass *) klass;
209   gstelement_class = (GstElementClass *) klass;
210   gstaggregator_class = (GstAggregatorClass *) klass;
211
212   gobject_class->get_property = gst_flv_mux_get_property;
213   gobject_class->set_property = gst_flv_mux_set_property;
214   gobject_class->finalize = gst_flv_mux_finalize;
215
216   /* FIXME: ideally the right mode of operation should be detected
217    * automatically using queries when parameter not specified. */
218   /**
219    * GstFlvMux:streamable
220    *
221    * If True, the output will be streaming friendly. (ie without indexes and
222    * duration)
223    */
224   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
225       g_param_spec_boolean ("streamable", "streamable",
226           "If set to true, the output should be as if it is to be streamed "
227           "and hence no indexes written or duration written.",
228           DEFAULT_STREAMABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
229   g_object_class_install_property (gobject_class, PROP_METADATACREATOR,
230       g_param_spec_string ("metadatacreator", "metadatacreator",
231           "The value of metadatacreator in the meta packet.",
232           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
233
234   g_object_class_install_property (gobject_class, PROP_ENCODER,
235       g_param_spec_string ("encoder", "encoder",
236           "The value of encoder in the meta packet.",
237           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
238
239   gstaggregator_class->create_new_pad =
240       GST_DEBUG_FUNCPTR (gst_flv_mux_create_new_pad);
241   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_flv_mux_release_pad);
242
243   gstaggregator_class->start = GST_DEBUG_FUNCPTR (gst_flv_mux_start);
244   gstaggregator_class->aggregate = GST_DEBUG_FUNCPTR (gst_flv_mux_aggregate);
245   gstaggregator_class->sink_event = GST_DEBUG_FUNCPTR (gst_flv_mux_sink_event);
246   gstaggregator_class->flush = GST_DEBUG_FUNCPTR (gst_flv_mux_flush);
247   gstaggregator_class->get_next_time =
248       GST_DEBUG_FUNCPTR (gst_flv_mux_get_next_time);
249   gstaggregator_class->update_src_caps =
250       GST_DEBUG_FUNCPTR (gst_flv_mux_update_src_caps);
251
252   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
253       &videosink_templ, GST_TYPE_FLV_MUX_PAD);
254   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
255       &audiosink_templ, GST_TYPE_FLV_MUX_PAD);
256   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
257       &src_templ, GST_TYPE_AGGREGATOR_PAD);
258   gst_element_class_set_static_metadata (gstelement_class, "FLV muxer",
259       "Codec/Muxer",
260       "Muxes video/audio streams into a FLV stream",
261       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
262
263   GST_DEBUG_CATEGORY_INIT (flvmux_debug, "flvmux", 0, "FLV muxer");
264 }
265
266 static void
267 gst_flv_mux_init (GstFlvMux * mux)
268 {
269   mux->srcpad = GST_AGGREGATOR_CAST (mux)->srcpad;
270
271   /* property */
272   mux->streamable = DEFAULT_STREAMABLE;
273   mux->metadatacreator = g_strdup (DEFAULT_METADATACREATOR);
274   mux->encoder = g_strdup (DEFAULT_METADATACREATOR);
275
276   mux->new_tags = FALSE;
277
278   gst_flv_mux_reset (GST_ELEMENT (mux));
279 }
280
281 static void
282 gst_flv_mux_finalize (GObject * object)
283 {
284   GstFlvMux *mux = GST_FLV_MUX (object);
285
286   gst_flv_mux_reset (GST_ELEMENT (object));
287   g_free (mux->metadatacreator);
288   g_free (mux->encoder);
289
290   G_OBJECT_CLASS (gst_flv_mux_parent_class)->finalize (object);
291 }
292
293 static void
294 gst_flv_mux_pad_finalize (GObject * object)
295 {
296   GstFlvMuxPad *pad = GST_FLV_MUX_PAD (object);
297
298   gst_flv_mux_reset_pad (pad);
299
300   G_OBJECT_CLASS (gst_flv_mux_pad_parent_class)->finalize (object);
301 }
302
303 static GstFlowReturn
304 gst_flv_mux_flush (GstAggregator * aggregator)
305 {
306   /* TODO: What is the right behaviour on flush? Should we just ignore it ?
307    * This still needs to be defined. */
308
309   gst_flv_mux_reset (GST_ELEMENT (aggregator));
310   return GST_FLOW_OK;
311 }
312
313 static gboolean
314 gst_flv_mux_start (GstAggregator * aggregator)
315 {
316   gst_flv_mux_reset (GST_ELEMENT (aggregator));
317   return TRUE;
318 }
319
320 static void
321 gst_flv_mux_reset (GstElement * element)
322 {
323   GstFlvMux *mux = GST_FLV_MUX (element);
324
325   g_list_foreach (mux->index, (GFunc) gst_flv_mux_index_entry_free, NULL);
326   g_list_free (mux->index);
327   mux->index = NULL;
328   mux->byte_count = 0;
329
330   mux->duration = GST_CLOCK_TIME_NONE;
331   mux->new_tags = FALSE;
332   mux->first_timestamp = GST_CLOCK_STIME_NONE;
333   mux->last_dts = 0;
334
335   mux->state = GST_FLV_MUX_STATE_HEADER;
336   mux->sent_header = FALSE;
337
338   /* tags */
339   gst_tag_setter_reset_tags (GST_TAG_SETTER (mux));
340 }
341
342 /* Extract per-codec relevant tags for
343  * insertion into the metadata later - ie bitrate,
344  * but maybe others in the future */
345 static void
346 gst_flv_mux_store_codec_tags (GstFlvMux * mux,
347     GstFlvMuxPad * flvpad, GstTagList * list)
348 {
349   /* Look for a bitrate as either nominal or actual bitrate tag */
350   if (gst_tag_list_get_uint (list, GST_TAG_NOMINAL_BITRATE, &flvpad->bitrate)
351       || gst_tag_list_get_uint (list, GST_TAG_BITRATE, &flvpad->bitrate)) {
352     GST_DEBUG_OBJECT (mux, "Stored bitrate for pad %" GST_PTR_FORMAT " = %u",
353         flvpad, flvpad->bitrate);
354   }
355 }
356
357 static gboolean
358 gst_flv_mux_sink_event (GstAggregator * aggregator, GstAggregatorPad * pad,
359     GstEvent * event)
360 {
361   GstFlvMux *mux = GST_FLV_MUX (aggregator);
362   GstFlvMuxPad *flvpad = (GstFlvMuxPad *) pad;
363   gboolean ret = TRUE;
364
365   switch (GST_EVENT_TYPE (event)) {
366     case GST_EVENT_CAPS:
367     {
368       GstCaps *caps;
369
370       gst_event_parse_caps (event, &caps);
371
372       if (mux->video_pad == flvpad) {
373         ret = gst_flv_mux_video_pad_setcaps (flvpad, caps);
374       } else if (mux->audio_pad == flvpad) {
375         ret = gst_flv_mux_audio_pad_setcaps (flvpad, caps);
376       } else {
377         g_assert_not_reached ();
378       }
379       break;
380     }
381     case GST_EVENT_TAG:{
382       GstTagList *list;
383       GstTagSetter *setter = GST_TAG_SETTER (mux);
384       const GstTagMergeMode mode = gst_tag_setter_get_tag_merge_mode (setter);
385
386       gst_event_parse_tag (event, &list);
387       gst_tag_setter_merge_tags (setter, list, mode);
388       gst_flv_mux_store_codec_tags (mux, flvpad, list);
389       mux->new_tags = TRUE;
390       ret = TRUE;
391       break;
392     }
393     default:
394       break;
395   }
396
397   if (!ret)
398     return FALSE;
399
400   return GST_AGGREGATOR_CLASS (parent_class)->sink_event (aggregator, pad,
401       event);;
402 }
403
404 static gboolean
405 gst_flv_mux_video_pad_setcaps (GstFlvMuxPad * pad, GstCaps * caps)
406 {
407   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
408   gboolean ret = TRUE;
409   GstStructure *s;
410   guint old_codec;
411   GstBuffer *old_codec_data = NULL;
412
413   old_codec = pad->codec;
414   if (pad->codec_data)
415     old_codec_data = gst_buffer_ref (pad->codec_data);
416
417   s = gst_caps_get_structure (caps, 0);
418
419   if (strcmp (gst_structure_get_name (s), "video/x-flash-video") == 0) {
420     pad->codec = 2;
421   } else if (strcmp (gst_structure_get_name (s), "video/x-flash-screen") == 0) {
422     pad->codec = 3;
423   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-flash") == 0) {
424     pad->codec = 4;
425   } else if (strcmp (gst_structure_get_name (s), "video/x-vp6-alpha") == 0) {
426     pad->codec = 5;
427   } else if (strcmp (gst_structure_get_name (s), "video/x-h264") == 0) {
428     pad->codec = 7;
429   } else {
430     ret = FALSE;
431   }
432
433   if (ret && gst_structure_has_field (s, "codec_data")) {
434     const GValue *val = gst_structure_get_value (s, "codec_data");
435
436     if (val)
437       gst_buffer_replace (&pad->codec_data, gst_value_get_buffer (val));
438     else if (!val && pad->codec_data)
439       gst_buffer_unref (pad->codec_data);
440   }
441
442   if (ret && mux->streamable && mux->state != GST_FLV_MUX_STATE_HEADER) {
443     if (old_codec != pad->codec) {
444       pad->info_changed = TRUE;
445     }
446
447     if (old_codec_data && pad->codec_data) {
448       GstMapInfo map;
449
450       gst_buffer_map (old_codec_data, &map, GST_MAP_READ);
451       if (map.size != gst_buffer_get_size (pad->codec_data) ||
452           gst_buffer_memcmp (pad->codec_data, 0, map.data, map.size))
453         pad->info_changed = TRUE;
454
455       gst_buffer_unmap (old_codec_data, &map);
456     } else if (!old_codec_data && pad->codec_data) {
457       pad->info_changed = TRUE;
458     }
459
460     if (pad->info_changed)
461       mux->state = GST_FLV_MUX_STATE_HEADER;
462   }
463
464   if (old_codec_data)
465     gst_buffer_unref (old_codec_data);
466
467   gst_object_unref (mux);
468
469   return ret;
470 }
471
472 static gboolean
473 gst_flv_mux_audio_pad_setcaps (GstFlvMuxPad * pad, GstCaps * caps)
474 {
475   GstFlvMux *mux = GST_FLV_MUX (gst_pad_get_parent (pad));
476   gboolean ret = TRUE;
477   GstStructure *s;
478   guint old_codec, old_rate, old_width, old_channels;
479   GstBuffer *old_codec_data = NULL;
480
481   old_codec = pad->codec;
482   old_rate = pad->rate;
483   old_width = pad->width;
484   old_channels = pad->channels;
485   if (pad->codec_data)
486     old_codec_data = gst_buffer_ref (pad->codec_data);
487
488   s = gst_caps_get_structure (caps, 0);
489
490   if (strcmp (gst_structure_get_name (s), "audio/x-adpcm") == 0) {
491     const gchar *layout = gst_structure_get_string (s, "layout");
492     if (layout && strcmp (layout, "swf") == 0) {
493       pad->codec = 1;
494     } else {
495       ret = FALSE;
496     }
497   } else if (strcmp (gst_structure_get_name (s), "audio/mpeg") == 0) {
498     gint mpegversion;
499
500     if (gst_structure_get_int (s, "mpegversion", &mpegversion)) {
501       if (mpegversion == 1) {
502         gint layer;
503
504         if (gst_structure_get_int (s, "layer", &layer) && layer == 3) {
505           gint rate;
506
507           if (gst_structure_get_int (s, "rate", &rate) && rate == 8000)
508             pad->codec = 14;
509           else
510             pad->codec = 2;
511         } else {
512           ret = FALSE;
513         }
514       } else if (mpegversion == 4 || mpegversion == 2) {
515         pad->codec = 10;
516       } else {
517         ret = FALSE;
518       }
519     } else {
520       ret = FALSE;
521     }
522   } else if (strcmp (gst_structure_get_name (s), "audio/x-nellymoser") == 0) {
523     gint rate, channels;
524
525     if (gst_structure_get_int (s, "rate", &rate)
526         && gst_structure_get_int (s, "channels", &channels)) {
527       if (channels == 1 && rate == 16000)
528         pad->codec = 4;
529       else if (channels == 1 && rate == 8000)
530         pad->codec = 5;
531       else
532         pad->codec = 6;
533     } else {
534       pad->codec = 6;
535     }
536   } else if (strcmp (gst_structure_get_name (s), "audio/x-raw") == 0) {
537     GstAudioInfo info;
538
539     if (gst_audio_info_from_caps (&info, caps)) {
540       pad->codec = 3;
541
542       if (GST_AUDIO_INFO_WIDTH (&info) == 8)
543         pad->width = 0;
544       else if (GST_AUDIO_INFO_WIDTH (&info) == 16)
545         pad->width = 1;
546       else
547         ret = FALSE;
548     } else
549       ret = FALSE;
550   } else if (strcmp (gst_structure_get_name (s), "audio/x-alaw") == 0) {
551     pad->codec = 7;
552   } else if (strcmp (gst_structure_get_name (s), "audio/x-mulaw") == 0) {
553     pad->codec = 8;
554   } else if (strcmp (gst_structure_get_name (s), "audio/x-speex") == 0) {
555     pad->codec = 11;
556   } else {
557     ret = FALSE;
558   }
559
560   if (ret) {
561     gint rate, channels;
562
563     if (gst_structure_get_int (s, "rate", &rate)) {
564       if (pad->codec == 10)
565         pad->rate = 3;
566       else if (rate == 5512)
567         pad->rate = 0;
568       else if (rate == 11025)
569         pad->rate = 1;
570       else if (rate == 22050)
571         pad->rate = 2;
572       else if (rate == 44100)
573         pad->rate = 3;
574       else if (rate == 8000 && (pad->codec == 5 || pad->codec == 14
575               || pad->codec == 7 || pad->codec == 8))
576         pad->rate = 0;
577       else if (rate == 16000 && (pad->codec == 4 || pad->codec == 11))
578         pad->rate = 0;
579       else
580         ret = FALSE;
581     } else if (pad->codec == 10) {
582       pad->rate = 3;
583     } else {
584       ret = FALSE;
585     }
586
587     if (gst_structure_get_int (s, "channels", &channels)) {
588       if (pad->codec == 4 || pad->codec == 5
589           || pad->codec == 6 || pad->codec == 11)
590         pad->channels = 0;
591       else if (pad->codec == 10)
592         pad->channels = 1;
593       else if (channels == 1)
594         pad->channels = 0;
595       else if (channels == 2)
596         pad->channels = 1;
597       else
598         ret = FALSE;
599     } else if (pad->codec == 4 || pad->codec == 5 || pad->codec == 6) {
600       pad->channels = 0;
601     } else if (pad->codec == 10) {
602       pad->channels = 1;
603     } else {
604       ret = FALSE;
605     }
606
607     if (pad->codec != 3)
608       pad->width = 1;
609   }
610
611   if (ret && gst_structure_has_field (s, "codec_data")) {
612     const GValue *val = gst_structure_get_value (s, "codec_data");
613
614     if (val)
615       gst_buffer_replace (&pad->codec_data, gst_value_get_buffer (val));
616     else if (!val && pad->codec_data)
617       gst_buffer_unref (pad->codec_data);
618   }
619
620   if (ret && mux->streamable && mux->state != GST_FLV_MUX_STATE_HEADER) {
621     if (old_codec != pad->codec || old_rate != pad->rate ||
622         old_width != pad->width || old_channels != pad->channels) {
623       pad->info_changed = TRUE;
624     }
625
626     if (old_codec_data && pad->codec_data) {
627       GstMapInfo map;
628
629       gst_buffer_map (old_codec_data, &map, GST_MAP_READ);
630       if (map.size != gst_buffer_get_size (pad->codec_data) ||
631           gst_buffer_memcmp (pad->codec_data, 0, map.data, map.size))
632         pad->info_changed = TRUE;
633
634       gst_buffer_unmap (old_codec_data, &map);
635     } else if (!old_codec_data && pad->codec_data) {
636       pad->info_changed = TRUE;
637     }
638
639     if (pad->info_changed)
640       mux->state = GST_FLV_MUX_STATE_HEADER;
641   }
642
643   if (old_codec_data)
644     gst_buffer_unref (old_codec_data);
645
646   gst_object_unref (mux);
647
648   return ret;
649 }
650
651 static void
652 gst_flv_mux_reset_pad (GstFlvMuxPad * pad)
653 {
654   GST_DEBUG_OBJECT (pad, "resetting pad");
655
656   if (pad->codec_data)
657     gst_buffer_unref (pad->codec_data);
658   pad->codec_data = NULL;
659   pad->codec = G_MAXUINT;
660   pad->rate = G_MAXUINT;
661   pad->width = G_MAXUINT;
662   pad->channels = G_MAXUINT;
663   pad->info_changed = FALSE;
664
665   gst_flv_mux_pad_flush (GST_AGGREGATOR_PAD_CAST (pad), NULL);
666 }
667
668 static GstAggregatorPad *
669 gst_flv_mux_create_new_pad (GstAggregator * agg,
670     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
671 {
672   GstElementClass *klass = GST_ELEMENT_GET_CLASS (agg);
673   GstAggregatorPad *aggpad;
674   GstFlvMux *mux = GST_FLV_MUX (agg);
675   GstFlvMuxPad *pad = NULL;
676   const gchar *name = NULL;
677   gboolean video;
678
679   if (mux->state != GST_FLV_MUX_STATE_HEADER) {
680     GST_WARNING_OBJECT (mux, "Can't request pads after writing header");
681     return NULL;
682   }
683
684   if (templ == gst_element_class_get_pad_template (klass, "audio")) {
685     if (mux->audio_pad) {
686       GST_WARNING_OBJECT (mux, "Already have an audio pad");
687       return NULL;
688     }
689     name = "audio";
690     video = FALSE;
691   } else if (templ == gst_element_class_get_pad_template (klass, "video")) {
692     if (mux->video_pad) {
693       GST_WARNING_OBJECT (mux, "Already have a video pad");
694       return NULL;
695     }
696     name = "video";
697     video = TRUE;
698   } else {
699     GST_WARNING_OBJECT (mux, "Invalid template");
700     return NULL;
701   }
702
703   aggpad =
704       GST_AGGREGATOR_CLASS (gst_flv_mux_parent_class)->create_new_pad (agg,
705       templ, name, caps);
706   if (aggpad == NULL)
707     return NULL;
708
709   pad = GST_FLV_MUX_PAD (aggpad);
710
711   gst_flv_mux_reset_pad (pad);
712
713   if (video)
714     mux->video_pad = pad;
715   else
716     mux->audio_pad = pad;
717
718   return aggpad;
719 }
720
721 static void
722 gst_flv_mux_release_pad (GstElement * element, GstPad * pad)
723 {
724   GstFlvMux *mux = GST_FLV_MUX (element);
725   GstFlvMuxPad *flvpad = GST_FLV_MUX_PAD (pad);
726
727   gst_pad_set_active (pad, FALSE);
728   gst_flv_mux_reset_pad (flvpad);
729
730   if (flvpad == mux->video_pad) {
731     mux->video_pad = NULL;
732   } else if (flvpad == mux->audio_pad) {
733     mux->audio_pad = NULL;
734   } else {
735     GST_WARNING_OBJECT (pad, "Pad is not known audio or video pad");
736   }
737
738   gst_element_remove_pad (element, pad);
739 }
740
741 static GstFlowReturn
742 gst_flv_mux_push (GstFlvMux * mux, GstBuffer * buffer)
743 {
744   GstAggregator *agg = GST_AGGREGATOR (mux);
745   GstAggregatorPad *srcpad = GST_AGGREGATOR_PAD (agg->srcpad);
746
747   if (GST_BUFFER_PTS_IS_VALID (buffer))
748     srcpad->segment.position = GST_BUFFER_PTS (buffer);
749
750   /* pushing the buffer that rewrites the header will make it no longer be the
751    * total output size in bytes, but it doesn't matter at that point */
752   mux->byte_count += gst_buffer_get_size (buffer);
753
754   return gst_aggregator_finish_buffer (GST_AGGREGATOR_CAST (mux), buffer);
755 }
756
757 static GstBuffer *
758 gst_flv_mux_create_header (GstFlvMux * mux)
759 {
760   GstBuffer *header;
761   guint8 *data;
762   gboolean have_audio;
763   gboolean have_video;
764
765   _gst_buffer_new_and_alloc (9 + 4, &header, &data);
766
767   data[0] = 'F';
768   data[1] = 'L';
769   data[2] = 'V';
770   data[3] = 0x01;               /* Version */
771
772   have_audio = (mux->audio_pad && mux->audio_pad->codec != G_MAXUINT);
773   have_video = (mux->video_pad && mux->video_pad->codec != G_MAXUINT);
774
775   data[4] = (have_audio << 2) | have_video;     /* flags */
776   GST_WRITE_UINT32_BE (data + 5, 9);    /* data offset */
777   GST_WRITE_UINT32_BE (data + 9, 0);    /* previous tag size */
778
779   return header;
780 }
781
782 static GstBuffer *
783 gst_flv_mux_preallocate_index (GstFlvMux * mux)
784 {
785   GstBuffer *tmp;
786   guint8 *data;
787   gint preallocate_size;
788
789   /* preallocate index of size:
790    *  - 'keyframes' ECMA array key: 2 + 9 = 11 bytes
791    *  - nested ECMA array header, length and end marker: 8 bytes
792    *  - 'times' and 'filepositions' keys: 22 bytes
793    *  - two strict arrays headers and lengths: 10 bytes
794    *  - each index entry: 18 bytes
795    */
796   preallocate_size = 11 + 8 + 22 + 10 + MAX_INDEX_ENTRIES * 18;
797   GST_DEBUG_OBJECT (mux, "preallocating %d bytes for the index",
798       preallocate_size);
799
800   _gst_buffer_new_and_alloc (preallocate_size, &tmp, &data);
801
802   /* prefill the space with a gstfiller: <spaces> script tag variable */
803   GST_WRITE_UINT16_BE (data, 9);        /* 9 characters */
804   memcpy (data + 2, "gstfiller", 9);
805   GST_WRITE_UINT8 (data + 11, AMF0_STRING_MARKER);      /* a string value */
806   GST_WRITE_UINT16_BE (data + 12, preallocate_size - 14);
807   memset (data + 14, ' ', preallocate_size - 14);       /* the rest is spaces */
808   return tmp;
809 }
810
811 static GstBuffer *
812 gst_flv_mux_create_number_script_value (const gchar * name, gdouble value)
813 {
814   GstBuffer *tmp;
815   guint8 *data;
816   gsize len = strlen (name);
817
818   _gst_buffer_new_and_alloc (2 + len + 1 + 8, &tmp, &data);
819
820   GST_WRITE_UINT16_BE (data, len);
821   data += 2;                    /* name length */
822   memcpy (data, name, len);
823   data += len;
824   *data++ = AMF0_NUMBER_MARKER; /* double type */
825   GST_WRITE_DOUBLE_BE (data, value);
826
827   return tmp;
828 }
829
830 static GstBuffer *
831 gst_flv_mux_create_metadata (GstFlvMux * mux)
832 {
833   const GstTagList *tags;
834   GstBuffer *script_tag, *tmp;
835   GstMapInfo map;
836   guint64 dts;
837   guint8 *data;
838   gint i, n_tags, tags_written = 0;
839
840   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
841
842   dts = mux->last_dts;
843
844   /* Timestamp must start at zero */
845   if (GST_CLOCK_STIME_IS_VALID (mux->first_timestamp)) {
846     dts -= mux->first_timestamp / GST_MSECOND;
847   }
848
849   GST_DEBUG_OBJECT (mux,
850       "Creating metadata, dts %" G_GUINT64_FORMAT ", tags = %" GST_PTR_FORMAT,
851       dts, tags);
852
853   if (dts > G_MAXUINT32) {
854     GST_LOG_OBJECT (mux,
855         "Detected rollover, timestamp will be truncated (previous:%"
856         G_GUINT64_FORMAT ", new:%u)", dts, (guint32) dts);
857   }
858
859   /* FIXME perhaps some bytewriter'ing here ... */
860
861   _gst_buffer_new_and_alloc (11, &script_tag, &data);
862
863   data[0] = 18;
864
865   /* Data size, unknown for now */
866   data[1] = 0;
867   data[2] = 0;
868   data[3] = 0;
869
870   /* Timestamp */
871   GST_WRITE_UINT24_BE (data + 4, dts);
872   data[7] = (((guint) dts) >> 24) & 0xff;
873
874   /* Stream ID */
875   data[8] = data[9] = data[10] = 0;
876
877   _gst_buffer_new_and_alloc (13, &tmp, &data);
878   data[0] = AMF0_STRING_MARKER; /* string */
879   data[1] = 0;
880   data[2] = 10;                 /* length 10 */
881   memcpy (&data[3], "onMetaData", 10);
882
883   script_tag = gst_buffer_append (script_tag, tmp);
884
885   n_tags = (tags) ? gst_tag_list_n_tags (tags) : 0;
886   _gst_buffer_new_and_alloc (5, &tmp, &data);
887   data[0] = 8;                  /* ECMA array */
888   GST_WRITE_UINT32_BE (data + 1, n_tags);
889   script_tag = gst_buffer_append (script_tag, tmp);
890
891   /* Some players expect the 'duration' to be always set. Fill it out later,
892      after querying the pads or after getting EOS */
893   if (!mux->streamable) {
894     tmp = gst_flv_mux_create_number_script_value ("duration", 86400);
895     script_tag = gst_buffer_append (script_tag, tmp);
896     tags_written++;
897
898     /* Sometimes the information about the total file size is useful for the
899        player. It will be filled later, after getting EOS */
900     tmp = gst_flv_mux_create_number_script_value ("filesize", 0);
901     script_tag = gst_buffer_append (script_tag, tmp);
902     tags_written++;
903
904     /* Preallocate space for the index to be written at EOS */
905     tmp = gst_flv_mux_preallocate_index (mux);
906     script_tag = gst_buffer_append (script_tag, tmp);
907   } else {
908     GST_DEBUG_OBJECT (mux, "not preallocating index, streamable mode");
909   }
910
911   for (i = 0; tags && i < n_tags; i++) {
912     const gchar *tag_name = gst_tag_list_nth_tag_name (tags, i);
913     if (!strcmp (tag_name, GST_TAG_DURATION)) {
914       guint64 dur;
915
916       if (!gst_tag_list_get_uint64 (tags, GST_TAG_DURATION, &dur))
917         continue;
918       mux->duration = dur;
919     } else if (!strcmp (tag_name, GST_TAG_ARTIST) ||
920         !strcmp (tag_name, GST_TAG_TITLE)) {
921       gchar *s;
922       const gchar *t = NULL;
923
924       if (!strcmp (tag_name, GST_TAG_ARTIST))
925         t = "creator";
926       else if (!strcmp (tag_name, GST_TAG_TITLE))
927         t = "title";
928
929       if (!gst_tag_list_get_string (tags, tag_name, &s))
930         continue;
931
932       _gst_buffer_new_and_alloc (2 + strlen (t) + 1 + 2 + strlen (s),
933           &tmp, &data);
934       data[0] = 0;              /* tag name length */
935       data[1] = strlen (t);
936       memcpy (&data[2], t, strlen (t));
937       data[2 + strlen (t)] = 2; /* string */
938       data[3 + strlen (t)] = (strlen (s) >> 8) & 0xff;
939       data[4 + strlen (t)] = (strlen (s)) & 0xff;
940       memcpy (&data[5 + strlen (t)], s, strlen (s));
941       script_tag = gst_buffer_append (script_tag, tmp);
942
943       g_free (s);
944       tags_written++;
945     }
946   }
947
948   if (!mux->streamable && mux->duration == GST_CLOCK_TIME_NONE) {
949     GList *l;
950     guint64 dur;
951
952     for (l = GST_ELEMENT_CAST (mux)->sinkpads; l; l = l->next) {
953       GstFlvMuxPad *pad = GST_FLV_MUX_PAD (l->data);
954
955       if (gst_pad_peer_query_duration (GST_PAD (pad), GST_FORMAT_TIME,
956               (gint64 *) & dur) && dur != GST_CLOCK_TIME_NONE) {
957         if (mux->duration == GST_CLOCK_TIME_NONE)
958           mux->duration = dur;
959         else
960           mux->duration = MAX (dur, mux->duration);
961       }
962     }
963   }
964
965   if (!mux->streamable && mux->duration != GST_CLOCK_TIME_NONE) {
966     gdouble d;
967     GstMapInfo map;
968
969     d = gst_guint64_to_gdouble (mux->duration);
970     d /= (gdouble) GST_SECOND;
971
972     GST_DEBUG_OBJECT (mux, "determined the duration to be %f", d);
973     gst_buffer_map (script_tag, &map, GST_MAP_WRITE);
974     GST_WRITE_DOUBLE_BE (map.data + 29 + 2 + 8 + 1, d);
975     gst_buffer_unmap (script_tag, &map);
976   }
977
978   if (mux->video_pad && mux->video_pad->codec != G_MAXUINT) {
979     GstCaps *caps = NULL;
980
981     if (mux->video_pad)
982       caps = gst_pad_get_current_caps (GST_PAD (mux->video_pad));
983
984     if (caps != NULL) {
985       GstStructure *s;
986       gint size;
987       gint num, den;
988
989       GST_DEBUG_OBJECT (mux, "putting videocodecid %d in the metadata",
990           mux->video_pad->codec);
991
992       tmp = gst_flv_mux_create_number_script_value ("videocodecid",
993           mux->video_pad->codec);
994       script_tag = gst_buffer_append (script_tag, tmp);
995       tags_written++;
996
997       s = gst_caps_get_structure (caps, 0);
998       gst_caps_unref (caps);
999
1000       if (gst_structure_get_int (s, "width", &size)) {
1001         GST_DEBUG_OBJECT (mux, "putting width %d in the metadata", size);
1002
1003         tmp = gst_flv_mux_create_number_script_value ("width", size);
1004         script_tag = gst_buffer_append (script_tag, tmp);
1005         tags_written++;
1006       }
1007
1008       if (gst_structure_get_int (s, "height", &size)) {
1009         GST_DEBUG_OBJECT (mux, "putting height %d in the metadata", size);
1010
1011         tmp = gst_flv_mux_create_number_script_value ("height", size);
1012         script_tag = gst_buffer_append (script_tag, tmp);
1013         tags_written++;
1014       }
1015
1016       if (gst_structure_get_fraction (s, "pixel-aspect-ratio", &num, &den)) {
1017         gdouble d;
1018
1019         d = num;
1020         GST_DEBUG_OBJECT (mux, "putting AspectRatioX %f in the metadata", d);
1021
1022         tmp = gst_flv_mux_create_number_script_value ("AspectRatioX", d);
1023         script_tag = gst_buffer_append (script_tag, tmp);
1024         tags_written++;
1025
1026         d = den;
1027         GST_DEBUG_OBJECT (mux, "putting AspectRatioY %f in the metadata", d);
1028
1029         tmp = gst_flv_mux_create_number_script_value ("AspectRatioY", d);
1030         script_tag = gst_buffer_append (script_tag, tmp);
1031         tags_written++;
1032       }
1033
1034       if (gst_structure_get_fraction (s, "framerate", &num, &den)) {
1035         gdouble d;
1036
1037         gst_util_fraction_to_double (num, den, &d);
1038         GST_DEBUG_OBJECT (mux, "putting framerate %f in the metadata", d);
1039
1040         tmp = gst_flv_mux_create_number_script_value ("framerate", d);
1041         script_tag = gst_buffer_append (script_tag, tmp);
1042         tags_written++;
1043       }
1044
1045       GST_DEBUG_OBJECT (mux, "putting videodatarate %u KB/s in the metadata",
1046           mux->video_pad->bitrate / 1024);
1047       tmp = gst_flv_mux_create_number_script_value ("videodatarate",
1048           mux->video_pad->bitrate / 1024);
1049       script_tag = gst_buffer_append (script_tag, tmp);
1050       tags_written++;
1051     }
1052   }
1053
1054   if (mux->audio_pad && mux->audio_pad->codec != G_MAXUINT) {
1055     GST_DEBUG_OBJECT (mux, "putting audiocodecid %d in the metadata",
1056         mux->audio_pad->codec);
1057
1058     tmp = gst_flv_mux_create_number_script_value ("audiocodecid",
1059         mux->audio_pad->codec);
1060     script_tag = gst_buffer_append (script_tag, tmp);
1061     tags_written++;
1062
1063     GST_DEBUG_OBJECT (mux, "putting audiodatarate %u KB/s in the metadata",
1064         mux->audio_pad->bitrate / 1024);
1065     tmp = gst_flv_mux_create_number_script_value ("audiodatarate",
1066         mux->audio_pad->bitrate / 1024);
1067     script_tag = gst_buffer_append (script_tag, tmp);
1068     tags_written++;
1069   }
1070
1071   _gst_buffer_new_and_alloc (2 + 15 + 1 + 2 + strlen (mux->metadatacreator),
1072       &tmp, &data);
1073   data[0] = 0;                  /* 15 bytes name */
1074   data[1] = 15;
1075   memcpy (&data[2], "metadatacreator", 15);
1076   data[17] = 2;                 /* string */
1077   data[18] = (strlen (mux->metadatacreator) >> 8) & 0xff;
1078   data[19] = (strlen (mux->metadatacreator)) & 0xff;
1079   memcpy (&data[20], mux->metadatacreator, strlen (mux->metadatacreator));
1080   script_tag = gst_buffer_append (script_tag, tmp);
1081   tags_written++;
1082
1083   _gst_buffer_new_and_alloc (2 + 7 + 1 + 2 + strlen (mux->encoder),
1084       &tmp, &data);
1085   data[0] = 0;                  /* 7 bytes name */
1086   data[1] = 7;
1087   memcpy (&data[2], "encoder", 7);
1088   data[9] = 2;                  /* string */
1089   data[10] = (strlen (mux->encoder) >> 8) & 0xff;
1090   data[11] = (strlen (mux->encoder)) & 0xff;
1091   memcpy (&data[12], mux->encoder, strlen (mux->encoder));
1092   script_tag = gst_buffer_append (script_tag, tmp);
1093   tags_written++;
1094
1095   {
1096     time_t secs;
1097     struct tm tm;
1098     gchar *s;
1099     static const gchar *weekdays[] = {
1100       "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1101     };
1102     static const gchar *months[] = {
1103       "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
1104       "Aug", "Sep", "Oct", "Nov", "Dec"
1105     };
1106
1107     secs = g_get_real_time () / G_USEC_PER_SEC;
1108 #ifdef HAVE_GMTIME_R
1109     gmtime_r (&secs, &tm);
1110 #else
1111     tm = *gmtime (&secs);
1112 #endif
1113
1114     s = g_strdup_printf ("%s %s %d %02d:%02d:%02d %d", weekdays[tm.tm_wday],
1115         months[tm.tm_mon], tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
1116         tm.tm_year + 1900);
1117
1118     _gst_buffer_new_and_alloc (2 + 12 + 1 + 2 + strlen (s), &tmp, &data);
1119     data[0] = 0;                /* 12 bytes name */
1120     data[1] = 12;
1121     memcpy (&data[2], "creationdate", 12);
1122     data[14] = 2;               /* string */
1123     data[15] = (strlen (s) >> 8) & 0xff;
1124     data[16] = (strlen (s)) & 0xff;
1125     memcpy (&data[17], s, strlen (s));
1126     script_tag = gst_buffer_append (script_tag, tmp);
1127
1128     g_free (s);
1129     tags_written++;
1130   }
1131
1132   if (!tags_written) {
1133     gst_buffer_unref (script_tag);
1134     script_tag = NULL;
1135     goto exit;
1136   }
1137
1138   _gst_buffer_new_and_alloc (2 + 0 + 1, &tmp, &data);
1139   data[0] = 0;                  /* 0 byte size */
1140   data[1] = 0;
1141   data[2] = 9;                  /* end marker */
1142   script_tag = gst_buffer_append (script_tag, tmp);
1143
1144
1145   _gst_buffer_new_and_alloc (4, &tmp, &data);
1146   GST_WRITE_UINT32_BE (data, gst_buffer_get_size (script_tag));
1147   script_tag = gst_buffer_append (script_tag, tmp);
1148
1149   gst_buffer_map (script_tag, &map, GST_MAP_WRITE);
1150   map.data[1] = ((gst_buffer_get_size (script_tag) - 11 - 4) >> 16) & 0xff;
1151   map.data[2] = ((gst_buffer_get_size (script_tag) - 11 - 4) >> 8) & 0xff;
1152   map.data[3] = ((gst_buffer_get_size (script_tag) - 11 - 4) >> 0) & 0xff;
1153
1154   GST_WRITE_UINT32_BE (map.data + 11 + 13 + 1, tags_written);
1155   gst_buffer_unmap (script_tag, &map);
1156
1157 exit:
1158   return script_tag;
1159 }
1160
1161 static GstBuffer *
1162 gst_flv_mux_buffer_to_tag_internal (GstFlvMux * mux, GstBuffer * buffer,
1163     GstFlvMuxPad * pad, gboolean is_codec_data)
1164 {
1165   GstBuffer *tag;
1166   GstMapInfo map;
1167   guint size;
1168   guint64 pts, dts, cts;
1169   guint8 *data, *bdata = NULL;
1170   gsize bsize = 0;
1171
1172   if (!GST_CLOCK_STIME_IS_VALID (pad->dts)) {
1173     pts = dts = pad->last_timestamp / GST_MSECOND;
1174   } else {
1175     pts = pad->pts / GST_MSECOND;
1176     dts = pad->dts / GST_MSECOND;
1177   }
1178
1179   /* We prevent backwards timestamps because they confuse librtmp,
1180    * it expects timestamps to go forward not only inside one stream, but
1181    * also between the audio & video streams.
1182    */
1183   if (dts < mux->last_dts) {
1184     GST_WARNING_OBJECT (pad, "Got backwards dts! (%" GST_TIME_FORMAT
1185         " < %" GST_TIME_FORMAT ")", GST_TIME_ARGS (dts * GST_MSECOND),
1186         GST_TIME_ARGS (mux->last_dts * GST_MSECOND));
1187     dts = mux->last_dts;
1188   }
1189   mux->last_dts = dts;
1190
1191
1192   /* Be safe in case TS are buggy */
1193   if (pts > dts)
1194     cts = pts - dts;
1195   else
1196     cts = 0;
1197
1198   /* Timestamp must start at zero */
1199   if (GST_CLOCK_STIME_IS_VALID (mux->first_timestamp)) {
1200     dts -= mux->first_timestamp / GST_MSECOND;
1201     pts = dts + cts;
1202   }
1203
1204   GST_LOG_OBJECT (mux,
1205       "got pts %" G_GUINT64_FORMAT " dts %" G_GUINT64_FORMAT " cts %"
1206       G_GUINT64_FORMAT, pts, dts, cts);
1207
1208   if (dts > G_MAXUINT32) {
1209     GST_LOG_OBJECT (mux,
1210         "Detected rollover, timestamp will be truncated (previous:%"
1211         G_GUINT64_FORMAT ", new:%u)", dts, (guint32) dts);
1212   }
1213
1214   if (buffer != NULL) {
1215     gst_buffer_map (buffer, &map, GST_MAP_READ);
1216     bdata = map.data;
1217     bsize = map.size;
1218   }
1219
1220   size = 11;
1221   if (mux->video_pad == pad) {
1222     size += 1;
1223     if (pad->codec == 7)
1224       size += 4 + bsize;
1225     else
1226       size += bsize;
1227   } else {
1228     size += 1;
1229     if (pad->codec == 10)
1230       size += 1 + bsize;
1231     else
1232       size += bsize;
1233   }
1234   size += 4;
1235
1236   _gst_buffer_new_and_alloc (size, &tag, &data);
1237   memset (data, 0, size);
1238
1239   data[0] = (mux->video_pad == pad) ? 9 : 8;
1240
1241   data[1] = ((size - 11 - 4) >> 16) & 0xff;
1242   data[2] = ((size - 11 - 4) >> 8) & 0xff;
1243   data[3] = ((size - 11 - 4) >> 0) & 0xff;
1244
1245
1246   GST_WRITE_UINT24_BE (data + 4, dts);
1247   data[7] = (((guint) dts) >> 24) & 0xff;
1248
1249   data[8] = data[9] = data[10] = 0;
1250
1251   if (mux->video_pad == pad) {
1252     if (buffer && GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
1253       data[11] |= 2 << 4;
1254     else
1255       data[11] |= 1 << 4;
1256
1257     data[11] |= pad->codec & 0x0f;
1258
1259     if (pad->codec == 7) {
1260       if (is_codec_data) {
1261         data[12] = 0;
1262         GST_WRITE_UINT24_BE (data + 13, 0);
1263       } else if (bsize == 0) {
1264         /* AVC end of sequence */
1265         data[12] = 2;
1266         GST_WRITE_UINT24_BE (data + 13, 0);
1267       } else {
1268         /* ACV NALU */
1269         data[12] = 1;
1270         GST_WRITE_UINT24_BE (data + 13, cts);
1271       }
1272       memcpy (data + 11 + 1 + 4, bdata, bsize);
1273     } else {
1274       memcpy (data + 11 + 1, bdata, bsize);
1275     }
1276   } else {
1277     data[11] |= (pad->codec << 4) & 0xf0;
1278     data[11] |= (pad->rate << 2) & 0x0c;
1279     data[11] |= (pad->width << 1) & 0x02;
1280     data[11] |= (pad->channels << 0) & 0x01;
1281
1282     GST_DEBUG_OBJECT (mux, "Creating byte %02x with "
1283         "codec:%d, rate:%d, width:%d, channels:%d",
1284         data[11], pad->codec, pad->rate, pad->width, pad->channels);
1285
1286     if (pad->codec == 10) {
1287       data[12] = is_codec_data ? 0 : 1;
1288
1289       memcpy (data + 11 + 1 + 1, bdata, bsize);
1290     } else {
1291       memcpy (data + 11 + 1, bdata, bsize);
1292     }
1293   }
1294
1295   if (buffer)
1296     gst_buffer_unmap (buffer, &map);
1297
1298   GST_WRITE_UINT32_BE (data + size - 4, size - 4);
1299
1300   GST_BUFFER_PTS (tag) = GST_CLOCK_TIME_NONE;
1301   GST_BUFFER_DTS (tag) = GST_CLOCK_TIME_NONE;
1302   GST_BUFFER_DURATION (tag) = GST_CLOCK_TIME_NONE;
1303
1304   if (buffer) {
1305     /* if we are streamable we copy over timestamps and offsets,
1306        if not just copy the offsets */
1307     if (mux->streamable) {
1308       GstClockTime timestamp = GST_CLOCK_TIME_NONE;
1309
1310       if (gst_segment_to_running_time_full (&GST_AGGREGATOR_PAD (pad)->segment,
1311               GST_FORMAT_TIME, GST_BUFFER_DTS_OR_PTS (buffer),
1312               &timestamp) == 1) {
1313         GST_BUFFER_PTS (tag) = timestamp;
1314         GST_BUFFER_DURATION (tag) = GST_BUFFER_DURATION (buffer);
1315       }
1316       GST_BUFFER_OFFSET (tag) = GST_BUFFER_OFFSET_NONE;
1317       GST_BUFFER_OFFSET_END (tag) = GST_BUFFER_OFFSET_NONE;
1318     } else {
1319       GST_BUFFER_OFFSET (tag) = GST_BUFFER_OFFSET (buffer);
1320       GST_BUFFER_OFFSET_END (tag) = GST_BUFFER_OFFSET_END (buffer);
1321     }
1322
1323     /* mark the buffer if it's an audio buffer and there's also video being muxed
1324      * or it's a video interframe */
1325     if (mux->video_pad == pad &&
1326         GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
1327       GST_BUFFER_FLAG_SET (tag, GST_BUFFER_FLAG_DELTA_UNIT);
1328   } else {
1329     GST_BUFFER_FLAG_SET (tag, GST_BUFFER_FLAG_DELTA_UNIT);
1330     GST_BUFFER_OFFSET (tag) = GST_BUFFER_OFFSET_END (tag) =
1331         GST_BUFFER_OFFSET_NONE;
1332   }
1333
1334   return tag;
1335 }
1336
1337 static inline GstBuffer *
1338 gst_flv_mux_buffer_to_tag (GstFlvMux * mux, GstBuffer * buffer,
1339     GstFlvMuxPad * pad)
1340 {
1341   return gst_flv_mux_buffer_to_tag_internal (mux, buffer, pad, FALSE);
1342 }
1343
1344 static inline GstBuffer *
1345 gst_flv_mux_codec_data_buffer_to_tag (GstFlvMux * mux, GstBuffer * buffer,
1346     GstFlvMuxPad * pad)
1347 {
1348   return gst_flv_mux_buffer_to_tag_internal (mux, buffer, pad, TRUE);
1349 }
1350
1351 static inline GstBuffer *
1352 gst_flv_mux_eos_to_tag (GstFlvMux * mux, GstFlvMuxPad * pad)
1353 {
1354   return gst_flv_mux_buffer_to_tag_internal (mux, NULL, pad, FALSE);
1355 }
1356
1357 static void
1358 gst_flv_mux_put_buffer_in_streamheader (GValue * streamheader,
1359     GstBuffer * buffer)
1360 {
1361   GValue value = { 0 };
1362   GstBuffer *buf;
1363
1364   g_value_init (&value, GST_TYPE_BUFFER);
1365   buf = gst_buffer_copy (buffer);
1366   gst_value_set_buffer (&value, buf);
1367   gst_buffer_unref (buf);
1368   gst_value_array_append_value (streamheader, &value);
1369   g_value_unset (&value);
1370 }
1371
1372 static GstCaps *
1373 gst_flv_mux_prepare_src_caps (GstFlvMux * mux, GstBuffer ** header_buf,
1374     GstBuffer ** metadata_buf, GstBuffer ** video_codec_data_buf,
1375     GstBuffer ** audio_codec_data_buf)
1376 {
1377   GstBuffer *header, *metadata;
1378   GstBuffer *video_codec_data, *audio_codec_data;
1379   GstCaps *caps;
1380   GstStructure *structure;
1381   GValue streamheader = { 0 };
1382   GList *l;
1383
1384   header = gst_flv_mux_create_header (mux);
1385   metadata = gst_flv_mux_create_metadata (mux);
1386   video_codec_data = NULL;
1387   audio_codec_data = NULL;
1388
1389   for (l = GST_ELEMENT_CAST (mux)->sinkpads; l != NULL; l = l->next) {
1390     GstFlvMuxPad *pad = l->data;
1391
1392     /* Get H.264 and AAC codec data, if present */
1393     if (pad && mux->video_pad == pad && pad->codec == 7) {
1394       if (pad->codec_data == NULL)
1395         GST_WARNING_OBJECT (mux, "Codec data for video stream not found, "
1396             "output might not be playable");
1397       else
1398         video_codec_data =
1399             gst_flv_mux_codec_data_buffer_to_tag (mux, pad->codec_data, pad);
1400     } else if (pad && mux->audio_pad == pad && pad->codec == 10) {
1401       if (pad->codec_data == NULL)
1402         GST_WARNING_OBJECT (mux, "Codec data for audio stream not found, "
1403             "output might not be playable");
1404       else
1405         audio_codec_data =
1406             gst_flv_mux_codec_data_buffer_to_tag (mux, pad->codec_data, pad);
1407     }
1408   }
1409
1410   /* mark buffers that will go in the streamheader */
1411   GST_BUFFER_FLAG_SET (header, GST_BUFFER_FLAG_HEADER);
1412   GST_BUFFER_FLAG_SET (metadata, GST_BUFFER_FLAG_HEADER);
1413   if (video_codec_data != NULL) {
1414     GST_BUFFER_FLAG_SET (video_codec_data, GST_BUFFER_FLAG_HEADER);
1415     /* mark as a delta unit, so downstream will not try to synchronize on that
1416      * buffer - to actually start playback you need a real video keyframe */
1417     GST_BUFFER_FLAG_SET (video_codec_data, GST_BUFFER_FLAG_DELTA_UNIT);
1418   }
1419   if (audio_codec_data != NULL) {
1420     GST_BUFFER_FLAG_SET (audio_codec_data, GST_BUFFER_FLAG_HEADER);
1421   }
1422
1423   /* put buffers in streamheader */
1424   g_value_init (&streamheader, GST_TYPE_ARRAY);
1425   gst_flv_mux_put_buffer_in_streamheader (&streamheader, header);
1426   gst_flv_mux_put_buffer_in_streamheader (&streamheader, metadata);
1427   if (video_codec_data != NULL)
1428     gst_flv_mux_put_buffer_in_streamheader (&streamheader, video_codec_data);
1429   if (audio_codec_data != NULL)
1430     gst_flv_mux_put_buffer_in_streamheader (&streamheader, audio_codec_data);
1431
1432   /* create the caps and put the streamheader in them */
1433   caps = gst_caps_new_empty_simple ("video/x-flv");
1434   structure = gst_caps_get_structure (caps, 0);
1435   gst_structure_set_value (structure, "streamheader", &streamheader);
1436   g_value_unset (&streamheader);
1437
1438   if (header_buf) {
1439     *header_buf = header;
1440   } else {
1441     gst_buffer_unref (header);
1442   }
1443
1444   if (metadata_buf) {
1445     *metadata_buf = metadata;
1446   } else {
1447     gst_buffer_unref (metadata);
1448   }
1449
1450   if (video_codec_data_buf) {
1451     *video_codec_data_buf = video_codec_data;
1452   } else if (video_codec_data) {
1453     gst_buffer_unref (video_codec_data);
1454   }
1455
1456   if (audio_codec_data_buf) {
1457     *audio_codec_data_buf = audio_codec_data;
1458   } else if (audio_codec_data) {
1459     gst_buffer_unref (audio_codec_data);
1460   }
1461
1462   return caps;
1463 }
1464
1465 static GstFlowReturn
1466 gst_flv_mux_write_header (GstFlvMux * mux)
1467 {
1468   GstBuffer *header, *metadata;
1469   GstBuffer *video_codec_data, *audio_codec_data;
1470   GstCaps *caps;
1471   GstFlowReturn ret;
1472
1473   header = metadata = video_codec_data = audio_codec_data = NULL;
1474
1475   /* if not streaming, check if downstream is seekable */
1476   if (!mux->streamable) {
1477     gboolean seekable;
1478     GstQuery *query;
1479
1480     query = gst_query_new_seeking (GST_FORMAT_BYTES);
1481     if (gst_pad_peer_query (mux->srcpad, query)) {
1482       gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1483       GST_INFO_OBJECT (mux, "downstream is %sseekable", seekable ? "" : "not ");
1484     } else {
1485       /* have to assume seeking is supported if query not handled downstream */
1486       GST_WARNING_OBJECT (mux, "downstream did not handle seeking query");
1487       seekable = FALSE;
1488     }
1489     if (!seekable) {
1490       mux->streamable = TRUE;
1491       g_object_notify (G_OBJECT (mux), "streamable");
1492       GST_WARNING_OBJECT (mux, "downstream is not seekable, but "
1493           "streamable=false. Will ignore that and create streamable output "
1494           "instead");
1495     }
1496     gst_query_unref (query);
1497   }
1498
1499   if (mux->streamable && mux->sent_header) {
1500     GstBuffer **video_codec_data_p = NULL, **audio_codec_data_p = NULL;
1501
1502     if (mux->video_pad && mux->video_pad->info_changed)
1503       video_codec_data_p = &video_codec_data;
1504     if (mux->audio_pad && mux->audio_pad->info_changed)
1505       audio_codec_data_p = &audio_codec_data;
1506
1507     caps = gst_flv_mux_prepare_src_caps (mux,
1508         NULL, NULL, video_codec_data_p, audio_codec_data_p);
1509   } else {
1510     caps = gst_flv_mux_prepare_src_caps (mux,
1511         &header, &metadata, &video_codec_data, &audio_codec_data);
1512   }
1513
1514   gst_aggregator_set_src_caps (GST_AGGREGATOR_CAST (mux), caps);
1515
1516   gst_caps_unref (caps);
1517
1518   /* push the header buffer, the metadata and the codec info, if any */
1519   if (header != NULL) {
1520     ret = gst_flv_mux_push (mux, header);
1521     if (ret != GST_FLOW_OK)
1522       goto failure_header;
1523     mux->sent_header = TRUE;
1524   }
1525   if (metadata != NULL) {
1526     ret = gst_flv_mux_push (mux, metadata);
1527     if (ret != GST_FLOW_OK)
1528       goto failure_metadata;
1529     mux->new_tags = FALSE;
1530   }
1531   if (video_codec_data != NULL) {
1532     ret = gst_flv_mux_push (mux, video_codec_data);
1533     if (ret != GST_FLOW_OK)
1534       goto failure_video_codec_data;
1535     mux->video_pad->info_changed = FALSE;
1536   }
1537   if (audio_codec_data != NULL) {
1538     ret = gst_flv_mux_push (mux, audio_codec_data);
1539     if (ret != GST_FLOW_OK)
1540       goto failure_audio_codec_data;
1541     mux->audio_pad->info_changed = FALSE;
1542   }
1543   return GST_FLOW_OK;
1544
1545 failure_header:
1546   gst_buffer_unref (metadata);
1547
1548 failure_metadata:
1549   if (video_codec_data != NULL)
1550     gst_buffer_unref (video_codec_data);
1551
1552 failure_video_codec_data:
1553   if (audio_codec_data != NULL)
1554     gst_buffer_unref (audio_codec_data);
1555
1556 failure_audio_codec_data:
1557   return ret;
1558 }
1559
1560 static GstClockTime
1561 gst_flv_mux_segment_to_running_time (const GstSegment * segment, GstClockTime t)
1562 {
1563   /* we can get a dts before the segment, if dts < pts and pts is inside
1564    * the segment, so we consider early times as 0 */
1565   if (t < segment->start)
1566     return 0;
1567   return gst_segment_to_running_time (segment, GST_FORMAT_TIME, t);
1568 }
1569
1570 static void
1571 gst_flv_mux_update_index (GstFlvMux * mux, GstBuffer * buffer,
1572     GstFlvMuxPad * pad)
1573 {
1574   /*
1575    * Add the tag byte offset and to the index if it's a valid seek point, which
1576    * means it's either a video keyframe or if there is no video pad (in that
1577    * case every FLV tag is a valid seek point)
1578    */
1579   if (mux->video_pad == pad &&
1580       GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
1581     return;
1582
1583   if (GST_BUFFER_PTS_IS_VALID (buffer)) {
1584     GstFlvMuxIndexEntry *entry = g_slice_new (GstFlvMuxIndexEntry);
1585     GstClockTime pts =
1586         gst_flv_mux_segment_to_running_time (&GST_AGGREGATOR_PAD
1587         (pad)->segment, GST_BUFFER_PTS (buffer));
1588     entry->position = mux->byte_count;
1589     entry->time = gst_guint64_to_gdouble (pts) / GST_SECOND;
1590     mux->index = g_list_prepend (mux->index, entry);
1591   }
1592 }
1593
1594 static GstFlowReturn
1595 gst_flv_mux_write_buffer (GstFlvMux * mux, GstFlvMuxPad * pad,
1596     GstBuffer * buffer)
1597 {
1598   GstBuffer *tag;
1599   GstFlowReturn ret;
1600   GstClockTime dts =
1601       gst_flv_mux_segment_to_running_time (&GST_AGGREGATOR_PAD (pad)->segment,
1602       GST_BUFFER_DTS (buffer));
1603
1604   /* clipping function arranged for running_time */
1605
1606   if (!mux->streamable)
1607     gst_flv_mux_update_index (mux, buffer, pad);
1608
1609   tag = gst_flv_mux_buffer_to_tag (mux, buffer, pad);
1610
1611   gst_buffer_unref (buffer);
1612
1613   ret = gst_flv_mux_push (mux, tag);
1614
1615   if (ret == GST_FLOW_OK && GST_CLOCK_TIME_IS_VALID (dts))
1616     pad->last_timestamp = dts;
1617
1618
1619   return ret;
1620 }
1621
1622 static guint64
1623 gst_flv_mux_determine_duration (GstFlvMux * mux)
1624 {
1625   GList *l;
1626   GstClockTime duration = GST_CLOCK_TIME_NONE;
1627
1628   GST_DEBUG_OBJECT (mux, "trying to determine the duration "
1629       "from pad timestamps");
1630
1631   for (l = GST_ELEMENT_CAST (mux)->sinkpads; l != NULL; l = l->next) {
1632     GstFlvMuxPad *pad = GST_FLV_MUX_PAD (l->data);
1633
1634     if (pad && (pad->last_timestamp != GST_CLOCK_TIME_NONE)) {
1635       if (duration == GST_CLOCK_TIME_NONE)
1636         duration = pad->last_timestamp;
1637       else
1638         duration = MAX (duration, pad->last_timestamp);
1639     }
1640   }
1641
1642   return duration;
1643 }
1644
1645 static gboolean
1646 gst_flv_mux_are_all_pads_eos (GstFlvMux * mux)
1647 {
1648   GList *l;
1649
1650   for (l = GST_ELEMENT_CAST (mux)->sinkpads; l; l = l->next) {
1651     GstFlvMuxPad *pad = GST_FLV_MUX_PAD (l->data);
1652
1653     if (!gst_aggregator_pad_is_eos (GST_AGGREGATOR_PAD (pad)))
1654       return FALSE;
1655   }
1656   return TRUE;
1657 }
1658
1659 static GstFlowReturn
1660 gst_flv_mux_write_eos (GstFlvMux * mux)
1661 {
1662   GstBuffer *tag;
1663
1664   if (mux->video_pad == NULL)
1665     return GST_FLOW_OK;
1666
1667   tag = gst_flv_mux_eos_to_tag (mux, mux->video_pad);
1668
1669   return gst_flv_mux_push (mux, tag);
1670 }
1671
1672 static GstFlowReturn
1673 gst_flv_mux_rewrite_header (GstFlvMux * mux)
1674 {
1675   GstBuffer *rewrite, *index, *tmp;
1676   GstEvent *event;
1677   guint8 *data;
1678   gdouble d;
1679   GList *l;
1680   guint32 index_len, allocate_size;
1681   guint32 i, index_skip;
1682   GstSegment segment;
1683   GstClockTime dur;
1684
1685   if (mux->streamable)
1686     return GST_FLOW_OK;
1687
1688   /* seek back to the preallocated index space */
1689   gst_segment_init (&segment, GST_FORMAT_BYTES);
1690   segment.start = segment.time = 13 + 29;
1691   event = gst_event_new_segment (&segment);
1692   if (!gst_pad_push_event (mux->srcpad, event)) {
1693     GST_WARNING_OBJECT (mux, "Seek to rewrite header failed");
1694     return GST_FLOW_OK;
1695   }
1696
1697   /* determine duration now based on our own timestamping,
1698    * so that it is likely many times better and consistent
1699    * than whatever obtained by some query */
1700   dur = gst_flv_mux_determine_duration (mux);
1701   if (dur != GST_CLOCK_TIME_NONE)
1702     mux->duration = dur;
1703
1704   /* rewrite the duration tag */
1705   d = gst_guint64_to_gdouble (mux->duration);
1706   d /= (gdouble) GST_SECOND;
1707
1708   GST_DEBUG_OBJECT (mux, "determined the final duration to be %f", d);
1709
1710   rewrite = gst_flv_mux_create_number_script_value ("duration", d);
1711
1712   /* rewrite the filesize tag */
1713   d = gst_guint64_to_gdouble (mux->byte_count);
1714
1715   GST_DEBUG_OBJECT (mux, "putting total filesize %f in the metadata", d);
1716
1717   tmp = gst_flv_mux_create_number_script_value ("filesize", d);
1718   rewrite = gst_buffer_append (rewrite, tmp);
1719
1720   if (!mux->index) {
1721     /* no index, so push buffer and return */
1722     return gst_flv_mux_push (mux, rewrite);
1723   }
1724
1725   /* rewrite the index */
1726   mux->index = g_list_reverse (mux->index);
1727   index_len = g_list_length (mux->index);
1728
1729   /* We write at most MAX_INDEX_ENTRIES elements */
1730   if (index_len > MAX_INDEX_ENTRIES) {
1731     index_skip = 1 + index_len / MAX_INDEX_ENTRIES;
1732     index_len = (index_len + index_skip - 1) / index_skip;
1733   } else {
1734     index_skip = 1;
1735   }
1736
1737   GST_DEBUG_OBJECT (mux, "Index length is %d", index_len);
1738   /* see size calculation in gst_flv_mux_preallocate_index */
1739   allocate_size = 11 + 8 + 22 + 10 + index_len * 18;
1740   GST_DEBUG_OBJECT (mux, "Allocating %d bytes for index", allocate_size);
1741   _gst_buffer_new_and_alloc (allocate_size, &index, &data);
1742
1743   GST_WRITE_UINT16_BE (data, 9);        /* the 'keyframes' key */
1744   memcpy (data + 2, "keyframes", 9);
1745   GST_WRITE_UINT8 (data + 11, 8);       /* nested ECMA array */
1746   GST_WRITE_UINT32_BE (data + 12, 2);   /* two elements */
1747   GST_WRITE_UINT16_BE (data + 16, 5);   /* first string key: 'times' */
1748   memcpy (data + 18, "times", 5);
1749   GST_WRITE_UINT8 (data + 23, 10);      /* strict array */
1750   GST_WRITE_UINT32_BE (data + 24, index_len);
1751   data += 28;
1752
1753   /* the keyframes' times */
1754   for (i = 0, l = mux->index; l; l = l->next, i++) {
1755     GstFlvMuxIndexEntry *entry = l->data;
1756
1757     if (i % index_skip != 0)
1758       continue;
1759     GST_WRITE_UINT8 (data, 0);  /* numeric (aka double) */
1760     GST_WRITE_DOUBLE_BE (data + 1, entry->time);
1761     data += 9;
1762   }
1763
1764   GST_WRITE_UINT16_BE (data, 13);       /* second string key: 'filepositions' */
1765   memcpy (data + 2, "filepositions", 13);
1766   GST_WRITE_UINT8 (data + 15, 10);      /* strict array */
1767   GST_WRITE_UINT32_BE (data + 16, index_len);
1768   data += 20;
1769
1770   /* the keyframes' file positions */
1771   for (i = 0, l = mux->index; l; l = l->next, i++) {
1772     GstFlvMuxIndexEntry *entry = l->data;
1773
1774     if (i % index_skip != 0)
1775       continue;
1776     GST_WRITE_UINT8 (data, 0);
1777     GST_WRITE_DOUBLE_BE (data + 1, entry->position);
1778     data += 9;
1779   }
1780
1781   GST_WRITE_UINT24_BE (data, 9);        /* finish the ECMA array */
1782
1783   /* If there is space left in the prefilled area, reinsert the filler.
1784      There is at least 18  bytes free, so it will always fit. */
1785   if (index_len < MAX_INDEX_ENTRIES) {
1786     GstBuffer *tmp;
1787     guint8 *data;
1788     guint32 remaining_filler_size;
1789
1790     _gst_buffer_new_and_alloc (14, &tmp, &data);
1791     GST_WRITE_UINT16_BE (data, 9);
1792     memcpy (data + 2, "gstfiller", 9);
1793     GST_WRITE_UINT8 (data + 11, 2);     /* string */
1794
1795     /* There is 18 bytes per remaining index entry minus what is used for
1796      * the'gstfiller' key. The rest is already filled with spaces, so just need
1797      * to update length. */
1798     remaining_filler_size = (MAX_INDEX_ENTRIES - index_len) * 18 - 14;
1799     GST_DEBUG_OBJECT (mux, "Remaining filler size is %d bytes",
1800         remaining_filler_size);
1801     GST_WRITE_UINT16_BE (data + 12, remaining_filler_size);
1802     index = gst_buffer_append (index, tmp);
1803   }
1804
1805   rewrite = gst_buffer_append (rewrite, index);
1806
1807   return gst_flv_mux_push (mux, rewrite);
1808 }
1809
1810 static GstFlvMuxPad *
1811 gst_flv_mux_find_best_pad (GstAggregator * aggregator, GstClockTime * ts)
1812 {
1813   GstAggregatorPad *apad;
1814   GstFlvMuxPad *pad, *best = NULL;
1815   GList *l;
1816   GstBuffer *buffer;
1817   GstClockTime best_ts = GST_CLOCK_TIME_NONE;
1818
1819   for (l = GST_ELEMENT_CAST (aggregator)->sinkpads; l; l = l->next) {
1820     apad = GST_AGGREGATOR_PAD (l->data);
1821     pad = GST_FLV_MUX_PAD (l->data);
1822     buffer = gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD (pad));
1823     if (!buffer)
1824       continue;
1825     if (best_ts == GST_CLOCK_TIME_NONE) {
1826       best = pad;
1827       best_ts = gst_flv_mux_segment_to_running_time (&apad->segment,
1828           GST_BUFFER_DTS_OR_PTS (buffer));
1829     } else if (GST_BUFFER_DTS_OR_PTS (buffer) != GST_CLOCK_TIME_NONE) {
1830       gint64 t = gst_flv_mux_segment_to_running_time (&apad->segment,
1831           GST_BUFFER_DTS_OR_PTS (buffer));
1832       if (t < best_ts) {
1833         best = pad;
1834         best_ts = t;
1835       }
1836     }
1837     gst_buffer_unref (buffer);
1838   }
1839   GST_DEBUG_OBJECT (aggregator,
1840       "Best pad found with %" GST_TIME_FORMAT ": %" GST_PTR_FORMAT,
1841       GST_TIME_ARGS (best_ts), best);
1842   if (ts)
1843     *ts = best_ts;
1844   return best;
1845 }
1846
1847 static GstFlowReturn
1848 gst_flv_mux_aggregate (GstAggregator * aggregator, gboolean timeout)
1849 {
1850   GstFlvMux *mux = GST_FLV_MUX (aggregator);
1851   GstFlvMuxPad *best;
1852   gint64 best_time = GST_CLOCK_STIME_NONE;
1853   GstFlowReturn ret;
1854   GstClockTime ts;
1855   GstBuffer *buffer = NULL;
1856
1857   if (mux->state == GST_FLV_MUX_STATE_HEADER) {
1858     if (GST_ELEMENT_CAST (mux)->sinkpads == NULL) {
1859       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1860           ("No input streams configured"));
1861       return GST_FLOW_ERROR;
1862     }
1863
1864     ret = gst_flv_mux_write_header (mux);
1865     if (ret != GST_FLOW_OK)
1866       return ret;
1867     mux->state = GST_FLV_MUX_STATE_DATA;
1868
1869     best = gst_flv_mux_find_best_pad (aggregator, &ts);
1870
1871     if (!mux->streamable || mux->first_timestamp == GST_CLOCK_STIME_NONE) {
1872       if (best && GST_CLOCK_STIME_IS_VALID (ts))
1873         mux->first_timestamp = ts;
1874       else
1875         mux->first_timestamp = 0;
1876     }
1877   } else {
1878     best = gst_flv_mux_find_best_pad (aggregator, &ts);
1879   }
1880
1881   if (mux->new_tags && mux->streamable) {
1882     GstBuffer *buf = gst_flv_mux_create_metadata (mux);
1883     if (buf)
1884       gst_flv_mux_push (mux, buf);
1885     mux->new_tags = FALSE;
1886   }
1887
1888   if (best) {
1889     buffer = gst_aggregator_pad_pop_buffer (GST_AGGREGATOR_PAD (best));
1890     g_assert (buffer);
1891     best->dts =
1892         gst_flv_mux_segment_to_running_time (&GST_AGGREGATOR_PAD
1893         (best)->segment, GST_BUFFER_DTS_OR_PTS (buffer));
1894
1895     if (GST_CLOCK_STIME_IS_VALID (best->dts))
1896       best_time = best->dts - mux->first_timestamp;
1897
1898     if (GST_BUFFER_PTS_IS_VALID (buffer))
1899       best->pts =
1900           gst_flv_mux_segment_to_running_time (&GST_AGGREGATOR_PAD
1901           (best)->segment, GST_BUFFER_PTS (buffer));
1902     else
1903       best->pts = best->dts;
1904
1905     GST_LOG_OBJECT (best, "got buffer PTS %" GST_TIME_FORMAT " DTS %"
1906         GST_STIME_FORMAT, GST_TIME_ARGS (best->pts),
1907         GST_STIME_ARGS (best->dts));
1908   } else {
1909     best_time = GST_CLOCK_STIME_NONE;
1910   }
1911
1912   /* The FLV timestamp is an int32 field. For non-live streams error out if a
1913      bigger timestamp is seen, for live the timestamp will get wrapped in
1914      gst_flv_mux_buffer_to_tag */
1915   if (!mux->streamable && (GST_CLOCK_STIME_IS_VALID (best_time))
1916       && best_time / GST_MSECOND > G_MAXINT32) {
1917     GST_WARNING_OBJECT (mux, "Timestamp larger than FLV supports - EOS");
1918     if (buffer) {
1919       gst_buffer_unref (buffer);
1920       buffer = NULL;
1921     }
1922     best = NULL;
1923   }
1924
1925   if (best) {
1926     return gst_flv_mux_write_buffer (mux, best, buffer);
1927   } else {
1928     if (gst_flv_mux_are_all_pads_eos (mux)) {
1929       gst_flv_mux_write_eos (mux);
1930       gst_flv_mux_rewrite_header (mux);
1931       return GST_FLOW_EOS;
1932     }
1933     return GST_FLOW_OK;
1934   }
1935 }
1936
1937 static void
1938 gst_flv_mux_get_property (GObject * object,
1939     guint prop_id, GValue * value, GParamSpec * pspec)
1940 {
1941   GstFlvMux *mux = GST_FLV_MUX (object);
1942
1943   switch (prop_id) {
1944     case PROP_STREAMABLE:
1945       g_value_set_boolean (value, mux->streamable);
1946       break;
1947     case PROP_METADATACREATOR:
1948       g_value_set_string (value, mux->metadatacreator);
1949       break;
1950     case PROP_ENCODER:
1951       g_value_set_string (value, mux->encoder);
1952       break;
1953     default:
1954       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1955       break;
1956   }
1957 }
1958
1959 static void
1960 gst_flv_mux_set_property (GObject * object,
1961     guint prop_id, const GValue * value, GParamSpec * pspec)
1962 {
1963   GstFlvMux *mux = GST_FLV_MUX (object);
1964
1965   switch (prop_id) {
1966     case PROP_STREAMABLE:
1967       mux->streamable = g_value_get_boolean (value);
1968       if (mux->streamable)
1969         gst_tag_setter_set_tag_merge_mode (GST_TAG_SETTER (mux),
1970             GST_TAG_MERGE_REPLACE);
1971       else
1972         gst_tag_setter_set_tag_merge_mode (GST_TAG_SETTER (mux),
1973             GST_TAG_MERGE_KEEP);
1974       break;
1975     case PROP_METADATACREATOR:
1976       g_free (mux->metadatacreator);
1977       if (!g_value_get_string (value)) {
1978         GST_WARNING_OBJECT (mux, "metadatacreator property can not be NULL");
1979         mux->metadatacreator = g_strdup (DEFAULT_METADATACREATOR);
1980       } else {
1981         mux->metadatacreator = g_value_dup_string (value);
1982       }
1983       break;
1984     case PROP_ENCODER:
1985       g_free (mux->encoder);
1986       if (!g_value_get_string (value)) {
1987         GST_WARNING_OBJECT (mux, "encoder property can not be NULL");
1988         mux->encoder = g_strdup (DEFAULT_METADATACREATOR);
1989       } else {
1990         mux->encoder = g_value_dup_string (value);
1991       }
1992       break;
1993     default:
1994       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1995       break;
1996   }
1997 }
1998
1999 static GstClockTime
2000 gst_flv_mux_get_next_time (GstAggregator * aggregator)
2001 {
2002   GstFlvMux *mux = GST_FLV_MUX (aggregator);
2003   GstAggregatorPad *agg_audio_pad = GST_AGGREGATOR_PAD_CAST (mux->audio_pad);
2004   GstAggregatorPad *agg_video_pad = GST_AGGREGATOR_PAD_CAST (mux->video_pad);
2005
2006   GST_OBJECT_LOCK (aggregator);
2007   if (mux->state == GST_FLV_MUX_STATE_HEADER &&
2008       ((mux->audio_pad && mux->audio_pad->codec == G_MAXUINT) ||
2009           (mux->video_pad && mux->video_pad->codec == G_MAXUINT)))
2010     goto wait_for_data;
2011
2012   if (!((agg_audio_pad && gst_aggregator_pad_has_buffer (agg_audio_pad)) ||
2013           (agg_video_pad && gst_aggregator_pad_has_buffer (agg_video_pad))))
2014     goto wait_for_data;
2015   GST_OBJECT_UNLOCK (aggregator);
2016
2017   return gst_aggregator_simple_get_next_time (aggregator);
2018
2019 wait_for_data:
2020   GST_OBJECT_UNLOCK (aggregator);
2021   return GST_CLOCK_TIME_NONE;
2022 }
2023
2024 static GstFlowReturn
2025 gst_flv_mux_update_src_caps (GstAggregator * aggregator,
2026     GstCaps * caps, GstCaps ** ret)
2027 {
2028   GstFlvMux *mux = GST_FLV_MUX (aggregator);
2029
2030   *ret = gst_flv_mux_prepare_src_caps (mux, NULL, NULL, NULL, NULL);
2031
2032   return GST_FLOW_OK;
2033 }