Merge branch 'plugin-move-rtp-opus'
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtpmp4apay.c
1 /* GStreamer
2  * Copyright (C) <2008> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
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 <string.h>
25
26 #include <gst/rtp/gstrtpbuffer.h>
27 #include <gst/audio/audio.h>
28
29 #include "gstrtpmp4apay.h"
30 #include "gstrtputils.h"
31
32 GST_DEBUG_CATEGORY_STATIC (rtpmp4apay_debug);
33 #define GST_CAT_DEFAULT (rtpmp4apay_debug)
34
35 /* FIXME: add framed=(boolean)true once our encoders have this field set
36  * on their output caps */
37 static GstStaticPadTemplate gst_rtp_mp4a_pay_sink_template =
38 GST_STATIC_PAD_TEMPLATE ("sink",
39     GST_PAD_SINK,
40     GST_PAD_ALWAYS,
41     GST_STATIC_CAPS ("audio/mpeg, mpegversion=(int)4, "
42         "stream-format=(string)raw")
43     );
44
45 static GstStaticPadTemplate gst_rtp_mp4a_pay_src_template =
46 GST_STATIC_PAD_TEMPLATE ("src",
47     GST_PAD_SRC,
48     GST_PAD_ALWAYS,
49     GST_STATIC_CAPS ("application/x-rtp, "
50         "media = (string) \"audio\", "
51         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
52         "clock-rate = (int) [1, MAX ], "
53         "encoding-name = (string) \"MP4A-LATM\""
54         /* All optional parameters
55          *
56          * "cpresent = (string) \"0\""
57          * "config=" 
58          */
59     )
60     );
61
62 static void gst_rtp_mp4a_pay_finalize (GObject * object);
63
64 static gboolean gst_rtp_mp4a_pay_setcaps (GstRTPBasePayload * payload,
65     GstCaps * caps);
66 static GstFlowReturn gst_rtp_mp4a_pay_handle_buffer (GstRTPBasePayload *
67     payload, GstBuffer * buffer);
68
69 #define gst_rtp_mp4a_pay_parent_class parent_class
70 G_DEFINE_TYPE (GstRtpMP4APay, gst_rtp_mp4a_pay, GST_TYPE_RTP_BASE_PAYLOAD)
71
72      static void gst_rtp_mp4a_pay_class_init (GstRtpMP4APayClass * klass)
73 {
74   GObjectClass *gobject_class;
75   GstElementClass *gstelement_class;
76   GstRTPBasePayloadClass *gstrtpbasepayload_class;
77
78   gobject_class = (GObjectClass *) klass;
79   gstelement_class = (GstElementClass *) klass;
80   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
81
82   gobject_class->finalize = gst_rtp_mp4a_pay_finalize;
83
84   gstrtpbasepayload_class->set_caps = gst_rtp_mp4a_pay_setcaps;
85   gstrtpbasepayload_class->handle_buffer = gst_rtp_mp4a_pay_handle_buffer;
86
87   gst_element_class_add_pad_template (gstelement_class,
88       gst_static_pad_template_get (&gst_rtp_mp4a_pay_src_template));
89   gst_element_class_add_pad_template (gstelement_class,
90       gst_static_pad_template_get (&gst_rtp_mp4a_pay_sink_template));
91
92   gst_element_class_set_static_metadata (gstelement_class,
93       "RTP MPEG4 audio payloader", "Codec/Payloader/Network/RTP",
94       "Payload MPEG4 audio as RTP packets (RFC 3016)",
95       "Wim Taymans <wim.taymans@gmail.com>");
96
97   GST_DEBUG_CATEGORY_INIT (rtpmp4apay_debug, "rtpmp4apay", 0,
98       "MP4A-LATM RTP Payloader");
99 }
100
101 static void
102 gst_rtp_mp4a_pay_init (GstRtpMP4APay * rtpmp4apay)
103 {
104   rtpmp4apay->rate = 90000;
105   rtpmp4apay->profile = g_strdup ("1");
106 }
107
108 static void
109 gst_rtp_mp4a_pay_finalize (GObject * object)
110 {
111   GstRtpMP4APay *rtpmp4apay;
112
113   rtpmp4apay = GST_RTP_MP4A_PAY (object);
114
115   g_free (rtpmp4apay->params);
116   rtpmp4apay->params = NULL;
117
118   if (rtpmp4apay->config)
119     gst_buffer_unref (rtpmp4apay->config);
120   rtpmp4apay->config = NULL;
121
122   g_free (rtpmp4apay->profile);
123   rtpmp4apay->profile = NULL;
124
125   G_OBJECT_CLASS (parent_class)->finalize (object);
126 }
127
128 static const unsigned int sampling_table[16] = {
129   96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
130   16000, 12000, 11025, 8000, 7350, 0, 0, 0
131 };
132
133 static gboolean
134 gst_rtp_mp4a_pay_parse_audio_config (GstRtpMP4APay * rtpmp4apay,
135     GstBuffer * buffer)
136 {
137   GstMapInfo map;
138   guint8 *data;
139   gsize size;
140   guint8 objectType;
141   guint8 samplingIdx;
142   guint8 channelCfg;
143
144   gst_buffer_map (buffer, &map, GST_MAP_READ);
145   data = map.data;
146   size = map.size;
147
148   if (size < 2)
149     goto too_short;
150
151   /* any object type is fine, we need to copy it to the profile-level-id field. */
152   objectType = (data[0] & 0xf8) >> 3;
153   if (objectType == 0)
154     goto invalid_object;
155
156   samplingIdx = ((data[0] & 0x07) << 1) | ((data[1] & 0x80) >> 7);
157   /* only fixed values for now */
158   if (samplingIdx > 12 && samplingIdx != 15)
159     goto wrong_freq;
160
161   channelCfg = ((data[1] & 0x78) >> 3);
162   if (channelCfg > 7)
163     goto wrong_channels;
164
165   /* rtp rate depends on sampling rate of the audio */
166   if (samplingIdx == 15) {
167     if (size < 5)
168       goto too_short;
169
170     /* index of 15 means we get the rate in the next 24 bits */
171     rtpmp4apay->rate = ((data[1] & 0x7f) << 17) |
172         ((data[2]) << 9) | ((data[3]) << 1) | ((data[4] & 0x80) >> 7);
173   } else {
174     /* else use the rate from the table */
175     rtpmp4apay->rate = sampling_table[samplingIdx];
176   }
177   /* extra rtp params contain the number of channels */
178   g_free (rtpmp4apay->params);
179   rtpmp4apay->params = g_strdup_printf ("%d", channelCfg);
180   /* audio stream type */
181   rtpmp4apay->streamtype = "5";
182   /* profile */
183   g_free (rtpmp4apay->profile);
184   rtpmp4apay->profile = g_strdup_printf ("%d", objectType);
185
186   GST_DEBUG_OBJECT (rtpmp4apay,
187       "objectType: %d, samplingIdx: %d (%d), channelCfg: %d", objectType,
188       samplingIdx, rtpmp4apay->rate, channelCfg);
189
190   gst_buffer_unmap (buffer, &map);
191
192   return TRUE;
193
194   /* ERROR */
195 too_short:
196   {
197     GST_ELEMENT_ERROR (rtpmp4apay, STREAM, FORMAT,
198         (NULL),
199         ("config string too short, expected 2 bytes, got %" G_GSIZE_FORMAT,
200             size));
201     gst_buffer_unmap (buffer, &map);
202     return FALSE;
203   }
204 invalid_object:
205   {
206     GST_ELEMENT_ERROR (rtpmp4apay, STREAM, FORMAT,
207         (NULL), ("invalid object type 0"));
208     gst_buffer_unmap (buffer, &map);
209     return FALSE;
210   }
211 wrong_freq:
212   {
213     GST_ELEMENT_ERROR (rtpmp4apay, STREAM, NOT_IMPLEMENTED,
214         (NULL), ("unsupported frequency index %d", samplingIdx));
215     gst_buffer_unmap (buffer, &map);
216     return FALSE;
217   }
218 wrong_channels:
219   {
220     GST_ELEMENT_ERROR (rtpmp4apay, STREAM, NOT_IMPLEMENTED,
221         (NULL), ("unsupported number of channels %d, must < 8", channelCfg));
222     gst_buffer_unmap (buffer, &map);
223     return FALSE;
224   }
225 }
226
227 static gboolean
228 gst_rtp_mp4a_pay_new_caps (GstRtpMP4APay * rtpmp4apay)
229 {
230   gchar *config;
231   GValue v = { 0 };
232   gboolean res;
233
234   g_value_init (&v, GST_TYPE_BUFFER);
235   gst_value_set_buffer (&v, rtpmp4apay->config);
236   config = gst_value_serialize (&v);
237
238   res = gst_rtp_base_payload_set_outcaps (GST_RTP_BASE_PAYLOAD (rtpmp4apay),
239       "cpresent", G_TYPE_STRING, "0", "config", G_TYPE_STRING, config, NULL);
240
241   g_value_unset (&v);
242   g_free (config);
243
244   return res;
245 }
246
247 static gboolean
248 gst_rtp_mp4a_pay_setcaps (GstRTPBasePayload * payload, GstCaps * caps)
249 {
250   GstRtpMP4APay *rtpmp4apay;
251   GstStructure *structure;
252   const GValue *codec_data;
253   gboolean res, framed = TRUE;
254   const gchar *stream_format;
255
256   rtpmp4apay = GST_RTP_MP4A_PAY (payload);
257
258   structure = gst_caps_get_structure (caps, 0);
259
260   /* this is already handled by the template caps, but it is better
261    * to leave here to have meaningful warning messages when linking
262    * fails */
263   stream_format = gst_structure_get_string (structure, "stream-format");
264   if (stream_format) {
265     if (strcmp (stream_format, "raw") != 0) {
266       GST_WARNING_OBJECT (rtpmp4apay, "AAC's stream-format must be 'raw', "
267           "%s is not supported", stream_format);
268       return FALSE;
269     }
270   } else {
271     GST_WARNING_OBJECT (rtpmp4apay, "AAC's stream-format not specified, "
272         "assuming 'raw'");
273   }
274
275   codec_data = gst_structure_get_value (structure, "codec_data");
276   if (codec_data) {
277     GST_LOG_OBJECT (rtpmp4apay, "got codec_data");
278     if (G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER) {
279       GstBuffer *buffer, *cbuffer;
280       GstMapInfo map;
281       GstMapInfo cmap;
282       guint i;
283
284       buffer = gst_value_get_buffer (codec_data);
285       GST_LOG_OBJECT (rtpmp4apay, "configuring codec_data");
286
287       /* parse buffer */
288       res = gst_rtp_mp4a_pay_parse_audio_config (rtpmp4apay, buffer);
289
290       if (!res)
291         goto config_failed;
292
293       gst_buffer_map (buffer, &map, GST_MAP_READ);
294
295       /* make the StreamMuxConfig, we need 15 bits for the header */
296       cbuffer = gst_buffer_new_and_alloc (map.size + 2);
297       gst_buffer_map (cbuffer, &cmap, GST_MAP_WRITE);
298
299       memset (cmap.data, 0, map.size + 2);
300
301       /* Create StreamMuxConfig according to ISO/IEC 14496-3:
302        *
303        * audioMuxVersion           == 0 (1 bit)
304        * allStreamsSameTimeFraming == 1 (1 bit)
305        * numSubFrames              == numSubFrames (6 bits)
306        * numProgram                == 0 (4 bits)
307        * numLayer                  == 0 (3 bits)
308        */
309       cmap.data[0] = 0x40;
310       cmap.data[1] = 0x00;
311
312       /* append the config bits, shifting them 1 bit left */
313       for (i = 0; i < map.size; i++) {
314         cmap.data[i + 1] |= ((map.data[i] & 0x80) >> 7);
315         cmap.data[i + 2] |= ((map.data[i] & 0x7f) << 1);
316       }
317
318       gst_buffer_unmap (cbuffer, &cmap);
319       gst_buffer_unmap (buffer, &map);
320
321       /* now we can configure the buffer */
322       if (rtpmp4apay->config)
323         gst_buffer_unref (rtpmp4apay->config);
324       rtpmp4apay->config = cbuffer;
325     }
326   }
327
328   if (gst_structure_get_boolean (structure, "framed", &framed) && !framed) {
329     GST_WARNING_OBJECT (payload, "Need framed AAC data as input!");
330   }
331
332   gst_rtp_base_payload_set_options (payload, "audio", TRUE, "MP4A-LATM",
333       rtpmp4apay->rate);
334
335   res = gst_rtp_mp4a_pay_new_caps (rtpmp4apay);
336
337   return res;
338
339   /* ERRORS */
340 config_failed:
341   {
342     GST_DEBUG_OBJECT (rtpmp4apay, "failed to parse config");
343     return FALSE;
344   }
345 }
346
347 #define RTP_HEADER_LEN 12
348
349 /* we expect buffers as exactly one complete AU
350  */
351 static GstFlowReturn
352 gst_rtp_mp4a_pay_handle_buffer (GstRTPBasePayload * basepayload,
353     GstBuffer * buffer)
354 {
355   GstRtpMP4APay *rtpmp4apay;
356   GstFlowReturn ret;
357   GstBufferList *list;
358   guint mtu;
359   guint offset;
360   gsize size;
361   gboolean fragmented;
362   GstClockTime timestamp;
363
364   ret = GST_FLOW_OK;
365
366   rtpmp4apay = GST_RTP_MP4A_PAY (basepayload);
367
368   offset = 0;
369   size = gst_buffer_get_size (buffer);
370
371   timestamp = GST_BUFFER_PTS (buffer);
372
373   fragmented = FALSE;
374   mtu = GST_RTP_BASE_PAYLOAD_MTU (rtpmp4apay);
375
376   list = gst_buffer_list_new_sized (size / (mtu - RTP_HEADER_LEN) + 1);
377
378   while (size > 0) {
379     guint towrite;
380     GstBuffer *outbuf;
381     guint payload_len;
382     guint packet_len;
383     guint header_len;
384     GstBuffer *paybuf;
385     GstRTPBuffer rtp = { NULL };
386
387     header_len = 0;
388     if (!fragmented) {
389       guint count;
390       /* first packet calculate space for the packet including the header */
391       count = size;
392       while (count >= 0xff) {
393         header_len++;
394         count -= 0xff;
395       }
396       header_len++;
397     }
398
399     packet_len = gst_rtp_buffer_calc_packet_len (header_len + size, 0, 0);
400     towrite = MIN (packet_len, mtu);
401     payload_len = gst_rtp_buffer_calc_payload_len (towrite, 0, 0);
402     payload_len -= header_len;
403
404     GST_DEBUG_OBJECT (rtpmp4apay,
405         "avail %" G_GSIZE_FORMAT
406         ", header_len %d, packet_len %d, payload_len %d", size, header_len,
407         packet_len, payload_len);
408
409     /* create buffer to hold the payload. */
410     outbuf = gst_rtp_buffer_new_allocate (header_len, 0, 0);
411
412     /* copy payload */
413     gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
414
415     if (!fragmented) {
416       guint8 *payload = gst_rtp_buffer_get_payload (&rtp);
417       guint count;
418
419       /* first packet write the header */
420       count = size;
421       while (count >= 0xff) {
422         *payload++ = 0xff;
423         count -= 0xff;
424       }
425       *payload++ = count;
426     }
427
428     /* marker only if the packet is complete */
429     gst_rtp_buffer_set_marker (&rtp, size == payload_len);
430
431     gst_rtp_buffer_unmap (&rtp);
432
433     /* create a new buf to hold the payload */
434     paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL,
435         offset, payload_len);
436
437     /* join memory parts */
438     gst_rtp_copy_meta (GST_ELEMENT_CAST (rtpmp4apay), outbuf, paybuf,
439         g_quark_from_static_string (GST_META_TAG_AUDIO_STR));
440     outbuf = gst_buffer_append (outbuf, paybuf);
441     gst_buffer_list_add (list, outbuf);
442     offset += payload_len;
443     size -= payload_len;
444
445     /* copy incomming timestamp (if any) to outgoing buffers */
446     GST_BUFFER_PTS (outbuf) = timestamp;
447
448     fragmented = TRUE;
449   }
450
451   ret =
452       gst_rtp_base_payload_push_list (GST_RTP_BASE_PAYLOAD (rtpmp4apay), list);
453
454   gst_buffer_unref (buffer);
455
456   return ret;
457 }
458
459 gboolean
460 gst_rtp_mp4a_pay_plugin_init (GstPlugin * plugin)
461 {
462   return gst_element_register (plugin, "rtpmp4apay",
463       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4A_PAY);
464 }