Merge branch 'master' into 0.11
[platform/upstream/gst-plugins-good.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 #define gst_rtp_mp4a_depay_parent_class parent_class
60 G_DEFINE_TYPE (GstRtpMP4ADepay, gst_rtp_mp4a_depay,
61     GST_TYPE_BASE_RTP_DEPAYLOAD);
62
63 static void gst_rtp_mp4a_depay_finalize (GObject * object);
64
65 static gboolean gst_rtp_mp4a_depay_setcaps (GstBaseRTPDepayload * depayload,
66     GstCaps * caps);
67 static GstBuffer *gst_rtp_mp4a_depay_process (GstBaseRTPDepayload * depayload,
68     GstBuffer * buf);
69
70 static GstStateChangeReturn gst_rtp_mp4a_depay_change_state (GstElement *
71     element, GstStateChange transition);
72
73
74 static void
75 gst_rtp_mp4a_depay_class_init (GstRtpMP4ADepayClass * klass)
76 {
77   GObjectClass *gobject_class;
78   GstElementClass *gstelement_class;
79   GstBaseRTPDepayloadClass *gstbasertpdepayload_class;
80
81   gobject_class = (GObjectClass *) klass;
82   gstelement_class = (GstElementClass *) klass;
83   gstbasertpdepayload_class = (GstBaseRTPDepayloadClass *) klass;
84
85   gobject_class->finalize = gst_rtp_mp4a_depay_finalize;
86
87   gstelement_class->change_state = gst_rtp_mp4a_depay_change_state;
88
89   gstbasertpdepayload_class->process = gst_rtp_mp4a_depay_process;
90   gstbasertpdepayload_class->set_caps = gst_rtp_mp4a_depay_setcaps;
91
92   gst_element_class_add_pad_template (gstelement_class,
93       gst_static_pad_template_get (&gst_rtp_mp4a_depay_src_template));
94   gst_element_class_add_pad_template (gstelement_class,
95       gst_static_pad_template_get (&gst_rtp_mp4a_depay_sink_template));
96
97   gst_element_class_set_details_simple (gstelement_class,
98       "RTP MPEG4 audio depayloader", "Codec/Depayloader/Network/RTP",
99       "Extracts MPEG4 audio from RTP packets (RFC 3016)",
100       "Nokia Corporation (contact <stefan.kost@nokia.com>), "
101       "Wim Taymans <wim.taymans@gmail.com>");
102
103   GST_DEBUG_CATEGORY_INIT (rtpmp4adepay_debug, "rtpmp4adepay", 0,
104       "MPEG4 audio RTP Depayloader");
105 }
106
107 static void
108 gst_rtp_mp4a_depay_init (GstRtpMP4ADepay * rtpmp4adepay)
109 {
110   rtpmp4adepay->adapter = gst_adapter_new ();
111 }
112
113 static void
114 gst_rtp_mp4a_depay_finalize (GObject * object)
115 {
116   GstRtpMP4ADepay *rtpmp4adepay;
117
118   rtpmp4adepay = GST_RTP_MP4A_DEPAY (object);
119
120   g_object_unref (rtpmp4adepay->adapter);
121   rtpmp4adepay->adapter = NULL;
122
123   G_OBJECT_CLASS (parent_class)->finalize (object);
124 }
125
126 static const guint aac_sample_rates[] = { 96000, 88200, 64000, 48000,
127   44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000
128 };
129
130 static gboolean
131 gst_rtp_mp4a_depay_setcaps (GstBaseRTPDepayload * depayload, GstCaps * caps)
132 {
133   GstStructure *structure;
134   GstRtpMP4ADepay *rtpmp4adepay;
135   GstCaps *srccaps;
136   const gchar *str;
137   gint clock_rate;
138   gint object_type;
139   gint channels = 2;            /* default */
140   gboolean res;
141
142   rtpmp4adepay = GST_RTP_MP4A_DEPAY (depayload);
143
144   structure = gst_caps_get_structure (caps, 0);
145
146   if (!gst_structure_get_int (structure, "clock-rate", &clock_rate))
147     clock_rate = 90000;         /* default */
148   depayload->clock_rate = clock_rate;
149
150   if (!gst_structure_get_int (structure, "object", &object_type))
151     object_type = 2;            /* AAC LC default */
152
153   srccaps = gst_caps_new_simple ("audio/mpeg",
154       "mpegversion", G_TYPE_INT, 4,
155       "framed", G_TYPE_BOOLEAN, TRUE, "channels", G_TYPE_INT, channels,
156       "stream-format", G_TYPE_STRING, "raw", NULL);
157
158   if ((str = gst_structure_get_string (structure, "config"))) {
159     GValue v = { 0 };
160
161     g_value_init (&v, GST_TYPE_BUFFER);
162     if (gst_value_deserialize (&v, str)) {
163       GstBuffer *buffer;
164       guint8 *data;
165       gsize size;
166       gint i;
167       guint32 rate = 0;
168       guint8 obj_type = 0, sr_idx = 0, channels = 0;
169       GstBitReader br;
170
171       buffer = gst_value_get_buffer (&v);
172       gst_buffer_ref (buffer);
173       g_value_unset (&v);
174
175       data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
176
177       if (size < 2) {
178         GST_WARNING_OBJECT (depayload, "config too short (%d < 2)",
179             (gint) size);
180         goto bad_config;
181       }
182
183       /* Parse StreamMuxConfig according to ISO/IEC 14496-3:
184        *
185        * audioMuxVersion           == 0 (1 bit)
186        * allStreamsSameTimeFraming == 1 (1 bit)
187        * numSubFrames              == rtpmp4adepay->numSubFrames (6 bits)
188        * numProgram                == 0 (4 bits)
189        * numLayer                  == 0 (3 bits)
190        *
191        * We only require audioMuxVersion == 0;
192        *
193        * The remaining bit of the second byte and the rest of the bits are used
194        * for audioSpecificConfig which we need to set in codec_info.
195        */
196       if ((data[0] & 0x80) != 0x00) {
197         GST_WARNING_OBJECT (depayload, "unknown audioMuxVersion 1");
198         goto bad_config;
199       }
200
201       rtpmp4adepay->numSubFrames = (data[0] & 0x3F);
202
203       GST_LOG_OBJECT (rtpmp4adepay, "numSubFrames %d",
204           rtpmp4adepay->numSubFrames);
205
206       /* shift rest of string 15 bits down */
207       size -= 2;
208       for (i = 0; i < size; i++) {
209         data[i] = ((data[i + 1] & 1) << 7) | ((data[i + 2] & 0xfe) >> 1);
210       }
211
212       gst_bit_reader_init (&br, data, size);
213
214       /* any object type is fine, we need to copy it to the profile-level-id field. */
215       if (!gst_bit_reader_get_bits_uint8 (&br, &obj_type, 5))
216         goto bad_config;
217       if (obj_type == 0) {
218         GST_WARNING_OBJECT (depayload, "invalid object type 0");
219         goto bad_config;
220       }
221
222       if (!gst_bit_reader_get_bits_uint8 (&br, &sr_idx, 4))
223         goto bad_config;
224       if (sr_idx >= G_N_ELEMENTS (aac_sample_rates) && sr_idx != 15) {
225         GST_WARNING_OBJECT (depayload, "invalid sample rate index %d", sr_idx);
226         goto bad_config;
227       }
228       GST_LOG_OBJECT (rtpmp4adepay, "sample rate index %u", sr_idx);
229
230       if (!gst_bit_reader_get_bits_uint8 (&br, &channels, 4))
231         goto bad_config;
232       if (channels > 7) {
233         GST_WARNING_OBJECT (depayload, "invalid channels %u", (guint) channels);
234         goto bad_config;
235       }
236
237       /* rtp rate depends on sampling rate of the audio */
238       if (sr_idx == 15) {
239         /* index of 15 means we get the rate in the next 24 bits */
240         if (!gst_bit_reader_get_bits_uint32 (&br, &rate, 24))
241           goto bad_config;
242       } else {
243         /* else use the rate from the table */
244         rate = aac_sample_rates[sr_idx];
245       }
246
247       rtpmp4adepay->frame_len = 1024;
248
249       switch (obj_type) {
250         case 1:
251         case 2:
252         case 3:
253         case 4:
254         case 6:
255         case 7:
256         {
257           guint8 frameLenFlag = 0;
258
259           if (gst_bit_reader_get_bits_uint8 (&br, &frameLenFlag, 1))
260             if (frameLenFlag)
261               rtpmp4adepay->frame_len = 960;
262           break;
263         }
264         default:
265           break;
266       }
267
268       /* ignore remaining bit, we're only interested in full bytes */
269       gst_buffer_unmap (buffer, data, size);
270       data = NULL;
271
272       gst_caps_set_simple (srccaps,
273           "channels", G_TYPE_INT, (gint) channels,
274           "rate", G_TYPE_INT, (gint) rate,
275           "codec_data", GST_TYPE_BUFFER, buffer, NULL);
276     bad_config:
277       if (data)
278         gst_buffer_unmap (buffer, data, -1);
279       gst_buffer_unref (buffer);
280     } else {
281       g_warning ("cannot convert config to buffer");
282     }
283   }
284   res = gst_pad_set_caps (depayload->srcpad, srccaps);
285   gst_caps_unref (srccaps);
286
287   return res;
288 }
289
290 static GstBuffer *
291 gst_rtp_mp4a_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf)
292 {
293   GstRtpMP4ADepay *rtpmp4adepay;
294   GstBuffer *outbuf;
295   GstRTPBuffer rtp;
296   guint8 *bdata;
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   gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp);
306   outbuf = gst_rtp_buffer_get_payload_buffer (&rtp);
307
308   outbuf = gst_buffer_make_writable (outbuf);
309   GST_BUFFER_TIMESTAMP (outbuf) = GST_BUFFER_TIMESTAMP (buf);
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 (&rtp)) {
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 = bdata = gst_buffer_map (outbuf, NULL, NULL, GST_MAP_READ);
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_copy_region (outbuf, GST_BUFFER_COPY_MEMORY, pos,
359           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       GST_BUFFER_TIMESTAMP (tmp) = timestamp;
370       gst_base_rtp_depayload_push (depayload, tmp);
371
372       /* shift ts for next buffers */
373       if (rtpmp4adepay->frame_len && timestamp != -1
374           && depayload->clock_rate != 0) {
375         timestamp +=
376             gst_util_uint64_scale_int (rtpmp4adepay->frame_len, GST_SECOND,
377             depayload->clock_rate);
378       }
379     }
380
381     /* just a check that lengths match */
382     if (avail) {
383       GST_ELEMENT_WARNING (depayload, STREAM, DECODE,
384           ("Packet invalid"), ("Not all payload consumed: "
385               "possible wrongly encoded packet."));
386     }
387
388     gst_buffer_unmap (outbuf, bdata, -1);
389     gst_buffer_unref (outbuf);
390   }
391   gst_rtp_buffer_unmap (&rtp);
392   return NULL;
393
394   /* ERRORS */
395 wrong_size:
396   {
397     GST_ELEMENT_WARNING (rtpmp4adepay, STREAM, DECODE,
398         ("Packet did not validate"), ("wrong packet size"));
399     gst_buffer_unmap (outbuf, bdata, -1);
400     gst_buffer_unref (outbuf);
401     gst_rtp_buffer_unmap (&rtp);
402     return NULL;
403   }
404 }
405
406 static GstStateChangeReturn
407 gst_rtp_mp4a_depay_change_state (GstElement * element,
408     GstStateChange transition)
409 {
410   GstRtpMP4ADepay *rtpmp4adepay;
411   GstStateChangeReturn ret;
412
413   rtpmp4adepay = GST_RTP_MP4A_DEPAY (element);
414
415   switch (transition) {
416     case GST_STATE_CHANGE_READY_TO_PAUSED:
417       gst_adapter_clear (rtpmp4adepay->adapter);
418       rtpmp4adepay->frame_len = 0;
419       rtpmp4adepay->numSubFrames = 0;
420       break;
421     default:
422       break;
423   }
424
425   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
426
427   switch (transition) {
428     default:
429       break;
430   }
431   return ret;
432 }
433
434 gboolean
435 gst_rtp_mp4a_depay_plugin_init (GstPlugin * plugin)
436 {
437   return gst_element_register (plugin, "rtpmp4adepay",
438       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4A_DEPAY);
439 }