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