fd1676588f1d655d5cbd8d084558b05648eda5b8
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtpvp9pay.c
1 /*
2  * gstrtpvp9pay.c - Source for GstRtpVP9Pay
3  * Copyright (C) 2011 Sjoerd Simons <sjoerd@luon.net>
4  * Copyright (C) 2011 Collabora Ltd.
5  *   Contact: Youness Alaoui <youness.alaoui@collabora.co.uk>
6  * Copyright (C) 2015 Stian Selnes <stian@pexip.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <gst/base/gstbitreader.h>
32 #include <gst/rtp/gstrtppayloads.h>
33 #include <gst/rtp/gstrtpbuffer.h>
34 #include <gst/video/video.h>
35 #include "dboolhuff.h"
36 #include "gstrtpvp9pay.h"
37 #include "gstrtputils.h"
38
39 GST_DEBUG_CATEGORY_STATIC (gst_rtp_vp9_pay_debug);
40 #define GST_CAT_DEFAULT gst_rtp_vp9_pay_debug
41
42 #define DEFAULT_PICTURE_ID_MODE VP9_PAY_NO_PICTURE_ID
43
44 enum
45 {
46   PROP_0,
47   PROP_PICTURE_ID_MODE
48 };
49
50 #define GST_TYPE_RTP_VP9_PAY_PICTURE_ID_MODE (gst_rtp_vp9_pay_picture_id_mode_get_type())
51 static GType
52 gst_rtp_vp9_pay_picture_id_mode_get_type (void)
53 {
54   static GType mode_type = 0;
55   static const GEnumValue modes[] = {
56     {VP9_PAY_NO_PICTURE_ID, "No Picture ID", "none"},
57     {VP9_PAY_PICTURE_ID_7BITS, "7-bit Picture ID", "7-bit"},
58     {VP9_PAY_PICTURE_ID_15BITS, "15-bit Picture ID", "15-bit"},
59     {0, NULL, NULL},
60   };
61
62   if (!mode_type) {
63     mode_type = g_enum_register_static ("GstVP9RTPPayMode", modes);
64   }
65   return mode_type;
66 }
67
68 static void gst_rtp_vp9_pay_get_property (GObject * object, guint prop_id,
69     GValue * value, GParamSpec * pspec);
70 static void gst_rtp_vp9_pay_set_property (GObject * object, guint prop_id,
71     const GValue * value, GParamSpec * pspec);
72
73 static GstFlowReturn gst_rtp_vp9_pay_handle_buffer (GstRTPBasePayload * payload,
74     GstBuffer * buffer);
75 static gboolean gst_rtp_vp9_pay_sink_event (GstRTPBasePayload * payload,
76     GstEvent * event);
77 static gboolean gst_rtp_vp9_pay_set_caps (GstRTPBasePayload * payload,
78     GstCaps * caps);
79
80 G_DEFINE_TYPE (GstRtpVP9Pay, gst_rtp_vp9_pay, GST_TYPE_RTP_BASE_PAYLOAD);
81
82 static GstStaticPadTemplate gst_rtp_vp9_pay_src_template =
83 GST_STATIC_PAD_TEMPLATE ("src",
84     GST_PAD_SRC,
85     GST_PAD_ALWAYS,
86     GST_STATIC_CAPS ("application/x-rtp, "
87         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ","
88         "clock-rate = (int) 90000, encoding-name = (string) { \"VP9\", \"VP9-DRAFT-IETF-01\" }"));
89
90 static GstStaticPadTemplate gst_rtp_vp9_pay_sink_template =
91 GST_STATIC_PAD_TEMPLATE ("sink",
92     GST_PAD_SINK,
93     GST_PAD_ALWAYS,
94     GST_STATIC_CAPS ("video/x-vp9"));
95
96 static void
97 gst_rtp_vp9_pay_init (GstRtpVP9Pay * obj)
98 {
99   obj->picture_id_mode = DEFAULT_PICTURE_ID_MODE;
100   if (obj->picture_id_mode == VP9_PAY_PICTURE_ID_7BITS)
101     obj->picture_id = g_random_int_range (0, G_MAXUINT8) & 0x7F;
102   else if (obj->picture_id_mode == VP9_PAY_PICTURE_ID_15BITS)
103     obj->picture_id = g_random_int_range (0, G_MAXUINT16) & 0x7FFF;
104 }
105
106 static void
107 gst_rtp_vp9_pay_class_init (GstRtpVP9PayClass * gst_rtp_vp9_pay_class)
108 {
109   GObjectClass *gobject_class = G_OBJECT_CLASS (gst_rtp_vp9_pay_class);
110   GstElementClass *element_class = GST_ELEMENT_CLASS (gst_rtp_vp9_pay_class);
111   GstRTPBasePayloadClass *pay_class =
112       GST_RTP_BASE_PAYLOAD_CLASS (gst_rtp_vp9_pay_class);
113
114   gobject_class->set_property = gst_rtp_vp9_pay_set_property;
115   gobject_class->get_property = gst_rtp_vp9_pay_get_property;
116
117   g_object_class_install_property (gobject_class, PROP_PICTURE_ID_MODE,
118       g_param_spec_enum ("picture-id-mode", "Picture ID Mode",
119           "The picture ID mode for payloading",
120           GST_TYPE_RTP_VP9_PAY_PICTURE_ID_MODE, DEFAULT_PICTURE_ID_MODE,
121           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
122
123   gst_element_class_add_static_pad_template (element_class,
124       &gst_rtp_vp9_pay_sink_template);
125   gst_element_class_add_static_pad_template (element_class,
126       &gst_rtp_vp9_pay_src_template);
127
128   gst_element_class_set_static_metadata (element_class, "RTP VP9 payloader",
129       "Codec/Payloader/Network/RTP",
130       "Puts VP9 video in RTP packets)", "Stian Selnes <stian@pexip.com>");
131
132   pay_class->handle_buffer = gst_rtp_vp9_pay_handle_buffer;
133   pay_class->sink_event = gst_rtp_vp9_pay_sink_event;
134   pay_class->set_caps = gst_rtp_vp9_pay_set_caps;
135
136   GST_DEBUG_CATEGORY_INIT (gst_rtp_vp9_pay_debug, "rtpvp9pay", 0,
137       "VP9 Video RTP Payloader");
138 }
139
140 static void
141 gst_rtp_vp9_pay_set_property (GObject * object,
142     guint prop_id, const GValue * value, GParamSpec * pspec)
143 {
144   GstRtpVP9Pay *rtpvp9pay = GST_RTP_VP9_PAY (object);
145
146   switch (prop_id) {
147     case PROP_PICTURE_ID_MODE:
148       rtpvp9pay->picture_id_mode = g_value_get_enum (value);
149       if (rtpvp9pay->picture_id_mode == VP9_PAY_PICTURE_ID_7BITS)
150         rtpvp9pay->picture_id = g_random_int_range (0, G_MAXUINT8) & 0x7F;
151       else if (rtpvp9pay->picture_id_mode == VP9_PAY_PICTURE_ID_15BITS)
152         rtpvp9pay->picture_id = g_random_int_range (0, G_MAXUINT16) & 0x7FFF;
153       break;
154     default:
155       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
156       break;
157   }
158 }
159
160 static void
161 gst_rtp_vp9_pay_get_property (GObject * object,
162     guint prop_id, GValue * value, GParamSpec * pspec)
163 {
164   GstRtpVP9Pay *rtpvp9pay = GST_RTP_VP9_PAY (object);
165
166   switch (prop_id) {
167     case PROP_PICTURE_ID_MODE:
168       g_value_set_enum (value, rtpvp9pay->picture_id_mode);
169       break;
170     default:
171       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
172       break;
173   }
174 }
175
176 #define VP9_PROFILE_0 0
177 #define VP9_PROFILE_1 1
178 #define VP9_PROFILE_2 2
179 #define VP9_PROFILE_3 3
180 #define VP9_FRAME_MARKER 0x2
181 #define VPX_CS_SRGB 7
182
183 static gboolean
184 gst_rtp_vp9_pay_parse_frame (GstRtpVP9Pay * self, GstBuffer * buffer,
185     gsize buffer_size)
186 {
187   GstMapInfo map = GST_MAP_INFO_INIT;
188   GstBitReader reader;
189   guint8 *data;
190   gsize size;
191   gboolean keyframe;
192   guint32 tmp, profile;
193
194   if (G_UNLIKELY (buffer_size < 3))
195     goto error;
196
197   if (!gst_buffer_map (buffer, &map, GST_MAP_READ) || !map.data)
198     goto error;
199
200   data = map.data;
201   size = map.size;
202
203   gst_bit_reader_init (&reader, data, size);
204
205
206   /* frame marker */
207   if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 2)
208       || tmp != VP9_FRAME_MARKER)
209     goto error;
210
211   /* profile, variable length */
212   if (!gst_bit_reader_get_bits_uint32 (&reader, &profile, 2))
213     goto error;
214   if (profile > 2) {
215     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 1))
216       goto error;
217     profile += tmp;
218   }
219
220   /* show existing frame */
221   if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 1))
222     goto error;
223   if (tmp) {
224     if (!gst_bit_reader_skip (&reader, 3))
225       goto error;
226     return TRUE;
227   }
228
229   /* frame type */
230   if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 1))
231     goto error;
232   self->is_keyframe = keyframe = (tmp == 0);
233
234   /* show frame and resilient mode */
235   if (!gst_bit_reader_skip (&reader, 2))
236     goto error;
237
238   if (keyframe) {
239     /* sync code */
240     const guint32 sync_code = 0x498342;
241     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 24))
242       goto error;
243     if (tmp != sync_code)
244       goto error;
245
246     if (profile >= VP9_PROFILE_2) {
247       /* bit depth */
248       if (!gst_bit_reader_skip (&reader, 1))
249         goto error;
250     }
251
252     /* color space */
253     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 3))
254       goto error;
255     if (tmp != VPX_CS_SRGB) {
256       /* color range */
257       if (!gst_bit_reader_skip (&reader, 1))
258         goto error;
259       if (profile == VP9_PROFILE_1 || profile == VP9_PROFILE_3) {
260         /* subsampling + reserved bit */
261         if (!gst_bit_reader_skip (&reader, 2 + 1))
262           goto error;
263       }
264     } else {
265       if (profile == VP9_PROFILE_1 || profile == VP9_PROFILE_3)
266         /* reserved bit */
267         if (!gst_bit_reader_skip (&reader, 1))
268           goto error;
269     }
270
271     /* frame size */
272     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 16))
273       goto error;
274     self->width = tmp + 1;
275     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 16))
276       goto error;
277     self->height = tmp + 1;
278
279     /* render size */
280     if (!gst_bit_reader_get_bits_uint32 (&reader, &tmp, 1))
281       goto error;
282     if (tmp) {
283       if (!gst_bit_reader_skip (&reader, 32))
284         goto error;
285     }
286
287     GST_INFO_OBJECT (self, "parsed width=%d height=%d", self->width,
288         self->height);
289   }
290
291
292   gst_buffer_unmap (buffer, &map);
293   return TRUE;
294
295 error:
296   GST_DEBUG ("Failed to parse frame");
297   if (map.memory != NULL) {
298     gst_buffer_unmap (buffer, &map);
299   }
300   return FALSE;
301 }
302
303 static gsize
304 gst_rtp_vp9_calc_header_len (GstRtpVP9Pay * self, gboolean start)
305 {
306   gsize len = 1;
307
308   switch (self->picture_id_mode) {
309     case VP9_PAY_PICTURE_ID_7BITS:
310       len += 1;
311       break;
312     case VP9_PAY_PICTURE_ID_15BITS:
313       len += 2;
314     default:
315       break;
316   }
317
318   /* Assume non-flexible mode */
319   /* Assume L-bit not set, no L header */
320
321   if (self->is_keyframe && start) {
322     /* Assume V-bit set */
323     /* FIXME: SS depends on layers and prediction structure */
324     /* For now assume 1 spatial and 1 temporal layer. */
325     /* FIXME: Only for the first packet in the key frame */
326     len += 8;
327   }
328
329   return len;
330 }
331
332 /* VP9 RTP header, non-flexible mode:
333
334          0 1 2 3 4 5 6 7
335         +-+-+-+-+-+-+-+-+
336         |I|P|L|F|B|E|V|-| (REQUIRED)
337         +-+-+-+-+-+-+-+-+
338    I:   |M| PICTURE ID  | (RECOMMENDED)
339         +-+-+-+-+-+-+-+-+
340    M:   | EXTENDED PID  | (RECOMMENDED)
341         +-+-+-+-+-+-+-+-+
342    L:   |  T  |U|  S  |D| (CONDITIONALLY RECOMMENDED)
343         +-+-+-+-+-+-+-+-+                             -\
344    P,F: | P_DIFF    |X|N| (CONDITIONALLY RECOMMENDED)  .
345         +-+-+-+-+-+-+-+-+                              . - up to 3 times
346    X:   |EXTENDED P_DIFF| (OPTIONAL)                   .
347         +-+-+-+-+-+-+-+-+                             -/
348    V:   | SS            |
349         | ..            |
350         +-+-+-+-+-+-+-+-+
351
352    Scalability structure (SS)
353      (from https://chromium.googlesource.com/external/webrtc/+/HEAD/webrtc/modules/rtp_rtcp/source/rtp_format_vp9.cc
354      since latest draft is not up to date with chromium)
355
356         +-+-+-+-+-+-+-+-+
357    V:   | N_S |Y|G|-|-|-|
358         +-+-+-+-+-+-+-+-+              -|
359    Y:   |     WIDTH     | (OPTIONAL)    .
360         +               +               .
361         |               | (OPTIONAL)    .
362         +-+-+-+-+-+-+-+-+               . N_S + 1 times
363         |     HEIGHT    | (OPTIONAL)    .
364         +               +               .
365         |               | (OPTIONAL)    .
366         +-+-+-+-+-+-+-+-+              -|
367    G:   |      N_G      | (OPTIONAL)
368         +-+-+-+-+-+-+-+-+                           -|
369    N_G: |  T  |U| R |-|-| (OPTIONAL)                 .
370         +-+-+-+-+-+-+-+-+              -|            . N_G times
371         |    P_DIFF     | (OPTIONAL)    . R times    .
372         +-+-+-+-+-+-+-+-+              -|           -|
373
374 **/
375
376 /* When growing the vp9 header keep max payload len calculation in sync */
377 static GstBuffer *
378 gst_rtp_vp9_create_header_buffer (GstRtpVP9Pay * self,
379     gboolean start, gboolean mark, GstBuffer * in)
380 {
381   GstBuffer *out;
382   guint8 *p;
383   GstRTPBuffer rtpbuffer = GST_RTP_BUFFER_INIT;
384   guint off = 1;
385   guint hdrlen = gst_rtp_vp9_calc_header_len (self, start);
386
387   out = gst_rtp_buffer_new_allocate (hdrlen, 0, 0);
388   gst_rtp_buffer_map (out, GST_MAP_READWRITE, &rtpbuffer);
389   p = gst_rtp_buffer_get_payload (&rtpbuffer);
390   p[0] = 0x0;
391
392   if (self->picture_id_mode != VP9_PAY_NO_PICTURE_ID) {
393     p[0] |= 0x80;
394     if (self->picture_id_mode == VP9_PAY_PICTURE_ID_7BITS) {
395       /* M=0 */
396       p[off++] = self->picture_id & 0x7F;
397     } else {
398       /* M=1 */
399       p[off++] = 0x80 | ((self->picture_id & 0x7FFF) >> 8);
400       p[off++] = self->picture_id & 0xFF;
401     }
402   }
403
404   if (!self->is_keyframe)
405     p[0] |= 0x40;
406   if (start)
407     p[0] |= 0x08;
408   if (mark)
409     p[0] |= 0x04;
410
411   if (self->is_keyframe && start) {
412     p[0] |= 0x02;
413     /* scalability structure, hard coded for now to be similar to chromium for
414      * quick and dirty interop */
415     p[off++] = 0x18;            /* N_S=0 Y=1 G=1 */
416     p[off++] = self->width >> 8;
417     p[off++] = self->width & 0xFF;
418     p[off++] = self->height >> 8;
419     p[off++] = self->height & 0xFF;
420     p[off++] = 0x01;            /* N_G=1 */
421     p[off++] = 0x04;            /* T=0, U=0, R=1 */
422     p[off++] = 0x01;            /* P_DIFF=1 */
423   }
424
425   g_assert_cmpint (off, ==, hdrlen);
426
427   gst_rtp_buffer_set_marker (&rtpbuffer, mark);
428
429   gst_rtp_buffer_unmap (&rtpbuffer);
430
431   GST_BUFFER_DURATION (out) = GST_BUFFER_DURATION (in);
432   GST_BUFFER_PTS (out) = GST_BUFFER_PTS (in);
433
434   return out;
435 }
436
437 static guint
438 gst_rtp_vp9_payload_next (GstRtpVP9Pay * self, GstBufferList * list,
439     guint offset, GstBuffer * buffer, gsize buffer_size, gsize max_payload_len)
440 {
441   GstBuffer *header;
442   GstBuffer *sub;
443   GstBuffer *out;
444   gboolean mark;
445   gsize remaining;
446   gsize available;
447
448   remaining = buffer_size - offset;
449   available = max_payload_len;
450   if (available > remaining)
451     available = remaining;
452
453   mark = (remaining == available);
454   header = gst_rtp_vp9_create_header_buffer (self, offset == 0, mark, buffer);
455   sub = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset, available);
456
457   gst_rtp_copy_video_meta (self, header, buffer);
458
459   out = gst_buffer_append (header, sub);
460
461   gst_buffer_list_insert (list, -1, out);
462
463   return available;
464 }
465
466
467 static GstFlowReturn
468 gst_rtp_vp9_pay_handle_buffer (GstRTPBasePayload * payload, GstBuffer * buffer)
469 {
470   GstRtpVP9Pay *self = GST_RTP_VP9_PAY (payload);
471   GstFlowReturn ret;
472   GstBufferList *list;
473   gsize size, max_paylen;
474   guint offset, mtu, vp9_hdr_len;
475
476   size = gst_buffer_get_size (buffer);
477
478   if (G_UNLIKELY (!gst_rtp_vp9_pay_parse_frame (self, buffer, size))) {
479     GST_ELEMENT_ERROR (self, STREAM, ENCODE, (NULL),
480         ("Failed to parse VP9 frame"));
481     return GST_FLOW_ERROR;
482   }
483
484   mtu = GST_RTP_BASE_PAYLOAD_MTU (payload);
485   vp9_hdr_len = gst_rtp_vp9_calc_header_len (self, TRUE);
486   max_paylen = gst_rtp_buffer_calc_payload_len (mtu - vp9_hdr_len, 0, 0);
487
488   list = gst_buffer_list_new_sized ((size / max_paylen) + 1);
489
490   offset = 0;
491   while (offset < size) {
492     offset +=
493         gst_rtp_vp9_payload_next (self, list, offset, buffer, size, max_paylen);
494   }
495
496   ret = gst_rtp_base_payload_push_list (payload, list);
497
498   /* Incremenent and wrap the picture id if it overflows */
499   if ((self->picture_id_mode == VP9_PAY_PICTURE_ID_7BITS &&
500           ++self->picture_id >= 0x80) ||
501       (self->picture_id_mode == VP9_PAY_PICTURE_ID_15BITS &&
502           ++self->picture_id >= 0x8000))
503     self->picture_id = 0;
504
505   gst_buffer_unref (buffer);
506
507   return ret;
508 }
509
510 static gboolean
511 gst_rtp_vp9_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
512 {
513   GstRtpVP9Pay *self = GST_RTP_VP9_PAY (payload);
514
515   if (GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_START) {
516     if (self->picture_id_mode == VP9_PAY_PICTURE_ID_7BITS)
517       self->picture_id = g_random_int_range (0, G_MAXUINT8) & 0x7F;
518     else if (self->picture_id_mode == VP9_PAY_PICTURE_ID_15BITS)
519       self->picture_id = g_random_int_range (0, G_MAXUINT16) & 0x7FFF;
520   }
521
522   return GST_RTP_BASE_PAYLOAD_CLASS (gst_rtp_vp9_pay_parent_class)->sink_event
523       (payload, event);
524 }
525
526 static gboolean
527 gst_rtp_vp9_pay_set_caps (GstRTPBasePayload * payload, GstCaps * caps)
528 {
529   GstCaps *src_caps;
530   const char *encoding_name = "VP9";
531
532   src_caps = gst_pad_get_allowed_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload));
533   if (src_caps) {
534     GstStructure *s;
535     const GValue *value;
536
537     s = gst_caps_get_structure (src_caps, 0);
538
539     if (gst_structure_has_field (s, "encoding-name")) {
540       GValue default_value = G_VALUE_INIT;
541
542       g_value_init (&default_value, G_TYPE_STRING);
543       g_value_set_static_string (&default_value, encoding_name);
544
545       value = gst_structure_get_value (s, "encoding-name");
546       if (!gst_value_can_intersect (&default_value, value))
547         encoding_name = "VP9-DRAFT-IETF-01";
548     }
549   }
550
551   gst_rtp_base_payload_set_options (payload, "video", TRUE,
552       encoding_name, 90000);
553
554   return gst_rtp_base_payload_set_outcaps (payload, NULL);
555 }
556
557 gboolean
558 gst_rtp_vp9_pay_plugin_init (GstPlugin * plugin)
559 {
560   return gst_element_register (plugin, "rtpvp9pay",
561       GST_RANK_MARGINAL, GST_TYPE_RTP_VP9_PAY);
562 }