rtph263ppay: Implement getcaps following RFC 4629, picks the right annexes
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtph263ppay.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 #include <stdlib.h>
26
27 #include <gst/rtp/gstrtpbuffer.h>
28
29 #include "gstrtph263ppay.h"
30
31 #define DEFAULT_FRAGMENTATION_MODE   GST_FRAGMENTATION_MODE_NORMAL
32
33 enum
34 {
35   PROP_0,
36   PROP_FRAGMENTATION_MODE
37 };
38
39 #define GST_TYPE_FRAGMENTATION_MODE (gst_fragmentation_mode_get_type())
40 static GType
41 gst_fragmentation_mode_get_type (void)
42 {
43   static GType fragmentation_mode_type = 0;
44   static const GEnumValue fragmentation_mode[] = {
45     {GST_FRAGMENTATION_MODE_NORMAL, "Normal", "normal"},
46     {GST_FRAGMENTATION_MODE_SYNC, "Fragment at sync points", "sync"},
47     {0, NULL, NULL},
48   };
49
50   if (!fragmentation_mode_type) {
51     fragmentation_mode_type =
52         g_enum_register_static ("GstFragmentationMode", fragmentation_mode);
53   }
54   return fragmentation_mode_type;
55 }
56
57
58 GST_DEBUG_CATEGORY_STATIC (rtph263ppay_debug);
59 #define GST_CAT_DEFAULT rtph263ppay_debug
60
61 static GstStaticPadTemplate gst_rtp_h263p_pay_sink_template =
62 GST_STATIC_PAD_TEMPLATE ("sink",
63     GST_PAD_SINK,
64     GST_PAD_ALWAYS,
65     GST_STATIC_CAPS ("video/x-h263, " "variant = (string) \"itu\"")
66     );
67
68 /*
69  * We also set all of those as required:
70  *
71  * "annex-f = (boolean) {true, false},"
72  * "annex-i = (boolean) {true, false},"
73  * "annex-j = (boolean) {true, false},"
74  * "annex-l = (boolean) {true, false},"
75  * "annex-t = (boolean) {true, false},"
76  * "annex-v = (boolean) {true, false}")
77  */
78
79
80 static GstStaticPadTemplate gst_rtp_h263p_pay_src_template =
81     GST_STATIC_PAD_TEMPLATE ("src",
82     GST_PAD_SRC,
83     GST_PAD_ALWAYS,
84     GST_STATIC_CAPS ("application/x-rtp, "
85         "media = (string) \"video\", "
86         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
87         "clock-rate = (int) 90000, " "encoding-name = (string) \"H263-1998\"; "
88         "application/x-rtp, "
89         "media = (string) \"video\", "
90         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
91         "clock-rate = (int) 90000, " "encoding-name = (string) \"H263-2000\"")
92     );
93
94 static void gst_rtp_h263p_pay_finalize (GObject * object);
95
96 static void gst_rtp_h263p_pay_set_property (GObject * object, guint prop_id,
97     const GValue * value, GParamSpec * pspec);
98 static void gst_rtp_h263p_pay_get_property (GObject * object, guint prop_id,
99     GValue * value, GParamSpec * pspec);
100
101 static gboolean gst_rtp_h263p_pay_setcaps (GstBaseRTPPayload * payload,
102     GstCaps * caps);
103 static GstCaps *gst_rtp_h263p_pay_sink_getcaps (GstBaseRTPPayload * payload,
104     GstPad * pad);
105 static GstFlowReturn gst_rtp_h263p_pay_handle_buffer (GstBaseRTPPayload *
106     payload, GstBuffer * buffer);
107
108 GST_BOILERPLATE (GstRtpH263PPay, gst_rtp_h263p_pay, GstBaseRTPPayload,
109     GST_TYPE_BASE_RTP_PAYLOAD);
110
111 static void
112 gst_rtp_h263p_pay_base_init (gpointer klass)
113 {
114   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
115
116   gst_element_class_add_pad_template (element_class,
117       gst_static_pad_template_get (&gst_rtp_h263p_pay_src_template));
118   gst_element_class_add_pad_template (element_class,
119       gst_static_pad_template_get (&gst_rtp_h263p_pay_sink_template));
120
121   gst_element_class_set_details_simple (element_class, "RTP H263 payloader",
122       "Codec/Payloader/Network/RTP",
123       "Payload-encodes H263/+/++ video in RTP packets (RFC 4629)",
124       "Wim Taymans <wim.taymans@gmail.com>");
125 }
126
127 static void
128 gst_rtp_h263p_pay_class_init (GstRtpH263PPayClass * klass)
129 {
130   GObjectClass *gobject_class;
131   GstBaseRTPPayloadClass *gstbasertppayload_class;
132
133   gobject_class = (GObjectClass *) klass;
134   gstbasertppayload_class = (GstBaseRTPPayloadClass *) klass;
135
136   gobject_class->finalize = gst_rtp_h263p_pay_finalize;
137   gobject_class->set_property = gst_rtp_h263p_pay_set_property;
138   gobject_class->get_property = gst_rtp_h263p_pay_get_property;
139
140   gstbasertppayload_class->set_caps = gst_rtp_h263p_pay_setcaps;
141   gstbasertppayload_class->get_caps = gst_rtp_h263p_pay_sink_getcaps;
142   gstbasertppayload_class->handle_buffer = gst_rtp_h263p_pay_handle_buffer;
143
144   g_object_class_install_property (G_OBJECT_CLASS (klass),
145       PROP_FRAGMENTATION_MODE, g_param_spec_enum ("fragmentation-mode",
146           "Fragmentation Mode",
147           "Packet Fragmentation Mode", GST_TYPE_FRAGMENTATION_MODE,
148           DEFAULT_FRAGMENTATION_MODE,
149           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
150
151   GST_DEBUG_CATEGORY_INIT (rtph263ppay_debug, "rtph263ppay",
152       0, "rtph263ppay (RFC 4629)");
153 }
154
155 static void
156 gst_rtp_h263p_pay_init (GstRtpH263PPay * rtph263ppay,
157     GstRtpH263PPayClass * klass)
158 {
159   rtph263ppay->adapter = gst_adapter_new ();
160
161   rtph263ppay->fragmentation_mode = DEFAULT_FRAGMENTATION_MODE;
162 }
163
164 static void
165 gst_rtp_h263p_pay_finalize (GObject * object)
166 {
167   GstRtpH263PPay *rtph263ppay;
168
169   rtph263ppay = GST_RTP_H263P_PAY (object);
170
171   g_object_unref (rtph263ppay->adapter);
172   rtph263ppay->adapter = NULL;
173
174   G_OBJECT_CLASS (parent_class)->finalize (object);
175 }
176
177 static gboolean
178 gst_rtp_h263p_pay_setcaps (GstBaseRTPPayload * payload, GstCaps * caps)
179 {
180   gboolean res;
181   GstCaps *peercaps;
182   gchar *encoding_name = NULL;
183
184   g_return_val_if_fail (gst_caps_is_fixed (caps), FALSE);
185
186   peercaps = gst_pad_peer_get_caps (GST_BASE_RTP_PAYLOAD_SRCPAD (payload));
187   if (peercaps) {
188     GstCaps *intersect = gst_caps_intersect (peercaps,
189         gst_pad_get_pad_template_caps (GST_BASE_RTP_PAYLOAD_SRCPAD (payload)));
190
191     gst_caps_unref (peercaps);
192     if (!gst_caps_is_empty (intersect)) {
193       GstStructure *s = gst_caps_get_structure (intersect, 0);
194       encoding_name = g_strdup (gst_structure_get_string (s, "encoding-name"));
195     }
196     gst_caps_unref (intersect);
197   }
198
199   if (!encoding_name)
200     encoding_name = g_strdup ("H263-1998");
201
202   gst_basertppayload_set_options (payload, "video", TRUE,
203       (gchar *) encoding_name, 90000);
204   res = gst_basertppayload_set_outcaps (payload, NULL);
205   g_free (encoding_name);
206
207   return res;
208 }
209
210 static GstCaps *
211 gst_rtp_h263p_pay_sink_getcaps (GstBaseRTPPayload * payload, GstPad * pad)
212 {
213   GstRtpH263PPay *rtph263ppay;
214   GstCaps *caps = gst_caps_new_empty ();
215   GstCaps *peercaps = NULL;
216   GstCaps *intersect = NULL;
217   guint i;
218
219   rtph263ppay = GST_RTP_H263P_PAY (payload);
220
221   peercaps = gst_pad_peer_get_caps (GST_BASE_RTP_PAYLOAD_SRCPAD (payload));
222   if (!peercaps)
223     return
224         gst_caps_copy (gst_pad_get_pad_template_caps
225         (GST_BASE_RTP_PAYLOAD_SRCPAD (payload)));
226
227   intersect = gst_caps_intersect (peercaps,
228       gst_pad_get_pad_template_caps (GST_BASE_RTP_PAYLOAD_SRCPAD (payload)));
229   gst_caps_unref (peercaps);
230
231   if (gst_caps_is_empty (intersect))
232     return intersect;
233
234   for (i = 0; i < gst_caps_get_size (intersect); i++) {
235     GstStructure *s = gst_caps_get_structure (intersect, i);
236     const gchar *encoding_name = gst_structure_get_string (s, "encoding-name");
237
238     if (!strcmp (encoding_name, "H263-2000")) {
239       const gchar *profile_str = gst_structure_get_string (s, "profile");
240       const gchar *level_str = gst_structure_get_string (s, "level");
241       int profile = 0;
242       int level = 0;
243
244       if (profile_str && level_str) {
245         gboolean i = FALSE, j = FALSE, l = FALSE, t = FALSE, f = FALSE,
246             v = FALSE;
247         GstStructure *new_s = gst_structure_new ("video/x-h263",
248             "variant", G_TYPE_STRING, "itu",
249             NULL);
250
251         profile = atoi (profile_str);
252         level = atoi (level_str);
253
254         /* These profiles are defined in the H.263 Annex X */
255         switch (profile) {
256           case 0:
257             /* The Baseline Profile (Profile 0) */
258             break;
259           case 1:
260             /* H.320 Coding Efficiency Version 2 Backward-Compatibility Profile
261              * (Profile 1)
262              * Baseline + Annexes I, J, L.4 and T
263              */
264             i = j = l = t = TRUE;
265             break;
266           case 2:
267             /* Version 1 Backward-Compatibility Profile (Profile 2)
268              * Baseline + Annex F
269              */
270             i = j = l = t = f = TRUE;
271             break;
272           case 3:
273             /* Version 2 Interactive and Streaming Wireless Profile
274              * Baseline + Annexes I, J, T
275              */
276             i = j = t = TRUE;
277             break;
278           case 4:
279             /* Version 3 Interactive and Streaming Wireless Profile (Profile 4)
280              * Baseline + Annexes I, J, T, V, W.6.3.8,
281              */
282             /* Missing W.6.3.8 */
283             i = j = t = v = TRUE;
284             break;
285           case 5:
286             /* Conversational High Compression Profile (Profile 5)
287              * Baseline + Annexes F, I, J, L.4, T, D, U
288              */
289             /* Missing D, U */
290             f = i = j = l = t = TRUE;
291             break;
292           case 6:
293             /* Conversational Internet Profile (Profile 6)
294              * Baseline + Annexes F, I, J, L.4, T, D, U and
295              * K with arbitratry slice ordering
296              */
297             /* Missing D, U, K with arbitratry slice ordering */
298             f = i = j = l = t = TRUE;
299             break;
300           case 7:
301             /* Conversational Interlace Profile (Profile 7)
302              * Baseline + Annexes F, I, J, L.4, T, D, U,  W.6.3.11
303              */
304             /* Missing D, U, W.6.3.11 */
305             f = i = j = l = t = TRUE;
306             break;
307           case 8:
308             /* High Latency Profile (Profile 8)
309              * Baseline + Annexes F, I, J, L.4, T, D, U, P.5, O.1.1 and
310              * K with arbitratry slice ordering
311              */
312             /* Missing D, U, P.5, O.1.1 */
313             f = i = j = l = t = TRUE;
314             break;
315         }
316
317
318         if (f || i || j || t || l || v) {
319           GValue list = { 0 };
320           GValue vstr = { 0 };
321
322           g_value_init (&list, GST_TYPE_LIST);
323           g_value_init (&vstr, G_TYPE_STRING);
324
325           g_value_set_static_string (&vstr, "h263");
326           gst_value_list_append_value (&list, &vstr);
327           g_value_set_static_string (&vstr, "h263p");
328           gst_value_list_append_value (&list, &vstr);
329
330           if (l || v) {
331             g_value_set_static_string (&vstr, "h263pp");
332             gst_value_list_append_value (&list, &vstr);
333           }
334           g_value_unset (&vstr);
335
336           gst_structure_set_value (new_s, "h263version", &list);
337           g_value_unset (&list);
338         } else {
339           gst_structure_set (new_s, "h263version", G_TYPE_STRING, "h263", NULL);
340         }
341
342
343         if (!f)
344           gst_structure_set (new_s, "annex-f", G_TYPE_BOOLEAN, FALSE, NULL);
345         if (!i)
346           gst_structure_set (new_s, "annex-i", G_TYPE_BOOLEAN, FALSE, NULL);
347         if (!j)
348           gst_structure_set (new_s, "annex-j", G_TYPE_BOOLEAN, FALSE, NULL);
349         if (!t)
350           gst_structure_set (new_s, "annex-t", G_TYPE_BOOLEAN, FALSE, NULL);
351         if (!l)
352           gst_structure_set (new_s, "annex-l", G_TYPE_BOOLEAN, FALSE, NULL);
353         if (!v)
354           gst_structure_set (new_s, "annex-v", G_TYPE_BOOLEAN, FALSE, NULL);
355
356         /* FIXME:
357          * Ignore the profile for now, gst-ffmpeg need to accept
358          * height/width/framerates first
359          */
360
361         gst_caps_merge_structure (caps, new_s);
362       } else {
363         GstStructure *new_s = gst_structure_new ("video/x-h263",
364             "variant", G_TYPE_STRING, "itu",
365             "h263version", G_TYPE_STRING, "h263",
366             NULL);
367
368         GST_DEBUG_OBJECT (rtph263ppay, "No profile or level specified"
369             " for H263-2000, defaulting to baseline H263");
370
371         gst_caps_merge_structure (caps, new_s);
372       }
373     } else {
374       gboolean f = FALSE, i = FALSE, j = FALSE, t = FALSE;
375       /* FIXME: ffmpeg support the Appendix K too, how do we express it ?
376        *   guint k;
377        */
378       const gchar *str;
379       GstStructure *new_s = gst_structure_new ("video/x-h263",
380           "variant", G_TYPE_STRING, "itu",
381           NULL);
382
383       str = gst_structure_get_string (s, "f");
384       if (str && !strcmp (str, "1"))
385         f = TRUE;
386
387       str = gst_structure_get_string (s, "i");
388       if (str && !strcmp (str, "1"))
389         i = TRUE;
390
391       str = gst_structure_get_string (s, "j");
392       if (str && !strcmp (str, "1"))
393         j = TRUE;
394
395       str = gst_structure_get_string (s, "t");
396       if (str && !strcmp (str, "1"))
397         t = TRUE;
398
399       if (f || i || j || t) {
400         GValue list = { 0 };
401         GValue vstr = { 0 };
402
403         g_value_init (&list, GST_TYPE_LIST);
404         g_value_init (&vstr, G_TYPE_STRING);
405
406         g_value_set_static_string (&vstr, "h263");
407         gst_value_list_append_value (&list, &vstr);
408         g_value_set_static_string (&vstr, "h263p");
409         gst_value_list_append_value (&list, &vstr);
410         g_value_unset (&vstr);
411
412         gst_structure_set_value (new_s, "h263version", &list);
413         g_value_unset (&list);
414       } else {
415         gst_structure_set (new_s, "h263version", G_TYPE_STRING, "h263", NULL);
416       }
417
418       if (!f)
419         gst_structure_set (new_s, "annex-f", G_TYPE_BOOLEAN, FALSE, NULL);
420       if (!i)
421         gst_structure_set (new_s, "annex-i", G_TYPE_BOOLEAN, FALSE, NULL);
422       if (!j)
423         gst_structure_set (new_s, "annex-j", G_TYPE_BOOLEAN, FALSE, NULL);
424       if (!t)
425         gst_structure_set (new_s, "annex-t", G_TYPE_BOOLEAN, FALSE, NULL);
426
427       gst_caps_merge_structure (caps, new_s);
428     }
429   }
430
431   gst_caps_unref (intersect);
432
433   return caps;
434 }
435
436
437 static void
438 gst_rtp_h263p_pay_set_property (GObject * object, guint prop_id,
439     const GValue * value, GParamSpec * pspec)
440 {
441   GstRtpH263PPay *rtph263ppay;
442
443   rtph263ppay = GST_RTP_H263P_PAY (object);
444
445   switch (prop_id) {
446     case PROP_FRAGMENTATION_MODE:
447       rtph263ppay->fragmentation_mode = g_value_get_enum (value);
448       break;
449     default:
450       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
451       break;
452   }
453 }
454
455 static void
456 gst_rtp_h263p_pay_get_property (GObject * object, guint prop_id,
457     GValue * value, GParamSpec * pspec)
458 {
459   GstRtpH263PPay *rtph263ppay;
460
461   rtph263ppay = GST_RTP_H263P_PAY (object);
462
463   switch (prop_id) {
464     case PROP_FRAGMENTATION_MODE:
465       g_value_set_enum (value, rtph263ppay->fragmentation_mode);
466       break;
467     default:
468       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
469       break;
470   }
471 }
472
473 static GstFlowReturn
474 gst_rtp_h263p_pay_flush (GstRtpH263PPay * rtph263ppay)
475 {
476   guint avail;
477   GstBuffer *outbuf;
478   GstFlowReturn ret;
479   gboolean fragmented;
480
481   avail = gst_adapter_available (rtph263ppay->adapter);
482   if (avail == 0)
483     return GST_FLOW_OK;
484
485   fragmented = FALSE;
486   /* This algorithm assumes the H263/+/++ encoder sends complete frames in each
487    * buffer */
488   /* With Fragmentation Mode at GST_FRAGMENTATION_MODE_NORMAL:
489    *  This algorithm implements the Follow-on packets method for packetization.
490    *  This assumes low packet loss network. 
491    * With Fragmentation Mode at GST_FRAGMENTATION_MODE_SYNC:
492    *  This algorithm separates large frames at synchronisation points (Segments)
493    *  (See RFC 4629 section 6). It would be interesting to have a property such as network
494    *  quality to select between both packetization methods */
495   /* TODO Add VRC supprt (See RFC 4629 section 5.2) */
496
497   while (avail > 0) {
498     guint towrite;
499     guint8 *payload;
500     guint payload_len;
501     gint header_len;
502     guint next_gop = 0;
503     gboolean found_gob = FALSE;
504
505     if (rtph263ppay->fragmentation_mode == GST_FRAGMENTATION_MODE_SYNC) {
506       /* start after 1st gop possible */
507       guint parsed_len = 3;
508       const guint8 *parse_data = NULL;
509
510       parse_data = gst_adapter_peek (rtph263ppay->adapter, avail);
511
512       /* Check if we have a gob or eos , eossbs */
513       /* FIXME EOS and EOSSBS packets should never contain any gobs and vice-versa */
514       if (avail >= 3 && *parse_data == 0 && *(parse_data + 1) == 0
515           && *(parse_data + 2) >= 0x80) {
516         GST_DEBUG_OBJECT (rtph263ppay, " Found GOB header");
517         found_gob = TRUE;
518       }
519       /* Find next and cut the packet accordingly */
520       /* TODO we should get as many gobs as possible until MTU is reached, this
521        * code seems to just get one GOB per packet */
522       while (parsed_len + 2 < avail) {
523         if (parse_data[parsed_len] == 0 && parse_data[parsed_len + 1] == 0
524             && parse_data[parsed_len + 2] >= 0x80) {
525           next_gop = parsed_len;
526           GST_DEBUG_OBJECT (rtph263ppay, " Next GOB Detected at :  %d",
527               next_gop);
528           break;
529         }
530         parsed_len++;
531       }
532     }
533
534     /* for picture start frames (non-fragmented), we need to remove the first
535      * two 0x00 bytes and set P=1 */
536     header_len = (fragmented && !found_gob) ? 2 : 0;
537
538     towrite = MIN (avail, gst_rtp_buffer_calc_payload_len
539         (GST_BASE_RTP_PAYLOAD_MTU (rtph263ppay) - header_len, 0, 0));
540
541     if (next_gop > 0)
542       towrite = MIN (next_gop, towrite);
543
544     payload_len = header_len + towrite;
545
546     outbuf = gst_rtp_buffer_new_allocate (payload_len, 0, 0);
547     /* last fragment gets the marker bit set */
548     gst_rtp_buffer_set_marker (outbuf, avail > towrite ? 0 : 1);
549
550     payload = gst_rtp_buffer_get_payload (outbuf);
551
552     gst_adapter_copy (rtph263ppay->adapter, &payload[header_len], 0, towrite);
553
554     /*  0                   1
555      *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
556      * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
557      * |   RR    |P|V|   PLEN    |PEBIT|
558      * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
559      */
560     /* if fragmented or gop header , write p bit =1 */
561     payload[0] = (fragmented && !found_gob) ? 0x00 : 0x04;
562     payload[1] = 0;
563
564     GST_BUFFER_TIMESTAMP (outbuf) = rtph263ppay->first_timestamp;
565     GST_BUFFER_DURATION (outbuf) = rtph263ppay->first_duration;
566
567     gst_adapter_flush (rtph263ppay->adapter, towrite);
568
569     ret = gst_basertppayload_push (GST_BASE_RTP_PAYLOAD (rtph263ppay), outbuf);
570
571     avail -= towrite;
572     fragmented = TRUE;
573   }
574
575   return ret;
576 }
577
578 static GstFlowReturn
579 gst_rtp_h263p_pay_handle_buffer (GstBaseRTPPayload * payload,
580     GstBuffer * buffer)
581 {
582   GstRtpH263PPay *rtph263ppay;
583   GstFlowReturn ret;
584
585   rtph263ppay = GST_RTP_H263P_PAY (payload);
586
587   rtph263ppay->first_timestamp = GST_BUFFER_TIMESTAMP (buffer);
588   rtph263ppay->first_duration = GST_BUFFER_DURATION (buffer);
589
590   /* we always encode and flush a full picture */
591   gst_adapter_push (rtph263ppay->adapter, buffer);
592   ret = gst_rtp_h263p_pay_flush (rtph263ppay);
593
594   return ret;
595 }
596
597 gboolean
598 gst_rtp_h263p_pay_plugin_init (GstPlugin * plugin)
599 {
600   return gst_element_register (plugin, "rtph263ppay",
601       GST_RANK_SECONDARY, GST_TYPE_RTP_H263P_PAY);
602 }