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