Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst / multipart / multipartmux.c
1 /* multipart muxer plugin for GStreamer
2  * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-multipartmux
22  *
23  * MultipartMux uses the #GstCaps of the sink pad as the Content-type field for
24  * incoming buffers when muxing them to a multipart stream. Most of the time 
25  * multipart streams are sequential JPEG frames.
26  *
27  * <refsect2>
28  * <title>Sample pipelines</title>
29  * |[
30  * gst-launch videotestsrc ! video/x-raw-yuv, framerate='(fraction)'5/1 ! jpegenc ! multipartmux ! filesink location=/tmp/test.multipart
31  * ]| a pipeline to mux 5 JPEG frames per second into a multipart stream
32  * stored to a file.
33  * </refsect2>
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 #include "multipartmux.h"
41
42 GST_DEBUG_CATEGORY_STATIC (gst_multipart_mux_debug);
43 #define GST_CAT_DEFAULT gst_multipart_mux_debug
44
45 #define DEFAULT_BOUNDARY        "ThisRandomString"
46
47 enum
48 {
49   ARG_0,
50   ARG_BOUNDARY
51       /* FILL ME */
52 };
53
54 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
55     GST_PAD_SRC,
56     GST_PAD_ALWAYS,
57     GST_STATIC_CAPS ("multipart/x-mixed-replace")
58     );
59
60 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink_%u",
61     GST_PAD_SINK,
62     GST_PAD_REQUEST,
63     GST_STATIC_CAPS_ANY         /* we can take anything, really */
64     );
65
66 typedef struct
67 {
68   const gchar *key;
69   const gchar *val;
70 } MimeTypeMap;
71
72 /* convert from gst structure names to mime types. Add more when needed. */
73 static const MimeTypeMap mimetypes[] = {
74   {"audio/x-mulaw", "audio/basic"},
75   {NULL, NULL}
76 };
77
78 static void gst_multipart_mux_finalize (GObject * object);
79
80 static gboolean gst_multipart_mux_handle_src_event (GstPad * pad,
81     GstObject * parent, GstEvent * event);
82 static GstPad *gst_multipart_mux_request_new_pad (GstElement * element,
83     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
84 static GstStateChangeReturn gst_multipart_mux_change_state (GstElement *
85     element, GstStateChange transition);
86
87 static GstFlowReturn gst_multipart_mux_collected (GstCollectPads2 * pads,
88     GstMultipartMux * mux);
89
90 static void gst_multipart_mux_set_property (GObject * object, guint prop_id,
91     const GValue * value, GParamSpec * pspec);
92 static void gst_multipart_mux_get_property (GObject * object, guint prop_id,
93     GValue * value, GParamSpec * pspec);
94
95 #define gst_multipart_mux_parent_class parent_class
96 G_DEFINE_TYPE (GstMultipartMux, gst_multipart_mux, GST_TYPE_ELEMENT);
97
98 static void
99 gst_multipart_mux_class_init (GstMultipartMuxClass * klass)
100 {
101   GObjectClass *gobject_class;
102   GstElementClass *gstelement_class;
103   gint i;
104
105   gobject_class = (GObjectClass *) klass;
106   gstelement_class = (GstElementClass *) klass;
107
108   parent_class = g_type_class_peek_parent (klass);
109
110   gobject_class->finalize = gst_multipart_mux_finalize;
111   gobject_class->get_property = gst_multipart_mux_get_property;
112   gobject_class->set_property = gst_multipart_mux_set_property;
113
114   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BOUNDARY,
115       g_param_spec_string ("boundary", "Boundary", "Boundary string",
116           DEFAULT_BOUNDARY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
117
118   gstelement_class->request_new_pad = gst_multipart_mux_request_new_pad;
119   gstelement_class->change_state = gst_multipart_mux_change_state;
120
121   gst_element_class_add_pad_template (gstelement_class,
122       gst_static_pad_template_get (&src_factory));
123   gst_element_class_add_pad_template (gstelement_class,
124       gst_static_pad_template_get (&sink_factory));
125
126   gst_element_class_set_details_simple (gstelement_class, "Multipart muxer",
127       "Codec/Muxer", "mux multipart streams", "Wim Taymans <wim@fluendo.com>");
128
129   /* populate mime types */
130   klass->mimetypes = g_hash_table_new (g_str_hash, g_str_equal);
131   for (i = 0; mimetypes[i].key; i++) {
132     g_hash_table_insert (klass->mimetypes, (gpointer) mimetypes[i].key,
133         (gpointer) mimetypes[i].val);
134   }
135 }
136
137 static void
138 gst_multipart_mux_init (GstMultipartMux * multipart_mux)
139 {
140   GstElementClass *klass = GST_ELEMENT_GET_CLASS (multipart_mux);
141
142   multipart_mux->srcpad =
143       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
144           "src"), "src");
145   gst_pad_set_event_function (multipart_mux->srcpad,
146       gst_multipart_mux_handle_src_event);
147   gst_element_add_pad (GST_ELEMENT (multipart_mux), multipart_mux->srcpad);
148
149   multipart_mux->boundary = g_strdup (DEFAULT_BOUNDARY);
150
151   multipart_mux->collect = gst_collect_pads2_new ();
152   gst_collect_pads2_set_function (multipart_mux->collect,
153       (GstCollectPads2Function) GST_DEBUG_FUNCPTR (gst_multipart_mux_collected),
154       multipart_mux);
155 }
156
157 static void
158 gst_multipart_mux_finalize (GObject * object)
159 {
160   GstMultipartMux *multipart_mux;
161
162   multipart_mux = GST_MULTIPART_MUX (object);
163
164   g_free (multipart_mux->boundary);
165
166   if (multipart_mux->collect)
167     gst_object_unref (multipart_mux->collect);
168
169   G_OBJECT_CLASS (parent_class)->finalize (object);
170 }
171
172 static GstPad *
173 gst_multipart_mux_request_new_pad (GstElement * element,
174     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
175 {
176   GstMultipartMux *multipart_mux;
177   GstPad *newpad;
178   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
179   gchar *name;
180
181   if (templ != gst_element_class_get_pad_template (klass, "sink_%u"))
182     goto wrong_template;
183
184   multipart_mux = GST_MULTIPART_MUX (element);
185
186   /* create new pad with the name */
187   name = g_strdup_printf ("sink_%u", multipart_mux->numpads);
188   newpad = gst_pad_new_from_template (templ, name);
189   g_free (name);
190
191   /* construct our own wrapper data structure for the pad to
192    * keep track of its status */
193   {
194     GstMultipartPadData *multipartpad;
195
196     multipartpad = (GstMultipartPadData *)
197         gst_collect_pads2_add_pad (multipart_mux->collect, newpad,
198         sizeof (GstMultipartPadData));
199
200     /* save a pointer to our data in the pad */
201     multipartpad->pad = newpad;
202     gst_pad_set_element_private (newpad, multipartpad);
203     multipart_mux->numpads++;
204   }
205
206   /* add the pad to the element */
207   gst_element_add_pad (element, newpad);
208
209   return newpad;
210
211   /* ERRORS */
212 wrong_template:
213   {
214     g_warning ("multipart_mux: this is not our template!");
215     return NULL;
216   }
217 }
218
219 /* handle events */
220 static gboolean
221 gst_multipart_mux_handle_src_event (GstPad * pad, GstObject * parent,
222     GstEvent * event)
223 {
224   GstEventType type;
225
226   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
227
228   switch (type) {
229     case GST_EVENT_SEEK:
230       /* disable seeking for now */
231       return FALSE;
232     default:
233       break;
234   }
235
236   return gst_pad_event_default (pad, parent, event);
237 }
238
239 static const gchar *
240 gst_multipart_mux_get_mime (GstMultipartMux * mux, GstStructure * s)
241 {
242   GstMultipartMuxClass *klass;
243   const gchar *mime;
244   const gchar *name;
245   gint rate;
246   gint channels;
247   gint bitrate = 0;
248
249   klass = GST_MULTIPART_MUX_GET_CLASS (mux);
250
251   name = gst_structure_get_name (s);
252
253   /* use hashtable to convert to mime type */
254   mime = g_hash_table_lookup (klass->mimetypes, name);
255   if (mime == NULL) {
256     if (!strcmp (name, "audio/x-adpcm"))
257       gst_structure_get_int (s, "bitrate", &bitrate);
258
259     switch (bitrate) {
260       case 16000:
261         mime = "audio/G726-16";
262         break;
263       case 24000:
264         mime = "audio/G726-24";
265         break;
266       case 32000:
267         mime = "audio/G726-32";
268         break;
269       case 40000:
270         mime = "audio/G726-40";
271         break;
272       default:
273         /* no mime type mapping, use name */
274         mime = name;
275         break;
276     }
277   }
278   /* RFC2046 requires audio/basic to be mulaw 8000Hz mono */
279   if (g_ascii_strcasecmp (mime, "audio/basic") == 0) {
280     if (gst_structure_get_int (s, "rate", &rate) &&
281         gst_structure_get_int (s, "channels", &channels)) {
282       if (rate != 8000 || channels != 1) {
283         mime = name;
284       }
285     } else {
286       mime = name;
287     }
288   }
289   return mime;
290 }
291
292 /*
293  * Given two pads, compare the buffers queued on it and return 0 if they have
294  * an equal priority, 1 if the new pad is better, -1 if the old pad is better 
295  */
296 static gint
297 gst_multipart_mux_compare_pads (GstMultipartMux * multipart_mux,
298     GstMultipartPadData * old, GstMultipartPadData * new)
299 {
300   guint64 oldtime, newtime;
301
302   /* if the old pad doesn't contain anything or is even NULL, return 
303    * the new pad as best candidate and vice versa */
304   if (old == NULL || old->buffer == NULL)
305     return 1;
306   if (new == NULL || new->buffer == NULL)
307     return -1;
308
309   /* no timestamp on old buffer, it must go first */
310   oldtime = old->timestamp;
311   if (oldtime == GST_CLOCK_TIME_NONE)
312     return -1;
313
314   /* no timestamp on new buffer, it must go first */
315   newtime = new->timestamp;
316   if (newtime == GST_CLOCK_TIME_NONE)
317     return 1;
318
319   /* old buffer has higher timestamp, new one should go first */
320   if (newtime < oldtime)
321     return 1;
322   /* new buffer has higher timestamp, old one should go first */
323   else if (newtime > oldtime)
324     return -1;
325
326   /* same priority if all of the above failed */
327   return 0;
328 }
329
330 /* make sure a buffer is queued on all pads, returns a pointer to an multipartpad
331  * that holds the best buffer or NULL when no pad was usable */
332 static GstMultipartPadData *
333 gst_multipart_mux_queue_pads (GstMultipartMux * mux)
334 {
335   GSList *walk = NULL;
336   GstMultipartPadData *bestpad = NULL;
337
338   g_return_val_if_fail (GST_IS_MULTIPART_MUX (mux), NULL);
339
340   /* try to make sure we have a buffer from each usable pad first */
341   walk = mux->collect->data;
342   while (walk) {
343     GstCollectData2 *data = (GstCollectData2 *) walk->data;
344     GstMultipartPadData *pad = (GstMultipartPadData *) data;
345
346     walk = g_slist_next (walk);
347
348     /* try to get a new buffer for this pad if needed and possible */
349     if (pad->buffer == NULL) {
350       GstBuffer *buf = NULL;
351
352       buf = gst_collect_pads2_pop (mux->collect, data);
353
354       /* Store timestamp with segment_start and preroll */
355       if (buf && GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
356         pad->timestamp =
357             gst_segment_to_running_time (&data->segment, GST_FORMAT_TIME,
358             GST_BUFFER_TIMESTAMP (buf));
359       } else {
360         pad->timestamp = GST_CLOCK_TIME_NONE;
361       }
362
363       pad->buffer = buf;
364     }
365
366     /* we should have a buffer now, see if it is the best stream to
367      * pull on */
368     if (pad->buffer != NULL) {
369       if (gst_multipart_mux_compare_pads (mux, bestpad, pad) > 0) {
370         bestpad = pad;
371       }
372     }
373   }
374
375   return bestpad;
376 }
377
378 /* basic idea:
379  *
380  * 1) find a pad to pull on, this is done by pulling on all pads and
381  *    looking at the buffers to decide which one should be muxed first.
382  * 2) create a new buffer for the header
383  * 3) push both buffers on best pad, go to 1
384  */
385 static GstFlowReturn
386 gst_multipart_mux_collected (GstCollectPads2 * pads, GstMultipartMux * mux)
387 {
388   GstMultipartPadData *best;
389   GstFlowReturn ret = GST_FLOW_OK;
390   gchar *header = NULL;
391   size_t headerlen;
392   GstBuffer *headerbuf = NULL;
393   GstBuffer *footerbuf = NULL;
394   GstBuffer *databuf = NULL;
395   GstStructure *structure = NULL;
396   GstCaps *caps;
397   const gchar *mime;
398
399   GST_DEBUG_OBJECT (mux, "all pads are collected");
400
401   /* queue buffers on all pads; find a buffer with the lowest timestamp */
402   best = gst_multipart_mux_queue_pads (mux);
403   if (!best)
404     /* EOS */
405     goto eos;
406   else if (!best->buffer)
407     goto buffer_error;
408
409   /* If not negotiated yet set caps on src pad */
410   if (!mux->negotiated) {
411     GstCaps *newcaps;
412
413     newcaps = gst_caps_new_simple ("multipart/x-mixed-replace",
414         "boundary", G_TYPE_STRING, mux->boundary, NULL);
415
416     if (!gst_pad_set_caps (mux->srcpad, newcaps)) {
417       gst_caps_unref (newcaps);
418       goto nego_error;
419     }
420
421     gst_caps_unref (newcaps);
422     mux->negotiated = TRUE;
423   }
424
425   /* see if we need to push a segment */
426   if (mux->need_segment) {
427     GstClockTime time;
428     GstSegment segment;
429
430     if (best->timestamp != -1)
431       time = best->timestamp;
432     else
433       time = 0;
434
435     /* for the segment, we take the first timestamp we see, we don't know the
436      * length and the position is 0 */
437     gst_segment_init (&segment, GST_FORMAT_TIME);
438     segment.start = time;
439
440     gst_pad_push_event (mux->srcpad, gst_event_new_segment (&segment));
441
442     mux->need_segment = FALSE;
443   }
444
445   caps = gst_pad_get_current_caps (best->pad);
446   if (caps == NULL)
447     goto no_caps;
448
449   structure = gst_caps_get_structure (caps, 0);
450   if (!structure) {
451     gst_caps_unref (caps);
452     goto no_caps;
453   }
454
455   /* get the mime type for the structure */
456   mime = gst_multipart_mux_get_mime (mux, structure);
457   gst_caps_unref (caps);
458
459   header = g_strdup_printf ("--%s\r\nContent-Type: %s\r\n"
460       "Content-Length: %" G_GSIZE_FORMAT "\r\n\r\n",
461       mux->boundary, mime, gst_buffer_get_size (best->buffer));
462   headerlen = strlen (header);
463
464   headerbuf = gst_buffer_new_allocate (NULL, headerlen, 1);
465   gst_buffer_fill (headerbuf, 0, header, headerlen);
466   g_free (header);
467
468   /* the header has the same timestamp as the data buffer (which we will push
469    * below) and has a duration of 0 */
470   GST_BUFFER_TIMESTAMP (headerbuf) = best->timestamp;
471   GST_BUFFER_DURATION (headerbuf) = 0;
472   GST_BUFFER_OFFSET (headerbuf) = mux->offset;
473   mux->offset += headerlen;
474   GST_BUFFER_OFFSET_END (headerbuf) = mux->offset;
475
476   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes header buffer",
477       headerlen);
478   ret = gst_pad_push (mux->srcpad, headerbuf);
479   if (ret != GST_FLOW_OK)
480     /* push always takes ownership of the buffer, even after an error, so we
481      * don't need to unref headerbuf here. */
482     goto beach;
483
484   /* take best->buffer, we don't need to unref it later as we will push it
485    * now. */
486   databuf = gst_buffer_make_writable (best->buffer);
487   best->buffer = NULL;
488
489   /* we need to updated the timestamp to match the running_time */
490   GST_BUFFER_TIMESTAMP (databuf) = best->timestamp;
491   GST_BUFFER_OFFSET (databuf) = mux->offset;
492   mux->offset += gst_buffer_get_size (databuf);
493   GST_BUFFER_OFFSET_END (databuf) = mux->offset;
494   GST_BUFFER_FLAG_SET (databuf, GST_BUFFER_FLAG_DELTA_UNIT);
495
496   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes data buffer",
497       gst_buffer_get_size (databuf));
498   ret = gst_pad_push (mux->srcpad, databuf);
499   if (ret != GST_FLOW_OK)
500     /* push always takes ownership of the buffer, even after an error, so we
501      * don't need to unref headerbuf here. */
502     goto beach;
503
504   footerbuf = gst_buffer_new_allocate (NULL, 2, 1);
505   gst_buffer_fill (footerbuf, 0, "\r\n", 2);
506
507   /* the footer has the same timestamp as the data buffer and has a
508    * duration of 0 */
509   GST_BUFFER_TIMESTAMP (footerbuf) = best->timestamp;
510   GST_BUFFER_DURATION (footerbuf) = 0;
511   GST_BUFFER_OFFSET (footerbuf) = mux->offset;
512   mux->offset += 2;
513   GST_BUFFER_OFFSET_END (footerbuf) = mux->offset;
514   GST_BUFFER_FLAG_SET (footerbuf, GST_BUFFER_FLAG_DELTA_UNIT);
515
516   GST_DEBUG_OBJECT (mux, "pushing 2 bytes footer buffer");
517   ret = gst_pad_push (mux->srcpad, footerbuf);
518
519 beach:
520   if (best && best->buffer) {
521     gst_buffer_unref (best->buffer);
522     best->buffer = NULL;
523   }
524   return ret;
525
526   /* ERRORS */
527 buffer_error:
528   {
529     /* There is a best but no buffer, this is not quite right.. */
530     GST_ELEMENT_ERROR (mux, STREAM, FAILED, (NULL), ("internal muxing error"));
531     ret = GST_FLOW_ERROR;
532     goto beach;
533   }
534 eos:
535   {
536     GST_DEBUG_OBJECT (mux, "Pushing EOS");
537     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
538     ret = GST_FLOW_EOS;
539     goto beach;
540   }
541 nego_error:
542   {
543     GST_WARNING_OBJECT (mux, "failed to set caps");
544     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
545     ret = GST_FLOW_NOT_NEGOTIATED;
546     goto beach;
547   }
548 no_caps:
549   {
550     GST_WARNING_OBJECT (mux, "no caps on the incoming buffer %p", best->buffer);
551     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
552     ret = GST_FLOW_NOT_NEGOTIATED;
553     goto beach;
554   }
555 }
556
557 static void
558 gst_multipart_mux_get_property (GObject * object,
559     guint prop_id, GValue * value, GParamSpec * pspec)
560 {
561   GstMultipartMux *mux;
562
563   mux = GST_MULTIPART_MUX (object);
564
565   switch (prop_id) {
566     case ARG_BOUNDARY:
567       g_value_set_string (value, mux->boundary);
568       break;
569     default:
570       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
571       break;
572   }
573 }
574
575 static void
576 gst_multipart_mux_set_property (GObject * object,
577     guint prop_id, const GValue * value, GParamSpec * pspec)
578 {
579   GstMultipartMux *mux;
580
581   mux = GST_MULTIPART_MUX (object);
582
583   switch (prop_id) {
584     case ARG_BOUNDARY:
585       g_free (mux->boundary);
586       mux->boundary = g_strdup (g_value_get_string (value));
587       break;
588     default:
589       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
590       break;
591   }
592 }
593
594 static GstStateChangeReturn
595 gst_multipart_mux_change_state (GstElement * element, GstStateChange transition)
596 {
597   GstMultipartMux *multipart_mux;
598   GstStateChangeReturn ret;
599
600   multipart_mux = GST_MULTIPART_MUX (element);
601
602   switch (transition) {
603     case GST_STATE_CHANGE_READY_TO_PAUSED:
604       multipart_mux->offset = 0;
605       multipart_mux->negotiated = FALSE;
606       multipart_mux->need_segment = TRUE;
607       GST_DEBUG_OBJECT (multipart_mux, "starting collect pads");
608       gst_collect_pads2_start (multipart_mux->collect);
609       break;
610     case GST_STATE_CHANGE_PAUSED_TO_READY:
611       GST_DEBUG_OBJECT (multipart_mux, "stopping collect pads");
612       gst_collect_pads2_stop (multipart_mux->collect);
613       break;
614     default:
615       break;
616   }
617
618   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
619   if (ret == GST_STATE_CHANGE_FAILURE)
620     return ret;
621
622   switch (transition) {
623     default:
624       break;
625   }
626
627   return ret;
628 }
629
630 gboolean
631 gst_multipart_mux_plugin_init (GstPlugin * plugin)
632 {
633   GST_DEBUG_CATEGORY_INIT (gst_multipart_mux_debug, "multipartmux", 0,
634       "multipart muxer");
635
636   return gst_element_register (plugin, "multipartmux", GST_RANK_NONE,
637       GST_TYPE_MULTIPART_MUX);
638 }