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