upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.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_%d",
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_base_init (gpointer g_class);
79 static void gst_multipart_mux_class_init (GstMultipartMuxClass * klass);
80 static void gst_multipart_mux_init (GstMultipartMux * multipart_mux);
81
82 static void gst_multipart_mux_finalize (GObject * object);
83
84 static gboolean gst_multipart_mux_handle_src_event (GstPad * pad,
85     GstEvent * event);
86 static GstPad *gst_multipart_mux_request_new_pad (GstElement * element,
87     GstPadTemplate * templ, const gchar * name);
88 static GstStateChangeReturn gst_multipart_mux_change_state (GstElement *
89     element, GstStateChange transition);
90
91 static GstFlowReturn gst_multipart_mux_collected (GstCollectPads * pads,
92     GstMultipartMux * mux);
93
94 static void gst_multipart_mux_set_property (GObject * object, guint prop_id,
95     const GValue * value, GParamSpec * pspec);
96 static void gst_multipart_mux_get_property (GObject * object, guint prop_id,
97     GValue * value, GParamSpec * pspec);
98
99 static GstElementClass *parent_class = NULL;
100
101 GType
102 gst_multipart_mux_get_type (void)
103 {
104   static GType multipart_mux_type = 0;
105
106   if (!multipart_mux_type) {
107     static const GTypeInfo multipart_mux_info = {
108       sizeof (GstMultipartMuxClass),
109       gst_multipart_mux_base_init,
110       NULL,
111       (GClassInitFunc) gst_multipart_mux_class_init,
112       NULL,
113       NULL,
114       sizeof (GstMultipartMux),
115       0,
116       (GInstanceInitFunc) gst_multipart_mux_init,
117     };
118
119     multipart_mux_type =
120         g_type_register_static (GST_TYPE_ELEMENT, "GstMultipartMux",
121         &multipart_mux_info, 0);
122   }
123   return multipart_mux_type;
124 }
125
126 static void
127 gst_multipart_mux_base_init (gpointer g_class)
128 {
129   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
130
131   gst_element_class_add_pad_template (element_class,
132       gst_static_pad_template_get (&src_factory));
133   gst_element_class_add_pad_template (element_class,
134       gst_static_pad_template_get (&sink_factory));
135
136   gst_element_class_set_details_simple (element_class, "Multipart muxer",
137       "Codec/Muxer", "mux multipart streams", "Wim Taymans <wim@fluendo.com>");
138 }
139
140 static void
141 gst_multipart_mux_class_init (GstMultipartMuxClass * klass)
142 {
143   GObjectClass *gobject_class;
144   GstElementClass *gstelement_class;
145   gint i;
146
147   gobject_class = (GObjectClass *) klass;
148   gstelement_class = (GstElementClass *) klass;
149
150   parent_class = g_type_class_peek_parent (klass);
151
152   gobject_class->finalize = gst_multipart_mux_finalize;
153   gobject_class->get_property = gst_multipart_mux_get_property;
154   gobject_class->set_property = gst_multipart_mux_set_property;
155
156   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BOUNDARY,
157       g_param_spec_string ("boundary", "Boundary", "Boundary string",
158           DEFAULT_BOUNDARY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
159
160   gstelement_class->request_new_pad = gst_multipart_mux_request_new_pad;
161   gstelement_class->change_state = gst_multipart_mux_change_state;
162
163   /* populate mime types */
164   klass->mimetypes = g_hash_table_new (g_str_hash, g_str_equal);
165   for (i = 0; mimetypes[i].key; i++) {
166     g_hash_table_insert (klass->mimetypes, (gpointer) mimetypes[i].key,
167         (gpointer) mimetypes[i].val);
168   }
169 }
170
171 static void
172 gst_multipart_mux_init (GstMultipartMux * multipart_mux)
173 {
174   GstElementClass *klass = GST_ELEMENT_GET_CLASS (multipart_mux);
175
176   multipart_mux->srcpad =
177       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
178           "src"), "src");
179   gst_pad_set_event_function (multipart_mux->srcpad,
180       gst_multipart_mux_handle_src_event);
181   gst_element_add_pad (GST_ELEMENT (multipart_mux), multipart_mux->srcpad);
182
183   multipart_mux->boundary = g_strdup (DEFAULT_BOUNDARY);
184
185   multipart_mux->collect = gst_collect_pads_new ();
186   gst_collect_pads_set_function (multipart_mux->collect,
187       (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_multipart_mux_collected),
188       multipart_mux);
189 }
190
191 static void
192 gst_multipart_mux_finalize (GObject * object)
193 {
194   GstMultipartMux *multipart_mux;
195
196   multipart_mux = GST_MULTIPART_MUX (object);
197
198   g_free (multipart_mux->boundary);
199
200   if (multipart_mux->collect)
201     gst_object_unref (multipart_mux->collect);
202
203   G_OBJECT_CLASS (parent_class)->finalize (object);
204 }
205
206 static GstPad *
207 gst_multipart_mux_request_new_pad (GstElement * element,
208     GstPadTemplate * templ, const gchar * req_name)
209 {
210   GstMultipartMux *multipart_mux;
211   GstPad *newpad;
212   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
213   gchar *name;
214
215   if (templ != gst_element_class_get_pad_template (klass, "sink_%d"))
216     goto wrong_template;
217
218   multipart_mux = GST_MULTIPART_MUX (element);
219
220   /* create new pad with the name */
221   name = g_strdup_printf ("sink_%02d", multipart_mux->numpads);
222   newpad = gst_pad_new_from_template (templ, name);
223   g_free (name);
224
225   /* construct our own wrapper data structure for the pad to
226    * keep track of its status */
227   {
228     GstMultipartPadData *multipartpad;
229
230     multipartpad = (GstMultipartPadData *)
231         gst_collect_pads_add_pad (multipart_mux->collect, newpad,
232         sizeof (GstMultipartPadData));
233
234     /* save a pointer to our data in the pad */
235     gst_pad_set_element_private (newpad, multipartpad);
236     multipart_mux->numpads++;
237   }
238
239   /* add the pad to the element */
240   gst_element_add_pad (element, newpad);
241
242   return newpad;
243
244   /* ERRORS */
245 wrong_template:
246   {
247     g_warning ("multipart_mux: this is not our template!");
248     return NULL;
249   }
250 }
251
252 /* handle events */
253 static gboolean
254 gst_multipart_mux_handle_src_event (GstPad * pad, GstEvent * event)
255 {
256   GstMultipartMux *multipart_mux;
257   GstEventType type;
258
259   multipart_mux = GST_MULTIPART_MUX (gst_pad_get_parent (pad));
260
261   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
262
263   switch (type) {
264     case GST_EVENT_SEEK:
265       /* disable seeking for now */
266       return FALSE;
267     default:
268       break;
269   }
270
271   gst_object_unref (multipart_mux);
272
273   return gst_pad_event_default (pad, event);
274 }
275
276 static const gchar *
277 gst_multipart_mux_get_mime (GstMultipartMux * mux, GstStructure * s)
278 {
279   GstMultipartMuxClass *klass;
280   const gchar *mime;
281   const gchar *name;
282   gint rate;
283   gint channels;
284   gint bitrate = 0;
285
286   klass = GST_MULTIPART_MUX_GET_CLASS (mux);
287
288   name = gst_structure_get_name (s);
289
290   /* use hashtable to convert to mime type */
291   mime = g_hash_table_lookup (klass->mimetypes, name);
292   if (mime == NULL) {
293     if (!strcmp (name, "audio/x-adpcm"))
294       gst_structure_get_int (s, "bitrate", &bitrate);
295
296     switch (bitrate) {
297       case 16000:
298         mime = "audio/G726-16";
299         break;
300       case 24000:
301         mime = "audio/G726-24";
302         break;
303       case 32000:
304         mime = "audio/G726-32";
305         break;
306       case 40000:
307         mime = "audio/G726-40";
308         break;
309       default:
310         /* no mime type mapping, use name */
311         mime = name;
312         break;
313     }
314   }
315   /* RFC2046 requires audio/basic to be mulaw 8000Hz mono */
316   if (g_ascii_strcasecmp (mime, "audio/basic") == 0) {
317     if (gst_structure_get_int (s, "rate", &rate) &&
318         gst_structure_get_int (s, "channels", &channels)) {
319       if (rate != 8000 || channels != 1) {
320         mime = name;
321       }
322     } else {
323       mime = name;
324     }
325   }
326   return mime;
327 }
328
329 /*
330  * Given two pads, compare the buffers queued on it and return 0 if they have
331  * an equal priority, 1 if the new pad is better, -1 if the old pad is better 
332  */
333 static gint
334 gst_multipart_mux_compare_pads (GstMultipartMux * multipart_mux,
335     GstMultipartPadData * old, GstMultipartPadData * new)
336 {
337   guint64 oldtime, newtime;
338
339   /* if the old pad doesn't contain anything or is even NULL, return 
340    * the new pad as best candidate and vice versa */
341   if (old == NULL || old->buffer == NULL)
342     return 1;
343   if (new == NULL || new->buffer == NULL)
344     return -1;
345
346   /* no timestamp on old buffer, it must go first */
347   oldtime = old->timestamp;
348   if (oldtime == GST_CLOCK_TIME_NONE)
349     return -1;
350
351   /* no timestamp on new buffer, it must go first */
352   newtime = new->timestamp;
353   if (newtime == GST_CLOCK_TIME_NONE)
354     return 1;
355
356   /* old buffer has higher timestamp, new one should go first */
357   if (newtime < oldtime)
358     return 1;
359   /* new buffer has higher timestamp, old one should go first */
360   else if (newtime > oldtime)
361     return -1;
362
363   /* same priority if all of the above failed */
364   return 0;
365 }
366
367 /* make sure a buffer is queued on all pads, returns a pointer to an multipartpad
368  * that holds the best buffer or NULL when no pad was usable */
369 static GstMultipartPadData *
370 gst_multipart_mux_queue_pads (GstMultipartMux * mux)
371 {
372   GSList *walk = NULL;
373   GstMultipartPadData *bestpad = NULL;
374
375   g_return_val_if_fail (GST_IS_MULTIPART_MUX (mux), NULL);
376
377   /* try to make sure we have a buffer from each usable pad first */
378   walk = mux->collect->data;
379   while (walk) {
380     GstCollectData *data = (GstCollectData *) walk->data;
381     GstMultipartPadData *pad = (GstMultipartPadData *) data;
382
383     walk = g_slist_next (walk);
384
385     /* try to get a new buffer for this pad if needed and possible */
386     if (pad->buffer == NULL) {
387       GstBuffer *buf = NULL;
388
389       buf = gst_collect_pads_pop (mux->collect, data);
390
391       /* Store timestamp with segment_start and preroll */
392       if (buf && GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
393         pad->timestamp =
394             gst_segment_to_running_time (&data->segment, GST_FORMAT_TIME,
395             GST_BUFFER_TIMESTAMP (buf));
396       } else {
397         pad->timestamp = GST_CLOCK_TIME_NONE;
398       }
399
400       pad->buffer = buf;
401     }
402
403     /* we should have a buffer now, see if it is the best stream to
404      * pull on */
405     if (pad->buffer != NULL) {
406       if (gst_multipart_mux_compare_pads (mux, bestpad, pad) > 0) {
407         bestpad = pad;
408       }
409     }
410   }
411
412   return bestpad;
413 }
414
415 /* basic idea:
416  *
417  * 1) find a pad to pull on, this is done by pulling on all pads and
418  *    looking at the buffers to decide which one should be muxed first.
419  * 2) create a new buffer for the header
420  * 3) push both buffers on best pad, go to 1
421  */
422 static GstFlowReturn
423 gst_multipart_mux_collected (GstCollectPads * pads, GstMultipartMux * mux)
424 {
425   GstMultipartPadData *best;
426   GstFlowReturn ret = GST_FLOW_OK;
427   gchar *header = NULL;
428   size_t headerlen;
429   GstBuffer *headerbuf = NULL;
430   GstBuffer *databuf = NULL;
431   GstStructure *structure = NULL;
432   const gchar *mime;
433
434   GST_DEBUG_OBJECT (mux, "all pads are collected");
435
436   /* queue buffers on all pads; find a buffer with the lowest timestamp */
437   best = gst_multipart_mux_queue_pads (mux);
438   if (!best)
439     /* EOS */
440     goto eos;
441   else if (!best->buffer)
442     goto buffer_error;
443
444   /* If not negotiated yet set caps on src pad */
445   if (!mux->negotiated) {
446     GstCaps *newcaps;
447
448     newcaps = gst_caps_new_simple ("multipart/x-mixed-replace",
449         "boundary", G_TYPE_STRING, mux->boundary, NULL);
450
451     if (!gst_pad_set_caps (mux->srcpad, newcaps)) {
452       gst_caps_unref (newcaps);
453       goto nego_error;
454     }
455
456     gst_caps_unref (newcaps);
457     mux->negotiated = TRUE;
458   }
459
460   /* see if we need to push a segment */
461   if (mux->need_segment) {
462     GstEvent *event;
463     GstClockTime time;
464
465     if (best->timestamp != -1)
466       time = best->timestamp;
467     else
468       time = 0;
469
470     /* for the segment, we take the first timestamp we see, we don't know the
471      * length and the position is 0 */
472     event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_TIME,
473         time, -1, 0);
474
475     gst_pad_push_event (mux->srcpad, event);
476
477     mux->need_segment = FALSE;
478   }
479
480   structure = gst_caps_get_structure (GST_BUFFER_CAPS (best->buffer), 0);
481   if (!structure)
482     goto no_caps;
483
484   /* get the mime type for the structure */
485   mime = gst_multipart_mux_get_mime (mux, structure);
486
487   header = g_strdup_printf ("\r\n--%s\r\nContent-Type: %s\r\n"
488       "Content-Length: %u\r\n\r\n",
489       mux->boundary, mime, GST_BUFFER_SIZE (best->buffer));
490   headerlen = strlen (header);
491
492   ret = gst_pad_alloc_buffer_and_set_caps (mux->srcpad, GST_BUFFER_OFFSET_NONE,
493       headerlen, GST_PAD_CAPS (mux->srcpad), &headerbuf);
494   if (ret != GST_FLOW_OK)
495     goto alloc_failed;
496
497   memcpy (GST_BUFFER_DATA (headerbuf), header, headerlen);
498   g_free (header);
499
500   /* the header has the same timestamp as the data buffer (which we will push
501    * below) and has a duration of 0 */
502   GST_BUFFER_TIMESTAMP (headerbuf) = best->timestamp;
503   GST_BUFFER_DURATION (headerbuf) = 0;
504   GST_BUFFER_OFFSET (headerbuf) = mux->offset;
505   mux->offset += headerlen;
506   GST_BUFFER_OFFSET_END (headerbuf) = mux->offset;
507
508   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes header buffer",
509       headerlen);
510   ret = gst_pad_push (mux->srcpad, headerbuf);
511   if (ret != GST_FLOW_OK)
512     /* push always takes ownership of the buffer, even after an error, so we
513      * don't need to unref headerbuf here. */
514     goto beach;
515
516   /* take best->buffer, we don't need to unref it later as we will push it
517    * now. */
518   databuf = gst_buffer_make_metadata_writable (best->buffer);
519   best->buffer = NULL;
520
521   gst_buffer_set_caps (databuf, GST_PAD_CAPS (mux->srcpad));
522   /* we need to updated the timestamp to match the running_time */
523   GST_BUFFER_TIMESTAMP (databuf) = best->timestamp;
524   GST_BUFFER_OFFSET (databuf) = mux->offset;
525   mux->offset += GST_BUFFER_SIZE (databuf);
526   GST_BUFFER_OFFSET_END (databuf) = mux->offset;
527   GST_BUFFER_FLAG_SET (databuf, GST_BUFFER_FLAG_DELTA_UNIT);
528
529   GST_DEBUG_OBJECT (mux, "pushing %u bytes data buffer",
530       GST_BUFFER_SIZE (databuf));
531   ret = gst_pad_push (mux->srcpad, databuf);
532
533 beach:
534   if (best && best->buffer) {
535     gst_buffer_unref (best->buffer);
536     best->buffer = NULL;
537   }
538   return ret;
539
540   /* ERRORS */
541 buffer_error:
542   {
543     /* There is a best but no buffer, this is not quite right.. */
544     GST_ELEMENT_ERROR (mux, STREAM, FAILED, (NULL), ("internal muxing error"));
545     ret = GST_FLOW_ERROR;
546     goto beach;
547   }
548 eos:
549   {
550     GST_DEBUG_OBJECT (mux, "Pushing EOS");
551     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
552     ret = GST_FLOW_UNEXPECTED;
553     goto beach;
554   }
555 nego_error:
556   {
557     GST_WARNING_OBJECT (mux, "failed to set caps");
558     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
559     ret = GST_FLOW_NOT_NEGOTIATED;
560     goto beach;
561   }
562 no_caps:
563   {
564     GST_WARNING_OBJECT (mux, "no caps on the incoming buffer %p", best->buffer);
565     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
566     ret = GST_FLOW_NOT_NEGOTIATED;
567     goto beach;
568   }
569 alloc_failed:
570   {
571     GST_WARNING_OBJECT (mux,
572         "failed allocating a %" G_GSIZE_FORMAT " bytes buffer", headerlen);
573     g_free (header);
574     goto beach;
575   }
576 }
577
578 static void
579 gst_multipart_mux_get_property (GObject * object,
580     guint prop_id, GValue * value, GParamSpec * pspec)
581 {
582   GstMultipartMux *mux;
583
584   mux = GST_MULTIPART_MUX (object);
585
586   switch (prop_id) {
587     case ARG_BOUNDARY:
588       g_value_set_string (value, mux->boundary);
589       break;
590     default:
591       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
592       break;
593   }
594 }
595
596 static void
597 gst_multipart_mux_set_property (GObject * object,
598     guint prop_id, const GValue * value, GParamSpec * pspec)
599 {
600   GstMultipartMux *mux;
601
602   mux = GST_MULTIPART_MUX (object);
603
604   switch (prop_id) {
605     case ARG_BOUNDARY:
606       g_free (mux->boundary);
607       mux->boundary = g_strdup (g_value_get_string (value));
608       break;
609     default:
610       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
611       break;
612   }
613 }
614
615 static GstStateChangeReturn
616 gst_multipart_mux_change_state (GstElement * element, GstStateChange transition)
617 {
618   GstMultipartMux *multipart_mux;
619   GstStateChangeReturn ret;
620
621   multipart_mux = GST_MULTIPART_MUX (element);
622
623   switch (transition) {
624     case GST_STATE_CHANGE_READY_TO_PAUSED:
625       multipart_mux->offset = 0;
626       multipart_mux->negotiated = FALSE;
627       multipart_mux->need_segment = TRUE;
628       GST_DEBUG_OBJECT (multipart_mux, "starting collect pads");
629       gst_collect_pads_start (multipart_mux->collect);
630       break;
631     case GST_STATE_CHANGE_PAUSED_TO_READY:
632       GST_DEBUG_OBJECT (multipart_mux, "stopping collect pads");
633       gst_collect_pads_stop (multipart_mux->collect);
634       break;
635     default:
636       break;
637   }
638
639   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
640   if (ret == GST_STATE_CHANGE_FAILURE)
641     return ret;
642
643   switch (transition) {
644     default:
645       break;
646   }
647
648   return ret;
649 }
650
651 gboolean
652 gst_multipart_mux_plugin_init (GstPlugin * plugin)
653 {
654   GST_DEBUG_CATEGORY_INIT (gst_multipart_mux_debug, "multipartmux", 0,
655       "multipart muxer");
656
657   return gst_element_register (plugin, "multipartmux", GST_RANK_NONE,
658       GST_TYPE_MULTIPART_MUX);
659 }