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