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