gst: Update for GST_PLUGIN_DEFINE() API changes
[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   static GstAllocationParams params = { 0, 0, 0, 1, };
399
400   GST_DEBUG_OBJECT (mux, "all pads are collected");
401
402   /* queue buffers on all pads; find a buffer with the lowest timestamp */
403   best = gst_multipart_mux_queue_pads (mux);
404   if (!best)
405     /* EOS */
406     goto eos;
407   else if (!best->buffer)
408     goto buffer_error;
409
410   /* If not negotiated yet set caps on src pad */
411   if (!mux->negotiated) {
412     GstCaps *newcaps;
413
414     newcaps = gst_caps_new_simple ("multipart/x-mixed-replace",
415         "boundary", G_TYPE_STRING, mux->boundary, NULL);
416
417     if (!gst_pad_set_caps (mux->srcpad, newcaps)) {
418       gst_caps_unref (newcaps);
419       goto nego_error;
420     }
421
422     gst_caps_unref (newcaps);
423     mux->negotiated = TRUE;
424   }
425
426   /* see if we need to push a segment */
427   if (mux->need_segment) {
428     GstClockTime time;
429     GstSegment segment;
430
431     if (best->timestamp != -1)
432       time = best->timestamp;
433     else
434       time = 0;
435
436     /* for the segment, we take the first timestamp we see, we don't know the
437      * length and the position is 0 */
438     gst_segment_init (&segment, GST_FORMAT_TIME);
439     segment.start = time;
440
441     gst_pad_push_event (mux->srcpad, gst_event_new_segment (&segment));
442
443     mux->need_segment = FALSE;
444   }
445
446   caps = gst_pad_get_current_caps (best->pad);
447   if (caps == NULL)
448     goto no_caps;
449
450   structure = gst_caps_get_structure (caps, 0);
451   if (!structure) {
452     gst_caps_unref (caps);
453     goto no_caps;
454   }
455
456   /* get the mime type for the structure */
457   mime = gst_multipart_mux_get_mime (mux, structure);
458   gst_caps_unref (caps);
459
460   header = g_strdup_printf ("--%s\r\nContent-Type: %s\r\n"
461       "Content-Length: %" G_GSIZE_FORMAT "\r\n\r\n",
462       mux->boundary, mime, gst_buffer_get_size (best->buffer));
463   headerlen = strlen (header);
464
465   headerbuf = gst_buffer_new_allocate (NULL, headerlen, &params);
466   gst_buffer_fill (headerbuf, 0, header, headerlen);
467   g_free (header);
468
469   /* the header has the same timestamp as the data buffer (which we will push
470    * below) and has a duration of 0 */
471   GST_BUFFER_TIMESTAMP (headerbuf) = best->timestamp;
472   GST_BUFFER_DURATION (headerbuf) = 0;
473   GST_BUFFER_OFFSET (headerbuf) = mux->offset;
474   mux->offset += headerlen;
475   GST_BUFFER_OFFSET_END (headerbuf) = mux->offset;
476
477   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes header buffer",
478       headerlen);
479   ret = gst_pad_push (mux->srcpad, headerbuf);
480   if (ret != GST_FLOW_OK)
481     /* push always takes ownership of the buffer, even after an error, so we
482      * don't need to unref headerbuf here. */
483     goto beach;
484
485   /* take best->buffer, we don't need to unref it later as we will push it
486    * now. */
487   databuf = gst_buffer_make_writable (best->buffer);
488   best->buffer = NULL;
489
490   /* we need to updated the timestamp to match the running_time */
491   GST_BUFFER_TIMESTAMP (databuf) = best->timestamp;
492   GST_BUFFER_OFFSET (databuf) = mux->offset;
493   mux->offset += gst_buffer_get_size (databuf);
494   GST_BUFFER_OFFSET_END (databuf) = mux->offset;
495   GST_BUFFER_FLAG_SET (databuf, GST_BUFFER_FLAG_DELTA_UNIT);
496
497   GST_DEBUG_OBJECT (mux, "pushing %" G_GSIZE_FORMAT " bytes data buffer",
498       gst_buffer_get_size (databuf));
499   ret = gst_pad_push (mux->srcpad, databuf);
500   if (ret != GST_FLOW_OK)
501     /* push always takes ownership of the buffer, even after an error, so we
502      * don't need to unref headerbuf here. */
503     goto beach;
504
505   footerbuf = gst_buffer_new_allocate (NULL, 2, &params);
506   gst_buffer_fill (footerbuf, 0, "\r\n", 2);
507
508   /* the footer has the same timestamp as the data buffer and has a
509    * duration of 0 */
510   GST_BUFFER_TIMESTAMP (footerbuf) = best->timestamp;
511   GST_BUFFER_DURATION (footerbuf) = 0;
512   GST_BUFFER_OFFSET (footerbuf) = mux->offset;
513   mux->offset += 2;
514   GST_BUFFER_OFFSET_END (footerbuf) = mux->offset;
515   GST_BUFFER_FLAG_SET (footerbuf, GST_BUFFER_FLAG_DELTA_UNIT);
516
517   GST_DEBUG_OBJECT (mux, "pushing 2 bytes footer buffer");
518   ret = gst_pad_push (mux->srcpad, footerbuf);
519
520 beach:
521   if (best && best->buffer) {
522     gst_buffer_unref (best->buffer);
523     best->buffer = NULL;
524   }
525   return ret;
526
527   /* ERRORS */
528 buffer_error:
529   {
530     /* There is a best but no buffer, this is not quite right.. */
531     GST_ELEMENT_ERROR (mux, STREAM, FAILED, (NULL), ("internal muxing error"));
532     ret = GST_FLOW_ERROR;
533     goto beach;
534   }
535 eos:
536   {
537     GST_DEBUG_OBJECT (mux, "Pushing EOS");
538     gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
539     ret = GST_FLOW_EOS;
540     goto beach;
541   }
542 nego_error:
543   {
544     GST_WARNING_OBJECT (mux, "failed to set caps");
545     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
546     ret = GST_FLOW_NOT_NEGOTIATED;
547     goto beach;
548   }
549 no_caps:
550   {
551     GST_WARNING_OBJECT (mux, "no caps on the incoming buffer %p", best->buffer);
552     GST_ELEMENT_ERROR (mux, CORE, NEGOTIATION, (NULL), (NULL));
553     ret = GST_FLOW_NOT_NEGOTIATED;
554     goto beach;
555   }
556 }
557
558 static void
559 gst_multipart_mux_get_property (GObject * object,
560     guint prop_id, GValue * value, GParamSpec * pspec)
561 {
562   GstMultipartMux *mux;
563
564   mux = GST_MULTIPART_MUX (object);
565
566   switch (prop_id) {
567     case ARG_BOUNDARY:
568       g_value_set_string (value, mux->boundary);
569       break;
570     default:
571       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
572       break;
573   }
574 }
575
576 static void
577 gst_multipart_mux_set_property (GObject * object,
578     guint prop_id, const GValue * value, GParamSpec * pspec)
579 {
580   GstMultipartMux *mux;
581
582   mux = GST_MULTIPART_MUX (object);
583
584   switch (prop_id) {
585     case ARG_BOUNDARY:
586       g_free (mux->boundary);
587       mux->boundary = g_strdup (g_value_get_string (value));
588       break;
589     default:
590       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
591       break;
592   }
593 }
594
595 static GstStateChangeReturn
596 gst_multipart_mux_change_state (GstElement * element, GstStateChange transition)
597 {
598   GstMultipartMux *multipart_mux;
599   GstStateChangeReturn ret;
600
601   multipart_mux = GST_MULTIPART_MUX (element);
602
603   switch (transition) {
604     case GST_STATE_CHANGE_READY_TO_PAUSED:
605       multipart_mux->offset = 0;
606       multipart_mux->negotiated = FALSE;
607       multipart_mux->need_segment = TRUE;
608       GST_DEBUG_OBJECT (multipart_mux, "starting collect pads");
609       gst_collect_pads2_start (multipart_mux->collect);
610       break;
611     case GST_STATE_CHANGE_PAUSED_TO_READY:
612       GST_DEBUG_OBJECT (multipart_mux, "stopping collect pads");
613       gst_collect_pads2_stop (multipart_mux->collect);
614       break;
615     default:
616       break;
617   }
618
619   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
620   if (ret == GST_STATE_CHANGE_FAILURE)
621     return ret;
622
623   switch (transition) {
624     default:
625       break;
626   }
627
628   return ret;
629 }
630
631 gboolean
632 gst_multipart_mux_plugin_init (GstPlugin * plugin)
633 {
634   GST_DEBUG_CATEGORY_INIT (gst_multipart_mux_debug, "multipartmux", 0,
635       "multipart muxer");
636
637   return gst_element_register (plugin, "multipartmux", GST_RANK_NONE,
638       GST_TYPE_MULTIPART_MUX);
639 }