tizen 2.0 init
[framework/multimedia/gst-plugins-good0.10.git] / gst / rtp / gstrtpmp4adepay.c
1 /* GStreamer
2  * Copyright (C) <2007> Nokia Corporation (contact <stefan.kost@nokia.com>)
3  *               <2007> Wim Taymans <wim.taymans@gmail.com>
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 version 2 as published by the Free Software Foundation.
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 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <gst/base/gstbitreader.h>
25 #include <gst/rtp/gstrtpbuffer.h>
26
27 #include <string.h>
28 #include "gstrtpmp4adepay.h"
29
30 GST_DEBUG_CATEGORY_STATIC (rtpmp4adepay_debug);
31 #define GST_CAT_DEFAULT (rtpmp4adepay_debug)
32
33 static GstStaticPadTemplate gst_rtp_mp4a_depay_src_template =
34 GST_STATIC_PAD_TEMPLATE ("src",
35     GST_PAD_SRC,
36     GST_PAD_ALWAYS,
37     GST_STATIC_CAPS ("audio/mpeg,"
38         "mpegversion = (int) 4," "framed = (boolean) true, "
39         "stream-format = (string) raw")
40     );
41
42 static GstStaticPadTemplate gst_rtp_mp4a_depay_sink_template =
43 GST_STATIC_PAD_TEMPLATE ("sink",
44     GST_PAD_SINK,
45     GST_PAD_ALWAYS,
46     GST_STATIC_CAPS ("application/x-rtp, "
47         "media = (string) \"audio\", "
48         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
49         "clock-rate = (int) [1, MAX ], "
50         "encoding-name = (string) \"MP4A-LATM\""
51         /* All optional parameters
52          *
53          * "profile-level-id=[1,MAX]"
54          * "config="
55          */
56     )
57     );
58
59 GST_BOILERPLATE (GstRtpMP4ADepay, gst_rtp_mp4a_depay, GstBaseRTPDepayload,
60     GST_TYPE_BASE_RTP_DEPAYLOAD);
61
62 static void gst_rtp_mp4a_depay_finalize (GObject * object);
63
64 static gboolean gst_rtp_mp4a_depay_setcaps (GstBaseRTPDepayload * depayload,
65     GstCaps * caps);
66 static GstBuffer *gst_rtp_mp4a_depay_process (GstBaseRTPDepayload * depayload,
67     GstBuffer * buf);
68
69 static GstStateChangeReturn gst_rtp_mp4a_depay_change_state (GstElement *
70     element, GstStateChange transition);
71
72
73 static void
74 gst_rtp_mp4a_depay_base_init (gpointer klass)
75 {
76   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
77
78   gst_element_class_add_static_pad_template (element_class,
79       &gst_rtp_mp4a_depay_src_template);
80   gst_element_class_add_static_pad_template (element_class,
81       &gst_rtp_mp4a_depay_sink_template);
82
83   gst_element_class_set_details_simple (element_class,
84       "RTP MPEG4 audio depayloader", "Codec/Depayloader/Network/RTP",
85       "Extracts MPEG4 audio from RTP packets (RFC 3016)",
86       "Nokia Corporation (contact <stefan.kost@nokia.com>), "
87       "Wim Taymans <wim.taymans@gmail.com>");
88 }
89
90 static void
91 gst_rtp_mp4a_depay_class_init (GstRtpMP4ADepayClass * klass)
92 {
93   GObjectClass *gobject_class;
94   GstElementClass *gstelement_class;
95   GstBaseRTPDepayloadClass *gstbasertpdepayload_class;
96
97   gobject_class = (GObjectClass *) klass;
98   gstelement_class = (GstElementClass *) klass;
99   gstbasertpdepayload_class = (GstBaseRTPDepayloadClass *) klass;
100
101   gobject_class->finalize = gst_rtp_mp4a_depay_finalize;
102
103   gstelement_class->change_state = gst_rtp_mp4a_depay_change_state;
104
105   gstbasertpdepayload_class->process = gst_rtp_mp4a_depay_process;
106   gstbasertpdepayload_class->set_caps = gst_rtp_mp4a_depay_setcaps;
107
108   GST_DEBUG_CATEGORY_INIT (rtpmp4adepay_debug, "rtpmp4adepay", 0,
109       "MPEG4 audio RTP Depayloader");
110 }
111
112 static void
113 gst_rtp_mp4a_depay_init (GstRtpMP4ADepay * rtpmp4adepay,
114     GstRtpMP4ADepayClass * klass)
115 {
116   rtpmp4adepay->adapter = gst_adapter_new ();
117 }
118
119 static void
120 gst_rtp_mp4a_depay_finalize (GObject * object)
121 {
122   GstRtpMP4ADepay *rtpmp4adepay;
123
124   rtpmp4adepay = GST_RTP_MP4A_DEPAY (object);
125
126   g_object_unref (rtpmp4adepay->adapter);
127   rtpmp4adepay->adapter = NULL;
128
129   G_OBJECT_CLASS (parent_class)->finalize (object);
130 }
131
132 static const guint aac_sample_rates[] = { 96000, 88200, 64000, 48000,
133   44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350
134 };
135
136 static gboolean
137 gst_rtp_mp4a_depay_setcaps (GstBaseRTPDepayload * depayload, GstCaps * caps)
138 {
139   GstStructure *structure;
140   GstRtpMP4ADepay *rtpmp4adepay;
141   GstCaps *srccaps;
142   const gchar *str;
143   gint clock_rate;
144   gint object_type;
145   gint channels = 2;            /* default */
146   gboolean res;
147
148   rtpmp4adepay = GST_RTP_MP4A_DEPAY (depayload);
149
150   structure = gst_caps_get_structure (caps, 0);
151
152   if (!gst_structure_get_int (structure, "clock-rate", &clock_rate))
153     clock_rate = 90000;         /* default */
154   depayload->clock_rate = clock_rate;
155
156   if (!gst_structure_get_int (structure, "object", &object_type))
157     object_type = 2;            /* AAC LC default */
158
159   srccaps = gst_caps_new_simple ("audio/mpeg",
160       "mpegversion", G_TYPE_INT, 4,
161       "framed", G_TYPE_BOOLEAN, TRUE, "channels", G_TYPE_INT, channels,
162       "stream-format", G_TYPE_STRING, "raw", NULL);
163
164   if ((str = gst_structure_get_string (structure, "config"))) {
165     GValue v = { 0 };
166
167     g_value_init (&v, GST_TYPE_BUFFER);
168     if (gst_value_deserialize (&v, str)) {
169       GstBuffer *buffer;
170       guint8 *data;
171       guint size;
172       gint i;
173       guint32 rate = 0;
174       guint8 obj_type = 0, sr_idx = 0, channels = 0;
175       GstBitReader br;
176
177       buffer = gst_value_get_buffer (&v);
178       gst_buffer_ref (buffer);
179       g_value_unset (&v);
180
181       data = GST_BUFFER_DATA (buffer);
182       size = GST_BUFFER_SIZE (buffer);
183
184       if (size < 2) {
185         GST_WARNING_OBJECT (depayload, "config too short (%d < 2)", size);
186         goto bad_config;
187       }
188
189       /* Parse StreamMuxConfig according to ISO/IEC 14496-3:
190        *
191        * audioMuxVersion           == 0 (1 bit)
192        * allStreamsSameTimeFraming == 1 (1 bit)
193        * numSubFrames              == rtpmp4adepay->numSubFrames (6 bits)
194        * numProgram                == 0 (4 bits)
195        * numLayer                  == 0 (3 bits)
196        *
197        * We only require audioMuxVersion == 0;
198        *
199        * The remaining bit of the second byte and the rest of the bits are used
200        * for audioSpecificConfig which we need to set in codec_info.
201        */
202       if ((data[0] & 0x80) != 0x00) {
203         GST_WARNING_OBJECT (depayload, "unknown audioMuxVersion 1");
204         goto bad_config;
205       }
206
207       rtpmp4adepay->numSubFrames = (data[0] & 0x3F);
208
209       GST_LOG_OBJECT (rtpmp4adepay, "numSubFrames %d",
210           rtpmp4adepay->numSubFrames);
211
212       /* shift rest of string 15 bits down */
213       size -= 2;
214       for (i = 0; i < size; i++) {
215         data[i] = ((data[i + 1] & 1) << 7) | ((data[i + 2] & 0xfe) >> 1);
216       }
217       /* ignore remaining bit, we're only interested in full bytes */
218       GST_BUFFER_SIZE (buffer) = size;
219
220       gst_bit_reader_init (&br, data, size);
221
222       /* any object type is fine, we need to copy it to the profile-level-id field. */
223       if (!gst_bit_reader_get_bits_uint8 (&br, &obj_type, 5))
224         goto bad_config;
225       if (obj_type == 0) {
226         GST_WARNING_OBJECT (depayload, "invalid object type 0");
227         goto bad_config;
228       }
229
230       if (!gst_bit_reader_get_bits_uint8 (&br, &sr_idx, 4))
231         goto bad_config;
232       if (sr_idx >= G_N_ELEMENTS (aac_sample_rates) && sr_idx != 15) {
233         GST_WARNING_OBJECT (depayload, "invalid sample rate index %d", sr_idx);
234         goto bad_config;
235       }
236       GST_LOG_OBJECT (rtpmp4adepay, "sample rate index %u", sr_idx);
237
238       if (!gst_bit_reader_get_bits_uint8 (&br, &channels, 4))
239         goto bad_config;
240       if (channels > 7) {
241         GST_WARNING_OBJECT (depayload, "invalid channels %u", (guint) channels);
242         goto bad_config;
243       }
244
245       /* rtp rate depends on sampling rate of the audio */
246       if (sr_idx == 15) {
247         /* index of 15 means we get the rate in the next 24 bits */
248         if (!gst_bit_reader_get_bits_uint32 (&br, &rate, 24))
249           goto bad_config;
250       } else if (sr_idx >= G_N_ELEMENTS (aac_sample_rates)) {
251         goto bad_config;
252       } else {
253         /* else use the rate from the table */
254         rate = aac_sample_rates[sr_idx];
255       }
256
257       rtpmp4adepay->frame_len = 1024;
258
259       switch (obj_type) {
260         case 1:
261         case 2:
262         case 3:
263         case 4:
264         case 6:
265         case 7:
266         {
267           guint8 frameLenFlag = 0;
268
269           if (gst_bit_reader_get_bits_uint8 (&br, &frameLenFlag, 1))
270             if (frameLenFlag)
271               rtpmp4adepay->frame_len = 960;
272           break;
273         }
274         default:
275           break;
276       }
277
278       gst_caps_set_simple (srccaps,
279           "channels", G_TYPE_INT, (gint) channels,
280           "rate", G_TYPE_INT, (gint) rate,
281           "codec_data", GST_TYPE_BUFFER, buffer, NULL);
282       gst_buffer_unref (buffer);
283     } else {
284       g_warning ("cannot convert config to buffer");
285     }
286   }
287 bad_config:
288   res = gst_pad_set_caps (depayload->srcpad, srccaps);
289   gst_caps_unref (srccaps);
290
291   return res;
292 }
293
294 static GstBuffer *
295 gst_rtp_mp4a_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf)
296 {
297   GstRtpMP4ADepay *rtpmp4adepay;
298   GstBuffer *outbuf;
299
300   rtpmp4adepay = GST_RTP_MP4A_DEPAY (depayload);
301
302   /* flush remaining data on discont */
303   if (GST_BUFFER_IS_DISCONT (buf)) {
304     gst_adapter_clear (rtpmp4adepay->adapter);
305   }
306
307   outbuf = gst_rtp_buffer_get_payload_buffer (buf);
308
309   gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_TIMESTAMPS);
310   gst_adapter_push (rtpmp4adepay->adapter, outbuf);
311
312   /* RTP marker bit indicates the last packet of the AudioMuxElement => create
313    * and push a buffer */
314   if (gst_rtp_buffer_get_marker (buf)) {
315     guint avail;
316     guint i;
317     guint8 *data;
318     guint pos;
319     GstClockTime timestamp;
320
321     avail = gst_adapter_available (rtpmp4adepay->adapter);
322     timestamp = gst_adapter_prev_timestamp (rtpmp4adepay->adapter, NULL);
323
324     GST_LOG_OBJECT (rtpmp4adepay, "have marker and %u available", avail);
325
326     outbuf = gst_adapter_take_buffer (rtpmp4adepay->adapter, avail);
327     data = GST_BUFFER_DATA (outbuf);
328     /* position in data we are at */
329     pos = 0;
330
331     /* looping through the number of sub-frames in the audio payload */
332     for (i = 0; i <= rtpmp4adepay->numSubFrames; i++) {
333       /* determine payload length and set buffer data pointer accordingly */
334       guint skip;
335       guint data_len;
336       GstBuffer *tmp = NULL;
337
338       /* each subframe starts with a variable length encoding */
339       data_len = 0;
340       for (skip = 0; skip < avail; skip++) {
341         data_len += data[skip];
342         if (data[skip] != 0xff)
343           break;
344       }
345       skip++;
346
347       /* this can not be possible, we have not enough data or the length
348        * decoding failed because we ran out of data. */
349       if (skip + data_len > avail)
350         goto wrong_size;
351
352       GST_LOG_OBJECT (rtpmp4adepay,
353           "subframe %u, header len %u, data len %u, left %u", i, skip, data_len,
354           avail);
355
356       /* take data out, skip the header */
357       pos += skip;
358       tmp = gst_buffer_create_sub (outbuf, pos, data_len);
359
360       /* skip data too */
361       skip += data_len;
362       pos += data_len;
363
364       /* update our pointers whith what we consumed */
365       data += skip;
366       avail -= skip;
367
368       GST_BUFFER_TIMESTAMP (tmp) = timestamp;
369       gst_base_rtp_depayload_push (depayload, tmp);
370
371       /* shift ts for next buffers */
372       if (rtpmp4adepay->frame_len && timestamp != -1
373           && depayload->clock_rate != 0) {
374         timestamp +=
375             gst_util_uint64_scale_int (rtpmp4adepay->frame_len, GST_SECOND,
376             depayload->clock_rate);
377       }
378     }
379
380     /* just a check that lengths match */
381     if (avail) {
382       GST_ELEMENT_WARNING (depayload, STREAM, DECODE,
383           ("Packet invalid"), ("Not all payload consumed: "
384               "possible wrongly encoded packet."));
385     }
386
387     gst_buffer_unref (outbuf);
388   }
389   return NULL;
390
391   /* ERRORS */
392 wrong_size:
393   {
394     GST_ELEMENT_WARNING (rtpmp4adepay, STREAM, DECODE,
395         ("Packet did not validate"), ("wrong packet size"));
396     gst_buffer_unref (outbuf);
397     return NULL;
398   }
399 }
400
401 static GstStateChangeReturn
402 gst_rtp_mp4a_depay_change_state (GstElement * element,
403     GstStateChange transition)
404 {
405   GstRtpMP4ADepay *rtpmp4adepay;
406   GstStateChangeReturn ret;
407
408   rtpmp4adepay = GST_RTP_MP4A_DEPAY (element);
409
410   switch (transition) {
411     case GST_STATE_CHANGE_READY_TO_PAUSED:
412       gst_adapter_clear (rtpmp4adepay->adapter);
413       rtpmp4adepay->frame_len = 0;
414       rtpmp4adepay->numSubFrames = 0;
415       break;
416     default:
417       break;
418   }
419
420   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
421
422   switch (transition) {
423     default:
424       break;
425   }
426   return ret;
427 }
428
429 gboolean
430 gst_rtp_mp4a_depay_plugin_init (GstPlugin * plugin)
431 {
432   return gst_element_register (plugin, "rtpmp4adepay",
433       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4A_DEPAY);
434 }