upload tizen1.0 source
[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_pad_template (element_class,
79       gst_static_pad_template_get (&gst_rtp_mp4a_depay_src_template));
80   gst_element_class_add_pad_template (element_class,
81       gst_static_pad_template_get (&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
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 > 12 && 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 {
251         /* else use the rate from the table */
252         rate = aac_sample_rates[sr_idx];
253       }
254
255       rtpmp4adepay->frame_len = 1024;
256
257       switch (obj_type) {
258         case 1:
259         case 2:
260         case 3:
261         case 4:
262         case 6:
263         case 7:
264         {
265           guint8 frameLenFlag = 0;
266
267           if (gst_bit_reader_get_bits_uint8 (&br, &frameLenFlag, 1))
268             if (frameLenFlag)
269               rtpmp4adepay->frame_len = 960;
270           break;
271         }
272         default:
273           break;
274       }
275
276       gst_caps_set_simple (srccaps,
277           "channels", G_TYPE_INT, (gint) channels,
278           "rate", G_TYPE_INT, (gint) rate,
279           "codec_data", GST_TYPE_BUFFER, buffer, NULL);
280       gst_buffer_unref (buffer);
281     } else {
282       g_warning ("cannot convert config to buffer");
283     }
284   }
285 bad_config:
286   res = gst_pad_set_caps (depayload->srcpad, srccaps);
287   gst_caps_unref (srccaps);
288
289   return res;
290 }
291
292 static GstBuffer *
293 gst_rtp_mp4a_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf)
294 {
295   GstRtpMP4ADepay *rtpmp4adepay;
296   GstBuffer *outbuf;
297
298   rtpmp4adepay = GST_RTP_MP4A_DEPAY (depayload);
299
300   /* flush remaining data on discont */
301   if (GST_BUFFER_IS_DISCONT (buf)) {
302     gst_adapter_clear (rtpmp4adepay->adapter);
303   }
304
305   outbuf = gst_rtp_buffer_get_payload_buffer (buf);
306
307   gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_TIMESTAMPS);
308   gst_adapter_push (rtpmp4adepay->adapter, outbuf);
309
310   /* RTP marker bit indicates the last packet of the AudioMuxElement => create
311    * and push a buffer */
312   if (gst_rtp_buffer_get_marker (buf)) {
313     guint avail;
314     guint i;
315     guint8 *data;
316     guint pos;
317     GstClockTime timestamp;
318     guint offset;
319
320     avail = gst_adapter_available (rtpmp4adepay->adapter);
321     timestamp = gst_adapter_prev_timestamp (rtpmp4adepay->adapter, NULL);
322
323     GST_LOG_OBJECT (rtpmp4adepay, "have marker and %u available", avail);
324
325     outbuf = gst_adapter_take_buffer (rtpmp4adepay->adapter, avail);
326     data = GST_BUFFER_DATA (outbuf);
327     /* position in data we are at */
328     pos = 0;
329     /* timestamp offset */
330     offset = 0;
331
332     /* looping through the number of sub-frames in the audio payload */
333     for (i = 0; i <= rtpmp4adepay->numSubFrames; i++) {
334       /* determine payload length and set buffer data pointer accordingly */
335       guint skip;
336       guint data_len;
337       GstBuffer *tmp = NULL;
338
339       /* each subframe starts with a variable length encoding */
340       data_len = 0;
341       for (skip = 0; skip < avail; skip++) {
342         data_len += data[skip];
343         if (data[skip] != 0xff)
344           break;
345       }
346       skip++;
347
348       /* this can not be possible, we have not enough data or the length
349        * decoding failed because we ran out of data. */
350       if (skip + data_len > avail)
351         goto wrong_size;
352
353       GST_LOG_OBJECT (rtpmp4adepay,
354           "subframe %u, header len %u, data len %u, left %u", i, skip, data_len,
355           avail);
356
357       /* take data out, skip the header */
358       pos += skip;
359       tmp = gst_buffer_create_sub (outbuf, pos, data_len);
360
361       /* skip data too */
362       skip += data_len;
363       pos += data_len;
364
365       /* update our pointers whith what we consumed */
366       data += skip;
367       avail -= skip;
368
369       if (offset > 0 && timestamp != -1 && depayload->clock_rate != 0) {
370         timestamp +=
371             gst_util_uint64_scale_int (offset, GST_SECOND,
372             depayload->clock_rate);
373       }
374
375       GST_BUFFER_TIMESTAMP (tmp) = timestamp;
376       gst_base_rtp_depayload_push (depayload, tmp);
377
378       /* calculate offsets for next buffers */
379       if (rtpmp4adepay->frame_len) {
380         offset += rtpmp4adepay->frame_len;
381       }
382     }
383
384     /* just a check that lengths match */
385     if (avail) {
386       GST_ELEMENT_WARNING (depayload, STREAM, DECODE,
387           ("Packet invalid"), ("Not all payload consumed: "
388               "possible wrongly encoded packet."));
389     }
390
391     gst_buffer_unref (outbuf);
392   }
393   return NULL;
394
395   /* ERRORS */
396 wrong_size:
397   {
398     GST_ELEMENT_WARNING (rtpmp4adepay, STREAM, DECODE,
399         ("Packet did not validate"), ("wrong packet size"));
400     gst_buffer_unref (outbuf);
401     return NULL;
402   }
403 }
404
405 static GstStateChangeReturn
406 gst_rtp_mp4a_depay_change_state (GstElement * element,
407     GstStateChange transition)
408 {
409   GstRtpMP4ADepay *rtpmp4adepay;
410   GstStateChangeReturn ret;
411
412   rtpmp4adepay = GST_RTP_MP4A_DEPAY (element);
413
414   switch (transition) {
415     case GST_STATE_CHANGE_READY_TO_PAUSED:
416       gst_adapter_clear (rtpmp4adepay->adapter);
417       rtpmp4adepay->frame_len = 0;
418       rtpmp4adepay->numSubFrames = 0;
419       break;
420     default:
421       break;
422   }
423
424   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
425
426   switch (transition) {
427     default:
428       break;
429   }
430   return ret;
431 }
432
433 gboolean
434 gst_rtp_mp4a_depay_plugin_init (GstPlugin * plugin)
435 {
436   return gst_element_register (plugin, "rtpmp4adepay",
437       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4A_DEPAY);
438 }