make %u in all request pad templates
[platform/upstream/gst-plugins-good.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     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 (GstCollectPads * 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_pads_new ();
152   gst_collect_pads_set_function (multipart_mux->collect,
153       (GstCollectPadsFunction) 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_pads_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, GstEvent * event)
222 {
223   GstMultipartMux *multipart_mux;
224   GstEventType type;
225
226   multipart_mux = GST_MULTIPART_MUX (gst_pad_get_parent (pad));
227
228   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
229
230   switch (type) {
231     case GST_EVENT_SEEK:
232       /* disable seeking for now */
233       return FALSE;
234     default:
235       break;
236   }
237
238   gst_object_unref (multipart_mux);
239
240   return gst_pad_event_default (pad, event);
241 }
242
243 static const gchar *
244 gst_multipart_mux_get_mime (GstMultipartMux * mux, GstStructure * s)
245 {
246   GstMultipartMuxClass *klass;
247   const gchar *mime;
248   const gchar *name;
249   gint rate;
250   gint channels;
251   gint bitrate = 0;
252
253   klass = GST_MULTIPART_MUX_GET_CLASS (mux);
254
255   name = gst_structure_get_name (s);
256
257   /* use hashtable to convert to mime type */
258   mime = g_hash_table_lookup (klass->mimetypes, name);
259   if (mime == NULL) {
260     if (!strcmp (name, "audio/x-adpcm"))
261       gst_structure_get_int (s, "bitrate", &bitrate);
262
263     switch (bitrate) {
264       case 16000:
265         mime = "audio/G726-16";
266         break;
267       case 24000:
268         mime = "audio/G726-24";
269         break;
270       case 32000:
271         mime = "audio/G726-32";
272         break;
273       case 40000:
274         mime = "audio/G726-40";
275         break;
276       default:
277         /* no mime type mapping, use name */
278         mime = name;
279         break;
280     }
281   }
282   /* RFC2046 requires audio/basic to be mulaw 8000Hz mono */
283   if (g_ascii_strcasecmp (mime, "audio/basic") == 0) {
284     if (gst_structure_get_int (s, "rate", &rate) &&
285         gst_structure_get_int (s, "channels", &channels)) {
286       if (rate != 8000 || channels != 1) {
287         mime = name;
288       }
289     } else {
290       mime = name;
291     }
292   }
293   return mime;
294 }
295
296 /*
297  * Given two pads, compare the buffers queued on it and return 0 if they have
298  * an equal priority, 1 if the new pad is better, -1 if the old pad is better 
299  */
300 static gint
301 gst_multipart_mux_compare_pads (GstMultipartMux * multipart_mux,
302     GstMultipartPadData * old, GstMultipartPadData * new)
303 {
304   guint64 oldtime, newtime;
305
306   /* if the old pad doesn't contain anything or is even NULL, return 
307    * the new pad as best candidate and vice versa */
308   if (old == NULL || old->buffer == NULL)
309     return 1;
310   if (new == NULL || new->buffer == NULL)
311     return -1;
312
313   /* no timestamp on old buffer, it must go first */
314   oldtime = old->timestamp;
315   if (oldtime == GST_CLOCK_TIME_NONE)
316     return -1;
317
318   /* no timestamp on new buffer, it must go first */
319   newtime = new->timestamp;
320   if (newtime == GST_CLOCK_TIME_NONE)
321     return 1;
322
323   /* old buffer has higher timestamp, new one should go first */
324   if (newtime < oldtime)
325     return 1;
326   /* new buffer has higher timestamp, old one should go first */
327   else if (newtime > oldtime)
328     return -1;
329
330   /* same priority if all of the above failed */
331   return 0;
332 }
333
334 /* make sure a buffer is queued on all pads, returns a pointer to an multipartpad
335  * that holds the best buffer or NULL when no pad was usable */
336 static GstMultipartPadData *
337 gst_multipart_mux_queue_pads (GstMultipartMux * mux)
338 {
339   GSList *walk = NULL;
340   GstMultipartPadData *bestpad = NULL;
341
342   g_return_val_if_fail (GST_IS_MULTIPART_MUX (mux), NULL);
343
344   /* try to make sure we have a buffer from each usable pad first */
345   walk = mux->collect->data;
346   while (walk) {
347     GstCollectData *data = (GstCollectData *) walk->data;
348     GstMultipartPadData *pad = (GstMultipartPadData *) data;
349
350     walk = g_slist_next (walk);
351
352     /* try to get a new buffer for this pad if needed and possible */
353     if (pad->buffer == NULL) {
354       GstBuffer *buf = NULL;
355
356       buf = gst_collect_pads_pop (mux->collect, data);
357
358       /* Store timestamp with segment_start and preroll */
359       if (buf && GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
360         pad->timestamp =
361             gst_segment_to_running_time (&data->segment, GST_FORMAT_TIME,
362             GST_BUFFER_TIMESTAMP (buf));
363       } else {
364         pad->timestamp = GST_CLOCK_TIME_NONE;
365       }
366
367       pad->buffer = buf;
368     }
369
370     /* we should have a buffer now, see if it is the best stream to
371      * pull on */
372     if (pad->buffer != NULL) {
373       if (gst_multipart_mux_compare_pads (mux, bestpad, pad) > 0) {
374         bestpad = pad;
375       }
376     }
377   }
378
379   return bestpad;
380 }
381
382 /* basic idea:
383  *
384  * 1) find a pad to pull on, this is done by pulling on all pads and
385  *    looking at the buffers to decide which one should be muxed first.
386  * 2) create a new buffer for the header
387  * 3) push both buffers on best pad, go to 1
388  */
389 static GstFlowReturn
390 gst_multipart_mux_collected (GstCollectPads * pads, GstMultipartMux * mux)
391 {
392   GstMultipartPadData *best;
393   GstFlowReturn ret = GST_FLOW_OK;
394   gchar *header = NULL;
395   size_t headerlen;
396   GstBuffer *headerbuf = NULL;
397   GstBuffer *footerbuf = NULL;
398   GstBuffer *databuf = NULL;
399   GstStructure *structure = NULL;
400   GstCaps *caps;
401   const gchar *mime;
402
403   GST_DEBUG_OBJECT (mux, "all pads are collected");
404
405   /* queue buffers on all pads; find a buffer with the lowest timestamp */
406   best = gst_multipart_mux_queue_pads (mux);
407   if (!best)
408     /* EOS */
409     goto eos;
410   else if (!best->buffer)
411     goto buffer_error;
412
413   /* If not negotiated yet set caps on src pad */
414   if (!mux->negotiated) {
415     GstCaps *newcaps;
416
417     newcaps = gst_caps_new_simple ("multipart/x-mixed-replace",
418         "boundary", G_TYPE_STRING, mux->boundary, NULL);
419
420     if (!gst_pad_set_caps (mux->srcpad, newcaps)) {
421       gst_caps_unref (newcaps);
422       goto nego_error;
423     }
424
425     gst_caps_unref (newcaps);
426     mux->negotiated = TRUE;
427   }
428
429   /* see if we need to push a segment */
430   if (mux->need_segment) {
431     GstClockTime time;
432     GstSegment segment;
433
434     if (best->timestamp != -1)
435       time = best->timestamp;
436     else
437       time = 0;
438
439     /* for the segment, we take the first timestamp we see, we don't know the
440      * length and the position is 0 */
441     gst_segment_init (&segment, GST_FORMAT_TIME);
442     segment.start = time;
443
444     gst_pad_push_event (mux->srcpad, gst_event_new_segment (&segment));
445
446     mux->need_segment = FALSE;
447   }
448
449   caps = gst_pad_get_current_caps (best->pad);
450   if (caps == NULL)
451     goto no_caps;
452
453   structure = gst_caps_get_structure (caps, 0);
454   if (!structure) {
455     gst_caps_unref (caps);
456     goto no_caps;
457   }
458
459   /* get the mime type for the structure */
460   mime = gst_multipart_mux_get_mime (mux, structure);
461   gst_caps_unref (caps);
462
463   header = g_strdup_printf ("--%s\r\nContent-Type: %s\r\n"
464       "Content-Length: %" G_GSIZE_FORMAT "\r\n\r\n",
465       mux->boundary, mime, gst_buffer_get_size (best->buffer));
466   headerlen = strlen (header);
467
468   headerbuf = gst_buffer_new_allocate (NULL, headerlen, 1);
469   gst_buffer_fill (headerbuf, 0, header, headerlen);
470   g_free (header);
471
472   /* the header has the same timestamp as the data buffer (which we will push
473    * below) and has a duration of 0 */
474   GST_BUFFER_TIMESTAMP (headerbuf) = best->timestamp;
475   GST_BUFFER_DURATION (headerbuf) = 0;
476   GST_BUFFER_OFFSET (headerbuf) = mux->offset;
477   mux->offset += headerlen;
478   GST_BUFFER_OFFSET_END (headerbuf) = mux->offset;
479
480   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes header buffer",
481       headerlen);
482   ret = gst_pad_push (mux->srcpad, headerbuf);
483   if (ret != GST_FLOW_OK)
484     /* push always takes ownership of the buffer, even after an error, so we
485      * don't need to unref headerbuf here. */
486     goto beach;
487
488   /* take best->buffer, we don't need to unref it later as we will push it
489    * now. */
490   databuf = gst_buffer_make_writable (best->buffer);
491   best->buffer = NULL;
492
493   /* we need to updated the timestamp to match the running_time */
494   GST_BUFFER_TIMESTAMP (databuf) = best->timestamp;
495   GST_BUFFER_OFFSET (databuf) = mux->offset;
496   mux->offset += gst_buffer_get_size (databuf);
497   GST_BUFFER_OFFSET_END (databuf) = mux->offset;
498   GST_BUFFER_FLAG_SET (databuf, GST_BUFFER_FLAG_DELTA_UNIT);
499
500   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes data buffer",
501       gst_buffer_get_size (databuf));
502   ret = gst_pad_push (mux->srcpad, databuf);
503   if (ret != GST_FLOW_OK)
504     /* push always takes ownership of the buffer, even after an error, so we
505      * don't need to unref headerbuf here. */
506     goto beach;
507
508   footerbuf = gst_buffer_new_allocate (NULL, 2, 1);
509   gst_buffer_fill (footerbuf, 0, "\r\n", 2);
510
511   /* the footer has the same timestamp as the data buffer and has a
512    * duration of 0 */
513   GST_BUFFER_TIMESTAMP (footerbuf) = best->timestamp;
514   GST_BUFFER_DURATION (footerbuf) = 0;
515   GST_BUFFER_OFFSET (footerbuf) = mux->offset;
516   mux->offset += 2;
517   GST_BUFFER_OFFSET_END (footerbuf) = mux->offset;
518   GST_BUFFER_FLAG_SET (footerbuf, GST_BUFFER_FLAG_DELTA_UNIT);
519
520   GST_DEBUG_OBJECT (mux, "pushing 2 bytes footer buffer");
521   ret = gst_pad_push (mux->srcpad, footerbuf);
522
523 beach:
524   if (best && best->buffer) {
525     gst_buffer_unref (best->buffer);
526     best->buffer = NULL;
527   }
528   return ret;
529
530   /* ERRORS */
531 buffer_error:
532   {
533     /* There is a best but no buffer, this is not quite right.. */
534     GST_ELEMENT_ERROR (mux, STREAM, FAILED, (NULL), ("internal muxing error"));
535     ret = GST_FLOW_ERROR;
536     goto beach;
537   }
538 eos:
539   {
540     GST_DEBUG_OBJECT (mux, "Pushing EOS");
541     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
542     ret = GST_FLOW_UNEXPECTED;
543     goto beach;
544   }
545 nego_error:
546   {
547     GST_WARNING_OBJECT (mux, "failed to set caps");
548     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
549     ret = GST_FLOW_NOT_NEGOTIATED;
550     goto beach;
551   }
552 no_caps:
553   {
554     GST_WARNING_OBJECT (mux, "no caps on the incoming buffer %p", best->buffer);
555     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
556     ret = GST_FLOW_NOT_NEGOTIATED;
557     goto beach;
558   }
559 }
560
561 static void
562 gst_multipart_mux_get_property (GObject * object,
563     guint prop_id, GValue * value, GParamSpec * pspec)
564 {
565   GstMultipartMux *mux;
566
567   mux = GST_MULTIPART_MUX (object);
568
569   switch (prop_id) {
570     case ARG_BOUNDARY:
571       g_value_set_string (value, mux->boundary);
572       break;
573     default:
574       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
575       break;
576   }
577 }
578
579 static void
580 gst_multipart_mux_set_property (GObject * object,
581     guint prop_id, const GValue * value, GParamSpec * pspec)
582 {
583   GstMultipartMux *mux;
584
585   mux = GST_MULTIPART_MUX (object);
586
587   switch (prop_id) {
588     case ARG_BOUNDARY:
589       g_free (mux->boundary);
590       mux->boundary = g_strdup (g_value_get_string (value));
591       break;
592     default:
593       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594       break;
595   }
596 }
597
598 static GstStateChangeReturn
599 gst_multipart_mux_change_state (GstElement * element, GstStateChange transition)
600 {
601   GstMultipartMux *multipart_mux;
602   GstStateChangeReturn ret;
603
604   multipart_mux = GST_MULTIPART_MUX (element);
605
606   switch (transition) {
607     case GST_STATE_CHANGE_READY_TO_PAUSED:
608       multipart_mux->offset = 0;
609       multipart_mux->negotiated = FALSE;
610       multipart_mux->need_segment = TRUE;
611       GST_DEBUG_OBJECT (multipart_mux, "starting collect pads");
612       gst_collect_pads_start (multipart_mux->collect);
613       break;
614     case GST_STATE_CHANGE_PAUSED_TO_READY:
615       GST_DEBUG_OBJECT (multipart_mux, "stopping collect pads");
616       gst_collect_pads_stop (multipart_mux->collect);
617       break;
618     default:
619       break;
620   }
621
622   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
623   if (ret == GST_STATE_CHANGE_FAILURE)
624     return ret;
625
626   switch (transition) {
627     default:
628       break;
629   }
630
631   return ret;
632 }
633
634 gboolean
635 gst_multipart_mux_plugin_init (GstPlugin * plugin)
636 {
637   GST_DEBUG_CATEGORY_INIT (gst_multipart_mux_debug, "multipartmux", 0,
638       "multipart muxer");
639
640   return gst_element_register (plugin, "multipartmux", GST_RANK_NONE,
641       GST_TYPE_MULTIPART_MUX);
642 }