gstdepay: check for correct fragment offset
[platform/upstream/gstreamer.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_RTP_BASE_DEPAYLOAD);
62
63 static void gst_rtp_mp4a_depay_finalize (GObject * object);
64
65 static gboolean gst_rtp_mp4a_depay_setcaps (GstRTPBaseDepayload * depayload,
66     GstCaps * caps);
67 static GstBuffer *gst_rtp_mp4a_depay_process (GstRTPBaseDepayload * 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   GstRTPBaseDepayloadClass *gstrtpbasedepayload_class;
80
81   gobject_class = (GObjectClass *) klass;
82   gstelement_class = (GstElementClass *) klass;
83   gstrtpbasedepayload_class = (GstRTPBaseDepayloadClass *) 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   gstrtpbasedepayload_class->process = gst_rtp_mp4a_depay_process;
90   gstrtpbasedepayload_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_static_metadata (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, 7350
128 };
129
130 static gboolean
131 gst_rtp_mp4a_depay_setcaps (GstRTPBaseDepayload * 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       GstMapInfo map;
165       guint8 *data;
166       gsize size;
167       gint i;
168       guint32 rate = 0;
169       guint8 obj_type = 0, sr_idx = 0, channels = 0;
170       GstBitReader br;
171
172       buffer = gst_value_get_buffer (&v);
173       gst_buffer_ref (buffer);
174       g_value_unset (&v);
175
176       gst_buffer_map (buffer, &map, GST_MAP_READ);
177       data = map.data;
178       size = map.size;
179
180       if (size < 2) {
181         GST_WARNING_OBJECT (depayload, "config too short (%d < 2)",
182             (gint) size);
183         goto bad_config;
184       }
185
186       /* Parse StreamMuxConfig according to ISO/IEC 14496-3:
187        *
188        * audioMuxVersion           == 0 (1 bit)
189        * allStreamsSameTimeFraming == 1 (1 bit)
190        * numSubFrames              == rtpmp4adepay->numSubFrames (6 bits)
191        * numProgram                == 0 (4 bits)
192        * numLayer                  == 0 (3 bits)
193        *
194        * We only require audioMuxVersion == 0;
195        *
196        * The remaining bit of the second byte and the rest of the bits are used
197        * for audioSpecificConfig which we need to set in codec_info.
198        */
199       if ((data[0] & 0x80) != 0x00) {
200         GST_WARNING_OBJECT (depayload, "unknown audioMuxVersion 1");
201         goto bad_config;
202       }
203
204       rtpmp4adepay->numSubFrames = (data[0] & 0x3F);
205
206       GST_LOG_OBJECT (rtpmp4adepay, "numSubFrames %d",
207           rtpmp4adepay->numSubFrames);
208
209       /* shift rest of string 15 bits down */
210       size -= 2;
211       for (i = 0; i < size; i++) {
212         data[i] = ((data[i + 1] & 1) << 7) | ((data[i + 2] & 0xfe) >> 1);
213       }
214
215       gst_bit_reader_init (&br, data, size);
216
217       /* any object type is fine, we need to copy it to the profile-level-id field. */
218       if (!gst_bit_reader_get_bits_uint8 (&br, &obj_type, 5))
219         goto bad_config;
220       if (obj_type == 0) {
221         GST_WARNING_OBJECT (depayload, "invalid object type 0");
222         goto bad_config;
223       }
224
225       if (!gst_bit_reader_get_bits_uint8 (&br, &sr_idx, 4))
226         goto bad_config;
227       if (sr_idx >= G_N_ELEMENTS (aac_sample_rates) && sr_idx != 15) {
228         GST_WARNING_OBJECT (depayload, "invalid sample rate index %d", sr_idx);
229         goto bad_config;
230       }
231       GST_LOG_OBJECT (rtpmp4adepay, "sample rate index %u", sr_idx);
232
233       if (!gst_bit_reader_get_bits_uint8 (&br, &channels, 4))
234         goto bad_config;
235       if (channels > 7) {
236         GST_WARNING_OBJECT (depayload, "invalid channels %u", (guint) channels);
237         goto bad_config;
238       }
239
240       /* rtp rate depends on sampling rate of the audio */
241       if (sr_idx == 15) {
242         /* index of 15 means we get the rate in the next 24 bits */
243         if (!gst_bit_reader_get_bits_uint32 (&br, &rate, 24))
244           goto bad_config;
245       } else if (sr_idx >= G_N_ELEMENTS (aac_sample_rates)) {
246         goto bad_config;
247       } else {
248         /* else use the rate from the table */
249         rate = aac_sample_rates[sr_idx];
250       }
251
252       rtpmp4adepay->frame_len = 1024;
253
254       switch (obj_type) {
255         case 1:
256         case 2:
257         case 3:
258         case 4:
259         case 6:
260         case 7:
261         {
262           guint8 frameLenFlag = 0;
263
264           if (gst_bit_reader_get_bits_uint8 (&br, &frameLenFlag, 1))
265             if (frameLenFlag)
266               rtpmp4adepay->frame_len = 960;
267           break;
268         }
269         default:
270           break;
271       }
272
273       /* ignore remaining bit, we're only interested in full bytes */
274       gst_buffer_resize (buffer, 0, size);
275       gst_buffer_unmap (buffer, &map);
276       data = NULL;
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     bad_config:
283       if (data)
284         gst_buffer_unmap (buffer, &map);
285       gst_buffer_unref (buffer);
286     } else {
287       g_warning ("cannot convert config to buffer");
288     }
289   }
290   res = gst_pad_set_caps (depayload->srcpad, srccaps);
291   gst_caps_unref (srccaps);
292
293   return res;
294 }
295
296 static GstBuffer *
297 gst_rtp_mp4a_depay_process (GstRTPBaseDepayload * depayload, GstBuffer * buf)
298 {
299   GstRtpMP4ADepay *rtpmp4adepay;
300   GstBuffer *outbuf;
301   GstRTPBuffer rtp = { NULL };
302   GstMapInfo map;
303
304   rtpmp4adepay = GST_RTP_MP4A_DEPAY (depayload);
305
306   /* flush remaining data on discont */
307   if (GST_BUFFER_IS_DISCONT (buf)) {
308     gst_adapter_clear (rtpmp4adepay->adapter);
309   }
310
311   gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp);
312   outbuf = gst_rtp_buffer_get_payload_buffer (&rtp);
313
314   outbuf = gst_buffer_make_writable (outbuf);
315   GST_BUFFER_TIMESTAMP (outbuf) = GST_BUFFER_TIMESTAMP (buf);
316   gst_adapter_push (rtpmp4adepay->adapter, outbuf);
317
318   /* RTP marker bit indicates the last packet of the AudioMuxElement => create
319    * and push a buffer */
320   if (gst_rtp_buffer_get_marker (&rtp)) {
321     guint avail;
322     guint i;
323     guint8 *data;
324     guint pos;
325     GstClockTime timestamp;
326
327     avail = gst_adapter_available (rtpmp4adepay->adapter);
328     timestamp = gst_adapter_prev_timestamp (rtpmp4adepay->adapter, NULL);
329
330     GST_LOG_OBJECT (rtpmp4adepay, "have marker and %u available", avail);
331
332     outbuf = gst_adapter_take_buffer (rtpmp4adepay->adapter, avail);
333     gst_buffer_map (outbuf, &map, GST_MAP_READ);
334     data = map.data;
335     /* position in data we are at */
336     pos = 0;
337
338     /* looping through the number of sub-frames in the audio payload */
339     for (i = 0; i <= rtpmp4adepay->numSubFrames; i++) {
340       /* determine payload length and set buffer data pointer accordingly */
341       guint skip;
342       guint data_len;
343       GstBuffer *tmp = NULL;
344
345       /* each subframe starts with a variable length encoding */
346       data_len = 0;
347       for (skip = 0; skip < avail; skip++) {
348         data_len += data[skip];
349         if (data[skip] != 0xff)
350           break;
351       }
352       skip++;
353
354       /* this can not be possible, we have not enough data or the length
355        * decoding failed because we ran out of data. */
356       if (skip + data_len > avail)
357         goto wrong_size;
358
359       GST_LOG_OBJECT (rtpmp4adepay,
360           "subframe %u, header len %u, data len %u, left %u", i, skip, data_len,
361           avail);
362
363       /* take data out, skip the header */
364       pos += skip;
365       tmp = gst_buffer_copy_region (outbuf, GST_BUFFER_COPY_MEMORY, pos,
366           data_len);
367
368       /* skip data too */
369       skip += data_len;
370       pos += data_len;
371
372       /* update our pointers whith what we consumed */
373       data += skip;
374       avail -= skip;
375
376       GST_BUFFER_TIMESTAMP (tmp) = timestamp;
377       gst_rtp_base_depayload_push (depayload, tmp);
378
379       /* shift ts for next buffers */
380       if (rtpmp4adepay->frame_len && timestamp != -1
381           && depayload->clock_rate != 0) {
382         timestamp +=
383             gst_util_uint64_scale_int (rtpmp4adepay->frame_len, GST_SECOND,
384             depayload->clock_rate);
385       }
386     }
387
388     /* just a check that lengths match */
389     if (avail) {
390       GST_ELEMENT_WARNING (depayload, STREAM, DECODE,
391           ("Packet invalid"), ("Not all payload consumed: "
392               "possible wrongly encoded packet."));
393     }
394
395     gst_buffer_unmap (outbuf, &map);
396     gst_buffer_unref (outbuf);
397   }
398   gst_rtp_buffer_unmap (&rtp);
399   return NULL;
400
401   /* ERRORS */
402 wrong_size:
403   {
404     GST_ELEMENT_WARNING (rtpmp4adepay, STREAM, DECODE,
405         ("Packet did not validate"), ("wrong packet size"));
406     gst_buffer_unmap (outbuf, &map);
407     gst_buffer_unref (outbuf);
408     gst_rtp_buffer_unmap (&rtp);
409     return NULL;
410   }
411 }
412
413 static GstStateChangeReturn
414 gst_rtp_mp4a_depay_change_state (GstElement * element,
415     GstStateChange transition)
416 {
417   GstRtpMP4ADepay *rtpmp4adepay;
418   GstStateChangeReturn ret;
419
420   rtpmp4adepay = GST_RTP_MP4A_DEPAY (element);
421
422   switch (transition) {
423     case GST_STATE_CHANGE_READY_TO_PAUSED:
424       gst_adapter_clear (rtpmp4adepay->adapter);
425       rtpmp4adepay->frame_len = 0;
426       rtpmp4adepay->numSubFrames = 0;
427       break;
428     default:
429       break;
430   }
431
432   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
433
434   switch (transition) {
435     default:
436       break;
437   }
438   return ret;
439 }
440
441 gboolean
442 gst_rtp_mp4a_depay_plugin_init (GstPlugin * plugin)
443 {
444   return gst_element_register (plugin, "rtpmp4adepay",
445       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4A_DEPAY);
446 }