rtpvp8: port some more to new memory API
[platform/upstream/gstreamer.git] / gst / rtp / gstrtpmp4vpay.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 "gstrtpmp4vpay.h"
29
30 GST_DEBUG_CATEGORY_STATIC (rtpmp4vpay_debug);
31 #define GST_CAT_DEFAULT (rtpmp4vpay_debug)
32
33 static GstStaticPadTemplate gst_rtp_mp4v_pay_sink_template =
34     GST_STATIC_PAD_TEMPLATE ("sink",
35     GST_PAD_SINK,
36     GST_PAD_ALWAYS,
37     GST_STATIC_CAPS ("video/mpeg,"
38         "mpegversion=(int) 4, systemstream=(boolean)false;" "video/x-divx")
39     );
40
41 static GstStaticPadTemplate gst_rtp_mp4v_pay_src_template =
42 GST_STATIC_PAD_TEMPLATE ("src",
43     GST_PAD_SRC,
44     GST_PAD_ALWAYS,
45     GST_STATIC_CAPS ("application/x-rtp, "
46         "media = (string) \"video\", "
47         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
48         "clock-rate = (int) [1, MAX ], " "encoding-name = (string) \"MP4V-ES\""
49         /* two string params
50          *
51          "profile-level-id = (string) [1,MAX]"
52          "config = (string) [1,MAX]"
53          */
54     )
55     );
56
57 #define DEFAULT_CONFIG_INTERVAL 0
58
59 enum
60 {
61   ARG_0,
62   ARG_CONFIG_INTERVAL
63 };
64
65
66 static void gst_rtp_mp4v_pay_finalize (GObject * object);
67
68 static void gst_rtp_mp4v_pay_set_property (GObject * object, guint prop_id,
69     const GValue * value, GParamSpec * pspec);
70 static void gst_rtp_mp4v_pay_get_property (GObject * object, guint prop_id,
71     GValue * value, GParamSpec * pspec);
72
73 static gboolean gst_rtp_mp4v_pay_setcaps (GstRTPBasePayload * payload,
74     GstCaps * caps);
75 static GstFlowReturn gst_rtp_mp4v_pay_handle_buffer (GstRTPBasePayload *
76     payload, GstBuffer * buffer);
77 static gboolean gst_rtp_mp4v_pay_sink_event (GstRTPBasePayload * pay,
78     GstEvent * event);
79
80 #define gst_rtp_mp4v_pay_parent_class parent_class
81 G_DEFINE_TYPE (GstRtpMP4VPay, gst_rtp_mp4v_pay, GST_TYPE_RTP_BASE_PAYLOAD)
82
83      static void gst_rtp_mp4v_pay_class_init (GstRtpMP4VPayClass * klass)
84 {
85   GObjectClass *gobject_class;
86   GstElementClass *gstelement_class;
87   GstRTPBasePayloadClass *gstrtpbasepayload_class;
88
89   gobject_class = (GObjectClass *) klass;
90   gstelement_class = (GstElementClass *) klass;
91   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
92
93   gobject_class->set_property = gst_rtp_mp4v_pay_set_property;
94   gobject_class->get_property = gst_rtp_mp4v_pay_get_property;
95
96   gst_element_class_add_pad_template (gstelement_class,
97       gst_static_pad_template_get (&gst_rtp_mp4v_pay_src_template));
98   gst_element_class_add_pad_template (gstelement_class,
99       gst_static_pad_template_get (&gst_rtp_mp4v_pay_sink_template));
100
101   gst_element_class_set_static_metadata (gstelement_class,
102       "RTP MPEG4 Video payloader", "Codec/Payloader/Network/RTP",
103       "Payload MPEG-4 video as RTP packets (RFC 3016)",
104       "Wim Taymans <wim.taymans@gmail.com>");
105
106   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CONFIG_INTERVAL,
107       g_param_spec_uint ("config-interval", "Config Send Interval",
108           "Send Config Insertion Interval in seconds (configuration headers "
109           "will be multiplexed in the data stream when detected.) (0 = disabled)",
110           0, 3600, DEFAULT_CONFIG_INTERVAL,
111           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
112       );
113
114   gobject_class->finalize = gst_rtp_mp4v_pay_finalize;
115
116   gstrtpbasepayload_class->set_caps = gst_rtp_mp4v_pay_setcaps;
117   gstrtpbasepayload_class->handle_buffer = gst_rtp_mp4v_pay_handle_buffer;
118   gstrtpbasepayload_class->sink_event = gst_rtp_mp4v_pay_sink_event;
119
120   GST_DEBUG_CATEGORY_INIT (rtpmp4vpay_debug, "rtpmp4vpay", 0,
121       "MP4 video RTP Payloader");
122 }
123
124 static void
125 gst_rtp_mp4v_pay_init (GstRtpMP4VPay * rtpmp4vpay)
126 {
127   rtpmp4vpay->adapter = gst_adapter_new ();
128   rtpmp4vpay->rate = 90000;
129   rtpmp4vpay->profile = 1;
130   rtpmp4vpay->need_config = TRUE;
131   rtpmp4vpay->config_interval = DEFAULT_CONFIG_INTERVAL;
132   rtpmp4vpay->last_config = -1;
133
134   rtpmp4vpay->config = NULL;
135 }
136
137 static void
138 gst_rtp_mp4v_pay_finalize (GObject * object)
139 {
140   GstRtpMP4VPay *rtpmp4vpay;
141
142   rtpmp4vpay = GST_RTP_MP4V_PAY (object);
143
144   if (rtpmp4vpay->config) {
145     gst_buffer_unref (rtpmp4vpay->config);
146     rtpmp4vpay->config = NULL;
147   }
148   g_object_unref (rtpmp4vpay->adapter);
149   rtpmp4vpay->adapter = NULL;
150
151   G_OBJECT_CLASS (parent_class)->finalize (object);
152 }
153
154 static gboolean
155 gst_rtp_mp4v_pay_new_caps (GstRtpMP4VPay * rtpmp4vpay)
156 {
157   gchar *profile, *config;
158   GValue v = { 0 };
159   gboolean res;
160
161   profile = g_strdup_printf ("%d", rtpmp4vpay->profile);
162   g_value_init (&v, GST_TYPE_BUFFER);
163   gst_value_set_buffer (&v, rtpmp4vpay->config);
164   config = gst_value_serialize (&v);
165
166   res = gst_rtp_base_payload_set_outcaps (GST_RTP_BASE_PAYLOAD (rtpmp4vpay),
167       "profile-level-id", G_TYPE_STRING, profile,
168       "config", G_TYPE_STRING, config, NULL);
169
170   g_value_unset (&v);
171
172   g_free (profile);
173   g_free (config);
174
175   return res;
176 }
177
178 static gboolean
179 gst_rtp_mp4v_pay_setcaps (GstRTPBasePayload * payload, GstCaps * caps)
180 {
181   GstRtpMP4VPay *rtpmp4vpay;
182   GstStructure *structure;
183   const GValue *codec_data;
184   gboolean res;
185
186   rtpmp4vpay = GST_RTP_MP4V_PAY (payload);
187
188   gst_rtp_base_payload_set_options (payload, "video", TRUE, "MP4V-ES",
189       rtpmp4vpay->rate);
190
191   res = TRUE;
192
193   structure = gst_caps_get_structure (caps, 0);
194   codec_data = gst_structure_get_value (structure, "codec_data");
195   if (codec_data) {
196     GST_LOG_OBJECT (rtpmp4vpay, "got codec_data");
197     if (G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER) {
198       GstBuffer *buffer;
199
200       buffer = gst_value_get_buffer (codec_data);
201
202       if (gst_buffer_get_size (buffer) < 5)
203         goto done;
204
205       gst_buffer_extract (buffer, 4, &rtpmp4vpay->profile, 1);
206       GST_LOG_OBJECT (rtpmp4vpay, "configuring codec_data, profile %d",
207           rtpmp4vpay->profile);
208
209       if (rtpmp4vpay->config)
210         gst_buffer_unref (rtpmp4vpay->config);
211       rtpmp4vpay->config = gst_buffer_copy (buffer);
212       res = gst_rtp_mp4v_pay_new_caps (rtpmp4vpay);
213     }
214   }
215
216 done:
217   return res;
218 }
219
220 static void
221 gst_rtp_mp4v_pay_empty (GstRtpMP4VPay * rtpmp4vpay)
222 {
223   gst_adapter_clear (rtpmp4vpay->adapter);
224 }
225
226 static GstFlowReturn
227 gst_rtp_mp4v_pay_flush (GstRtpMP4VPay * rtpmp4vpay)
228 {
229   guint avail;
230   GstBuffer *outbuf;
231   GstBuffer *outbuf_data = NULL;
232   GstFlowReturn ret;
233   GstBufferList *list = NULL;
234
235   /* the data available in the adapter is either smaller
236    * than the MTU or bigger. In the case it is smaller, the complete
237    * adapter contents can be put in one packet. In the case the
238    * adapter has more than one MTU, we need to split the MP4V data
239    * over multiple packets. */
240   avail = gst_adapter_available (rtpmp4vpay->adapter);
241
242   if (rtpmp4vpay->config == NULL && rtpmp4vpay->need_config) {
243     /* when we don't have a config yet, flush things out */
244     gst_adapter_flush (rtpmp4vpay->adapter, avail);
245     avail = 0;
246   }
247
248   if (!avail)
249     return GST_FLOW_OK;
250
251   ret = GST_FLOW_OK;
252
253   /* Use buffer lists. Each frame will be put into a list
254    * of buffers and the whole list will be pushed downstream
255    * at once */
256   list = gst_buffer_list_new ();
257
258   while (avail > 0) {
259     guint towrite;
260     guint payload_len;
261     guint packet_len;
262     GstRTPBuffer rtp = { NULL };
263
264     /* this will be the total lenght of the packet */
265     packet_len = gst_rtp_buffer_calc_packet_len (avail, 0, 0);
266
267     /* fill one MTU or all available bytes */
268     towrite = MIN (packet_len, GST_RTP_BASE_PAYLOAD_MTU (rtpmp4vpay));
269
270     /* this is the payload length */
271     payload_len = gst_rtp_buffer_calc_payload_len (towrite, 0, 0);
272
273     /* create buffer without payload. The payload will be put
274      * in next buffer instead. Both buffers will be merged */
275     outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
276
277     /* Take buffer with the payload from the adapter */
278     outbuf_data = gst_adapter_take_buffer (rtpmp4vpay->adapter, payload_len);
279
280     avail -= payload_len;
281
282     gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
283     gst_rtp_buffer_set_marker (&rtp, avail == 0);
284     gst_rtp_buffer_unmap (&rtp);
285
286     outbuf = gst_buffer_append (outbuf, outbuf_data);
287
288     GST_BUFFER_TIMESTAMP (outbuf) = rtpmp4vpay->first_timestamp;
289
290     /* add to list */
291     gst_buffer_list_insert (list, -1, outbuf);
292   }
293
294   /* push the whole buffer list at once */
295   ret =
296       gst_rtp_base_payload_push_list (GST_RTP_BASE_PAYLOAD (rtpmp4vpay), list);
297
298   return ret;
299 }
300
301 #define VOS_STARTCODE                   0x000001B0
302 #define VOS_ENDCODE                     0x000001B1
303 #define USER_DATA_STARTCODE             0x000001B2
304 #define GOP_STARTCODE                   0x000001B3
305 #define VISUAL_OBJECT_STARTCODE         0x000001B5
306 #define VOP_STARTCODE                   0x000001B6
307
308 static gboolean
309 gst_rtp_mp4v_pay_depay_data (GstRtpMP4VPay * enc, guint8 * data, guint size,
310     gint * strip, gboolean * vopi)
311 {
312   guint32 code;
313   gboolean result;
314   *vopi = FALSE;
315
316   *strip = 0;
317
318   if (size < 5)
319     return FALSE;
320
321   code = GST_READ_UINT32_BE (data);
322   GST_DEBUG_OBJECT (enc, "start code 0x%08x", code);
323
324   switch (code) {
325     case VOS_STARTCODE:
326     case 0x00000101:
327     {
328       gint i;
329       guint8 profile;
330       gboolean newprofile = FALSE;
331       gboolean equal;
332
333       if (code == VOS_STARTCODE) {
334         /* profile_and_level_indication */
335         profile = data[4];
336
337         GST_DEBUG_OBJECT (enc, "VOS profile 0x%08x", profile);
338
339         if (profile != enc->profile) {
340           newprofile = TRUE;
341           enc->profile = profile;
342         }
343       }
344
345       /* up to the next GOP_STARTCODE or VOP_STARTCODE is
346        * the config information */
347       code = 0xffffffff;
348       for (i = 5; i < size - 4; i++) {
349         code = (code << 8) | data[i];
350         if (code == GOP_STARTCODE || code == VOP_STARTCODE)
351           break;
352       }
353       i -= 3;
354       /* see if config changed */
355       equal = FALSE;
356       if (enc->config) {
357         if (gst_buffer_get_size (enc->config) == i) {
358           equal = gst_buffer_memcmp (enc->config, 0, data, i) == 0;
359         }
360       }
361       /* if config string changed or new profile, make new caps */
362       if (!equal || newprofile) {
363         if (enc->config)
364           gst_buffer_unref (enc->config);
365         enc->config = gst_buffer_new_and_alloc (i);
366
367         gst_buffer_fill (enc->config, 0, data, i);
368
369         gst_rtp_mp4v_pay_new_caps (enc);
370       }
371       *strip = i;
372       /* we need to flush out the current packet. */
373       result = TRUE;
374       break;
375     }
376     case VOP_STARTCODE:
377       GST_DEBUG_OBJECT (enc, "VOP");
378       /* VOP startcode, we don't have to flush the packet */
379       result = FALSE;
380       /* vop-coding-type == I-frame */
381       if (size > 4 && (data[4] >> 6 == 0)) {
382         GST_DEBUG_OBJECT (enc, "VOP-I");
383         *vopi = TRUE;
384       }
385       break;
386     case GOP_STARTCODE:
387       GST_DEBUG_OBJECT (enc, "GOP");
388       *vopi = TRUE;
389       result = TRUE;
390       break;
391     case 0x00000100:
392       enc->need_config = FALSE;
393       result = TRUE;
394       break;
395     default:
396       if (code >= 0x20 && code <= 0x2f) {
397         GST_DEBUG_OBJECT (enc, "short header");
398         result = FALSE;
399       } else {
400         GST_DEBUG_OBJECT (enc, "other startcode");
401         /* all other startcodes need a flush */
402         result = TRUE;
403       }
404       break;
405   }
406   return result;
407 }
408
409 /* we expect buffers starting on startcodes. 
410  */
411 static GstFlowReturn
412 gst_rtp_mp4v_pay_handle_buffer (GstRTPBasePayload * basepayload,
413     GstBuffer * buffer)
414 {
415   GstRtpMP4VPay *rtpmp4vpay;
416   GstFlowReturn ret;
417   guint avail;
418   guint packet_len;
419   GstMapInfo map;
420   gsize size;
421   gboolean flush;
422   gint strip;
423   GstClockTime timestamp, duration;
424   gboolean vopi;
425   gboolean send_config;
426
427   ret = GST_FLOW_OK;
428   send_config = FALSE;
429
430   rtpmp4vpay = GST_RTP_MP4V_PAY (basepayload);
431
432   gst_buffer_map (buffer, &map, GST_MAP_READ);
433   size = map.size;
434   timestamp = GST_BUFFER_TIMESTAMP (buffer);
435   duration = GST_BUFFER_DURATION (buffer);
436   avail = gst_adapter_available (rtpmp4vpay->adapter);
437
438   if (duration == -1)
439     duration = 0;
440
441   /* empty buffer, take timestamp */
442   if (avail == 0) {
443     rtpmp4vpay->first_timestamp = timestamp;
444     rtpmp4vpay->duration = 0;
445   }
446
447   /* depay incomming data and see if we need to start a new RTP
448    * packet */
449   flush =
450       gst_rtp_mp4v_pay_depay_data (rtpmp4vpay, map.data, size, &strip, &vopi);
451   gst_buffer_unmap (buffer, &map);
452
453   if (strip) {
454     /* strip off config if requested */
455     if (!(rtpmp4vpay->config_interval > 0)) {
456       GstBuffer *subbuf;
457
458       GST_LOG_OBJECT (rtpmp4vpay, "stripping config at %d, size %d", strip,
459           (gint) size - strip);
460
461       /* strip off header */
462       subbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_MEMORY, strip,
463           size - strip);
464       GST_BUFFER_TIMESTAMP (subbuf) = timestamp;
465       gst_buffer_unref (buffer);
466       buffer = subbuf;
467
468       size = gst_buffer_get_size (buffer);
469     } else {
470       GST_LOG_OBJECT (rtpmp4vpay, "found config in stream");
471       rtpmp4vpay->last_config = timestamp;
472     }
473   }
474
475   /* there is a config request, see if we need to insert it */
476   if (vopi && (rtpmp4vpay->config_interval > 0) && rtpmp4vpay->config) {
477     if (rtpmp4vpay->last_config != -1) {
478       guint64 diff;
479
480       GST_LOG_OBJECT (rtpmp4vpay,
481           "now %" GST_TIME_FORMAT ", last VOP-I %" GST_TIME_FORMAT,
482           GST_TIME_ARGS (timestamp), GST_TIME_ARGS (rtpmp4vpay->last_config));
483
484       /* calculate diff between last config in milliseconds */
485       if (timestamp > rtpmp4vpay->last_config) {
486         diff = timestamp - rtpmp4vpay->last_config;
487       } else {
488         diff = 0;
489       }
490
491       GST_DEBUG_OBJECT (rtpmp4vpay,
492           "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
493
494       /* bigger than interval, queue config */
495       /* FIXME should convert timestamps to running time */
496       if (GST_TIME_AS_SECONDS (diff) >= rtpmp4vpay->config_interval) {
497         GST_DEBUG_OBJECT (rtpmp4vpay, "time to send config");
498         send_config = TRUE;
499       }
500     } else {
501       /* no known previous config time, send now */
502       GST_DEBUG_OBJECT (rtpmp4vpay, "no previous config time, send now");
503       send_config = TRUE;
504     }
505
506     if (send_config) {
507       /* we need to send config now first */
508       GST_LOG_OBJECT (rtpmp4vpay, "inserting config in stream");
509
510       /* insert header */
511       buffer = gst_buffer_append (gst_buffer_ref (rtpmp4vpay->config), buffer);
512
513       GST_BUFFER_TIMESTAMP (buffer) = timestamp;
514       size = gst_buffer_get_size (buffer);
515
516       if (timestamp != -1) {
517         rtpmp4vpay->last_config = timestamp;
518       }
519     }
520   }
521
522   /* if we need to flush, do so now */
523   if (flush) {
524     ret = gst_rtp_mp4v_pay_flush (rtpmp4vpay);
525     rtpmp4vpay->first_timestamp = timestamp;
526     rtpmp4vpay->duration = 0;
527     avail = 0;
528   }
529
530   /* get packet length of data and see if we exceeded MTU. */
531   packet_len = gst_rtp_buffer_calc_packet_len (avail + size, 0, 0);
532
533   if (gst_rtp_base_payload_is_filled (basepayload,
534           packet_len, rtpmp4vpay->duration + duration)) {
535     ret = gst_rtp_mp4v_pay_flush (rtpmp4vpay);
536     rtpmp4vpay->first_timestamp = timestamp;
537     rtpmp4vpay->duration = 0;
538   }
539
540   /* push new data */
541   gst_adapter_push (rtpmp4vpay->adapter, buffer);
542
543   rtpmp4vpay->duration += duration;
544
545   return ret;
546 }
547
548 static gboolean
549 gst_rtp_mp4v_pay_sink_event (GstRTPBasePayload * pay, GstEvent * event)
550 {
551   GstRtpMP4VPay *rtpmp4vpay;
552
553   rtpmp4vpay = GST_RTP_MP4V_PAY (pay);
554
555   GST_DEBUG ("Got event: %s", GST_EVENT_TYPE_NAME (event));
556
557   switch (GST_EVENT_TYPE (event)) {
558     case GST_EVENT_SEGMENT:
559     case GST_EVENT_EOS:
560       /* This flush call makes sure that the last buffer is always pushed
561        * to the base payloader */
562       gst_rtp_mp4v_pay_flush (rtpmp4vpay);
563       break;
564     case GST_EVENT_FLUSH_STOP:
565       gst_rtp_mp4v_pay_empty (rtpmp4vpay);
566       break;
567     default:
568       break;
569   }
570
571   /* let parent handle event too */
572   return GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (pay, event);
573 }
574
575 static void
576 gst_rtp_mp4v_pay_set_property (GObject * object, guint prop_id,
577     const GValue * value, GParamSpec * pspec)
578 {
579   GstRtpMP4VPay *rtpmp4vpay;
580
581   rtpmp4vpay = GST_RTP_MP4V_PAY (object);
582
583   switch (prop_id) {
584     case ARG_CONFIG_INTERVAL:
585       rtpmp4vpay->config_interval = g_value_get_uint (value);
586       break;
587     default:
588       break;
589   }
590 }
591
592 static void
593 gst_rtp_mp4v_pay_get_property (GObject * object, guint prop_id,
594     GValue * value, GParamSpec * pspec)
595 {
596   GstRtpMP4VPay *rtpmp4vpay;
597
598   rtpmp4vpay = GST_RTP_MP4V_PAY (object);
599
600   switch (prop_id) {
601     case ARG_CONFIG_INTERVAL:
602       g_value_set_uint (value, rtpmp4vpay->config_interval);
603       break;
604     default:
605       break;
606   }
607 }
608
609 gboolean
610 gst_rtp_mp4v_pay_plugin_init (GstPlugin * plugin)
611 {
612   return gst_element_register (plugin, "rtpmp4vpay",
613       GST_RANK_SECONDARY, GST_TYPE_RTP_MP4V_PAY);
614 }