gstdepay: check for correct fragment offset
[platform/upstream/gstreamer.git] / gst / rtp / gstrtpamrpay.c
1 /* GStreamer
2  * Copyright (C) <2005> 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 "gstrtpamrpay.h"
29
30 GST_DEBUG_CATEGORY_STATIC (rtpamrpay_debug);
31 #define GST_CAT_DEFAULT (rtpamrpay_debug)
32
33 /* references:
34  *
35  * RFC 3267 - Real-Time Transport Protocol (RTP) Payload Format and File
36  *    Storage Format for the Adaptive Multi-Rate (AMR) and Adaptive
37  *    Multi-Rate Wideband (AMR-WB) Audio Codecs.
38  *
39  * ETSI TS 126 201 V6.0.0 (2004-12) - Digital cellular telecommunications system (Phase 2+);
40  *                 Universal Mobile Telecommunications System (UMTS);
41  *                          AMR speech codec, wideband;
42  *                                 Frame structure
43  *                    (3GPP TS 26.201 version 6.0.0 Release 6)
44  */
45
46 static GstStaticPadTemplate gst_rtp_amr_pay_sink_template =
47     GST_STATIC_PAD_TEMPLATE ("sink",
48     GST_PAD_SINK,
49     GST_PAD_ALWAYS,
50     GST_STATIC_CAPS ("audio/AMR, channels=(int)1, rate=(int)8000; "
51         "audio/AMR-WB, channels=(int)1, rate=(int)16000")
52     );
53
54 static GstStaticPadTemplate gst_rtp_amr_pay_src_template =
55     GST_STATIC_PAD_TEMPLATE ("src",
56     GST_PAD_SRC,
57     GST_PAD_ALWAYS,
58     GST_STATIC_CAPS ("application/x-rtp, "
59         "media = (string) \"audio\", "
60         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
61         "clock-rate = (int) 8000, "
62         "encoding-name = (string) \"AMR\", "
63         "encoding-params = (string) \"1\", "
64         "octet-align = (string) \"1\", "
65         "crc = (string) \"0\", "
66         "robust-sorting = (string) \"0\", "
67         "interleaving = (string) \"0\", "
68         "mode-set = (int) [ 0, 7 ], "
69         "mode-change-period = (int) [ 1, MAX ], "
70         "mode-change-neighbor = (string) { \"0\", \"1\" }, "
71         "maxptime = (int) [ 20, MAX ], " "ptime = (int) [ 20, MAX ];"
72         "application/x-rtp, "
73         "media = (string) \"audio\", "
74         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
75         "clock-rate = (int) 16000, "
76         "encoding-name = (string) \"AMR-WB\", "
77         "encoding-params = (string) \"1\", "
78         "octet-align = (string) \"1\", "
79         "crc = (string) \"0\", "
80         "robust-sorting = (string) \"0\", "
81         "interleaving = (string) \"0\", "
82         "mode-set = (int) [ 0, 7 ], "
83         "mode-change-period = (int) [ 1, MAX ], "
84         "mode-change-neighbor = (string) { \"0\", \"1\" }, "
85         "maxptime = (int) [ 20, MAX ], " "ptime = (int) [ 20, MAX ]")
86     );
87
88 static gboolean gst_rtp_amr_pay_setcaps (GstRTPBasePayload * basepayload,
89     GstCaps * caps);
90 static GstFlowReturn gst_rtp_amr_pay_handle_buffer (GstRTPBasePayload * pad,
91     GstBuffer * buffer);
92
93 static GstStateChangeReturn
94 gst_rtp_amr_pay_change_state (GstElement * element, GstStateChange transition);
95
96 #define gst_rtp_amr_pay_parent_class parent_class
97 G_DEFINE_TYPE (GstRtpAMRPay, gst_rtp_amr_pay, GST_TYPE_RTP_BASE_PAYLOAD);
98
99 static void
100 gst_rtp_amr_pay_class_init (GstRtpAMRPayClass * klass)
101 {
102   GstElementClass *gstelement_class;
103   GstRTPBasePayloadClass *gstrtpbasepayload_class;
104
105   gstelement_class = (GstElementClass *) klass;
106   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
107
108   gstelement_class->change_state = gst_rtp_amr_pay_change_state;
109
110   gst_element_class_add_pad_template (gstelement_class,
111       gst_static_pad_template_get (&gst_rtp_amr_pay_src_template));
112   gst_element_class_add_pad_template (gstelement_class,
113       gst_static_pad_template_get (&gst_rtp_amr_pay_sink_template));
114
115   gst_element_class_set_static_metadata (gstelement_class, "RTP AMR payloader",
116       "Codec/Payloader/Network/RTP",
117       "Payload-encode AMR or AMR-WB audio into RTP packets (RFC 3267)",
118       "Wim Taymans <wim.taymans@gmail.com>");
119
120   gstrtpbasepayload_class->set_caps = gst_rtp_amr_pay_setcaps;
121   gstrtpbasepayload_class->handle_buffer = gst_rtp_amr_pay_handle_buffer;
122
123   GST_DEBUG_CATEGORY_INIT (rtpamrpay_debug, "rtpamrpay", 0,
124       "AMR/AMR-WB RTP Payloader");
125 }
126
127 static void
128 gst_rtp_amr_pay_init (GstRtpAMRPay * rtpamrpay)
129 {
130 }
131
132 static void
133 gst_rtp_amr_pay_reset (GstRtpAMRPay * pay)
134 {
135   pay->next_rtp_time = 0;
136   pay->first_ts = GST_CLOCK_TIME_NONE;
137   pay->first_rtp_time = 0;
138 }
139
140 static gboolean
141 gst_rtp_amr_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
142 {
143   GstRtpAMRPay *rtpamrpay;
144   gboolean res;
145   const GstStructure *s;
146   const gchar *str;
147
148   rtpamrpay = GST_RTP_AMR_PAY (basepayload);
149
150   /* figure out the mode Narrow or Wideband */
151   s = gst_caps_get_structure (caps, 0);
152   if ((str = gst_structure_get_name (s))) {
153     if (strcmp (str, "audio/AMR") == 0)
154       rtpamrpay->mode = GST_RTP_AMR_P_MODE_NB;
155     else if (strcmp (str, "audio/AMR-WB") == 0)
156       rtpamrpay->mode = GST_RTP_AMR_P_MODE_WB;
157     else
158       goto wrong_type;
159   } else
160     goto wrong_type;
161
162   if (rtpamrpay->mode == GST_RTP_AMR_P_MODE_NB)
163     gst_rtp_base_payload_set_options (basepayload, "audio", TRUE, "AMR", 8000);
164   else
165     gst_rtp_base_payload_set_options (basepayload, "audio", TRUE, "AMR-WB",
166         16000);
167
168   res = gst_rtp_base_payload_set_outcaps (basepayload,
169       "encoding-params", G_TYPE_STRING, "1", "octet-align", G_TYPE_STRING, "1",
170       /* don't set the defaults
171        *
172        * "crc", G_TYPE_STRING, "0",
173        * "robust-sorting", G_TYPE_STRING, "0",
174        * "interleaving", G_TYPE_STRING, "0",
175        */
176       NULL);
177
178   return res;
179
180   /* ERRORS */
181 wrong_type:
182   {
183     GST_ERROR_OBJECT (rtpamrpay, "unsupported media type '%s'",
184         GST_STR_NULL (str));
185     return FALSE;
186   }
187 }
188
189 static void
190 gst_rtp_amr_pay_recalc_rtp_time (GstRtpAMRPay * rtpamrpay,
191     GstClockTime timestamp)
192 {
193   /* re-sync rtp time */
194   if (GST_CLOCK_TIME_IS_VALID (rtpamrpay->first_ts) &&
195       GST_CLOCK_TIME_IS_VALID (timestamp) && timestamp >= rtpamrpay->first_ts) {
196     GstClockTime diff;
197     guint32 rtpdiff;
198
199     /* interpolate to reproduce gap from start, rather than intermediate
200      * intervals to avoid roundup accumulation errors */
201     diff = timestamp - rtpamrpay->first_ts;
202     rtpdiff = ((diff / GST_MSECOND) * 8) <<
203         (rtpamrpay->mode == GST_RTP_AMR_P_MODE_WB);
204     rtpamrpay->next_rtp_time = rtpamrpay->first_rtp_time + rtpdiff;
205     GST_DEBUG_OBJECT (rtpamrpay,
206         "elapsed time %" GST_TIME_FORMAT ", rtp %" G_GUINT32_FORMAT ", "
207         "new offset %" G_GUINT32_FORMAT, GST_TIME_ARGS (diff), rtpdiff,
208         rtpamrpay->next_rtp_time);
209   }
210 }
211
212 /* -1 is invalid */
213 static const gint nb_frame_size[16] = {
214   12, 13, 15, 17, 19, 20, 26, 31,
215   5, -1, -1, -1, -1, -1, -1, 0
216 };
217
218 static const gint wb_frame_size[16] = {
219   17, 23, 32, 36, 40, 46, 50, 58,
220   60, 5, -1, -1, -1, -1, -1, 0
221 };
222
223 static GstFlowReturn
224 gst_rtp_amr_pay_handle_buffer (GstRTPBasePayload * basepayload,
225     GstBuffer * buffer)
226 {
227   GstRtpAMRPay *rtpamrpay;
228   const gint *frame_size;
229   GstFlowReturn ret;
230   guint payload_len;
231   GstMapInfo map;
232   GstBuffer *outbuf;
233   guint8 *payload, *ptr, *payload_amr;
234   GstClockTime timestamp, duration;
235   guint packet_len, mtu;
236   gint i, num_packets, num_nonempty_packets;
237   gint amr_len;
238   gboolean sid = FALSE;
239   GstRTPBuffer rtp = { NULL };
240
241   rtpamrpay = GST_RTP_AMR_PAY (basepayload);
242   mtu = GST_RTP_BASE_PAYLOAD_MTU (rtpamrpay);
243
244   gst_buffer_map (buffer, &map, GST_MAP_READ);
245
246   timestamp = GST_BUFFER_TIMESTAMP (buffer);
247   duration = GST_BUFFER_DURATION (buffer);
248
249   /* setup frame size pointer */
250   if (rtpamrpay->mode == GST_RTP_AMR_P_MODE_NB)
251     frame_size = nb_frame_size;
252   else
253     frame_size = wb_frame_size;
254
255   GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", map.size);
256
257   /* FIXME, only
258    * octet aligned, no interleaving, single channel, no CRC,
259    * no robust-sorting. To fix this you need to implement the downstream
260    * negotiation function. */
261
262   /* first count number of packets and total amr frame size */
263   amr_len = num_packets = num_nonempty_packets = 0;
264   for (i = 0; i < map.size; i++) {
265     guint8 FT;
266     gint fr_size;
267
268     FT = (map.data[i] & 0x78) >> 3;
269
270     fr_size = frame_size[FT];
271     GST_DEBUG_OBJECT (basepayload, "frame type %d, frame size %d", FT, fr_size);
272     /* FIXME, we don't handle this yet.. */
273     if (fr_size <= 0)
274       goto wrong_size;
275
276     if (fr_size == 5)
277       sid = TRUE;
278
279     amr_len += fr_size;
280     num_nonempty_packets++;
281     num_packets++;
282     i += fr_size;
283   }
284   if (amr_len > map.size)
285     goto incomplete_frame;
286
287   /* we need one extra byte for the CMR, the ToC is in the input
288    * data */
289   payload_len = map.size + 1;
290
291   /* get packet len to check against MTU */
292   packet_len = gst_rtp_buffer_calc_packet_len (payload_len, 0, 0);
293   if (packet_len > mtu)
294     goto too_big;
295
296   /* now alloc output buffer */
297   outbuf = gst_rtp_buffer_new_allocate (payload_len, 0, 0);
298
299   gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
300
301   /* copy timestamp */
302   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
303
304   if (duration != GST_CLOCK_TIME_NONE)
305     GST_BUFFER_DURATION (outbuf) = duration;
306   else {
307     GST_BUFFER_DURATION (outbuf) = num_packets * 20 * GST_MSECOND;
308   }
309
310   if (GST_BUFFER_IS_DISCONT (buffer)) {
311     GST_DEBUG_OBJECT (basepayload, "discont, setting marker bit");
312     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
313     gst_rtp_buffer_set_marker (&rtp, TRUE);
314     gst_rtp_amr_pay_recalc_rtp_time (rtpamrpay, timestamp);
315   }
316
317   if (G_UNLIKELY (sid)) {
318     gst_rtp_amr_pay_recalc_rtp_time (rtpamrpay, timestamp);
319   }
320
321   /* perfect rtptime */
322   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (rtpamrpay->first_ts))) {
323     rtpamrpay->first_ts = timestamp;
324     rtpamrpay->first_rtp_time = rtpamrpay->next_rtp_time;
325   }
326   GST_BUFFER_OFFSET (outbuf) = rtpamrpay->next_rtp_time;
327   rtpamrpay->next_rtp_time +=
328       (num_packets * 160) << (rtpamrpay->mode == GST_RTP_AMR_P_MODE_WB);
329
330   /* get payload, this is now writable */
331   payload = gst_rtp_buffer_get_payload (&rtp);
332
333   /*   0 1 2 3 4 5 6 7
334    *  +-+-+-+-+-+-+-+-+
335    *  |  CMR  |R|R|R|R|
336    *  +-+-+-+-+-+-+-+-+
337    */
338   payload[0] = 0xF0;            /* CMR, no specific mode requested */
339
340   /* this is where we copy the AMR data, after num_packets FTs and the
341    * CMR. */
342   payload_amr = payload + num_packets + 1;
343
344   /* copy data in payload, first we copy all the FTs then all
345    * the AMR data. The last FT has to have the F flag cleared. */
346   ptr = map.data;
347   for (i = 1; i <= num_packets; i++) {
348     guint8 FT;
349     gint fr_size;
350
351     /*   0 1 2 3 4 5 6 7
352      *  +-+-+-+-+-+-+-+-+
353      *  |F|  FT   |Q|P|P| more FT...
354      *  +-+-+-+-+-+-+-+-+
355      */
356     FT = (*ptr & 0x78) >> 3;
357
358     fr_size = frame_size[FT];
359
360     if (i == num_packets)
361       /* last packet, clear F flag */
362       payload[i] = *ptr & 0x7f;
363     else
364       /* set F flag */
365       payload[i] = *ptr | 0x80;
366
367     memcpy (payload_amr, &ptr[1], fr_size);
368
369     /* all sizes are > 0 since we checked for that above */
370     ptr += fr_size + 1;
371     payload_amr += fr_size;
372   }
373
374   gst_buffer_unmap (buffer, &map);
375   gst_buffer_unref (buffer);
376
377   gst_rtp_buffer_unmap (&rtp);
378
379   ret = gst_rtp_base_payload_push (basepayload, outbuf);
380
381   return ret;
382
383   /* ERRORS */
384 wrong_size:
385   {
386     GST_ELEMENT_ERROR (basepayload, STREAM, FORMAT,
387         (NULL), ("received AMR frame with size <= 0"));
388     gst_buffer_unmap (buffer, &map);
389     gst_buffer_unref (buffer);
390
391     return GST_FLOW_ERROR;
392   }
393 incomplete_frame:
394   {
395     GST_ELEMENT_ERROR (basepayload, STREAM, FORMAT,
396         (NULL), ("received incomplete AMR frames"));
397     gst_buffer_unmap (buffer, &map);
398     gst_buffer_unref (buffer);
399
400     return GST_FLOW_ERROR;
401   }
402 too_big:
403   {
404     GST_ELEMENT_ERROR (basepayload, STREAM, FORMAT,
405         (NULL), ("received too many AMR frames for MTU"));
406     gst_buffer_unmap (buffer, &map);
407     gst_buffer_unref (buffer);
408
409     return GST_FLOW_ERROR;
410   }
411 }
412
413 static GstStateChangeReturn
414 gst_rtp_amr_pay_change_state (GstElement * element, GstStateChange transition)
415 {
416   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
417
418   /* handle upwards state changes here */
419   switch (transition) {
420     default:
421       break;
422   }
423
424   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
425
426   /* handle downwards state changes */
427   switch (transition) {
428     case GST_STATE_CHANGE_PAUSED_TO_READY:
429       gst_rtp_amr_pay_reset (GST_RTP_AMR_PAY (element));
430       break;
431     default:
432       break;
433   }
434
435   return ret;
436 }
437
438 gboolean
439 gst_rtp_amr_pay_plugin_init (GstPlugin * plugin)
440 {
441   return gst_element_register (plugin, "rtpamrpay",
442       GST_RANK_SECONDARY, GST_TYPE_RTP_AMR_PAY);
443 }