rtph261pay: fix indentation
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtph261pay.c
1 /* GStreamer
2  * Copyright (C) <2014> Stian Selnes <stian@pexip.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
21 /**
22  * SECTION:element-rtph261pay
23  * @see_also: rtph261depay
24  *
25  * Payload encoded H.261 video frames into RTP packets according to RFC 4587.
26  * For detailed information see: https://www.rfc-editor.org/rfc/rfc4587.txt
27  *
28  * The payloader takes a H.261 frame, parses it and splits it into fragments
29  * on MB boundaries in order to match configured MTU size. For each fragment
30  * an RTP packet is constructed with an RTP packet header followed by the
31  * fragment. In addition the payloader will make sure the packetized H.261
32  * stream appears as a continuous bit-stream after depacketization by shifting
33  * the encoded bit-stream of a frame to align with the last significant bit of
34  * the previous frame. This helps interoperability in the case where the
35  * encoder does not produce a continuous bit-stream but the decoder requires
36  * it.
37  *
38  * <refsect2>
39  * <title>Example launch line</title>
40  * |[
41  * gst-launch-1.0 videotestsrc ! avenc_h261 ! rtph261pay ! udpsink
42  * ]| This will encode a test video and payload it. Refer to the rtph261depay
43  * example to depayload and play the RTP stream.
44  * </refsect2>
45  */
46
47 #ifdef HAVE_CONFIG_H
48 #  include "config.h"
49 #endif
50
51 #include "gstrtph261pay.h"
52 #include <gst/rtp/gstrtpbuffer.h>
53 #include <gst/base/gstbitreader.h>
54 #include <string.h>
55
56 GST_DEBUG_CATEGORY_STATIC (rtph261pay_debug);
57 #define GST_CAT_DEFAULT (rtph261pay_debug)
58
59 #define GST_RTP_HEADER_LEN 12
60 #define GST_RTP_H261_PAYLOAD_HEADER_LEN 4
61
62 static GstStaticPadTemplate gst_rtp_h261_pay_sink_template =
63 GST_STATIC_PAD_TEMPLATE ("sink",
64     GST_PAD_SINK,
65     GST_PAD_ALWAYS,
66     GST_STATIC_CAPS ("video/x-h261")
67     );
68
69 static GstStaticPadTemplate gst_rtp_h261_pay_src_template =
70     GST_STATIC_PAD_TEMPLATE ("src",
71     GST_PAD_SRC,
72     GST_PAD_ALWAYS,
73     GST_STATIC_CAPS ("application/x-rtp, "
74         "media = (string) \"video\", "
75         "payload = (int) " GST_RTP_PAYLOAD_H261_STRING ", "
76         "clock-rate = (int) 90000, " "encoding-name = (string) \"H261\"; "
77         "application/x-rtp, "
78         "media = (string) \"video\", "
79         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
80         "clock-rate = (int) 90000, " "encoding-name = (string) \"H261\"")
81     );
82
83 G_DEFINE_TYPE (GstRtpH261Pay, gst_rtp_h261_pay, GST_TYPE_RTP_BASE_PAYLOAD);
84 #define parent_class gst_rtp_h261_pay_parent_class
85
86 typedef struct
87 {
88   guint32 mba;
89   guint32 mtype;
90   guint32 quant;
91   gint mvx;
92   gint mvy;
93   guint endpos;
94   gint gobn;
95 } Macroblock;
96
97 typedef struct
98 {
99   Macroblock last;
100   guint startpos;
101   guint endpos;
102   guint32 gn;
103   guint32 gquant;
104 } Gob;
105
106 #define PSC_LEN 20
107 #define TR_LEN 5
108 #define PTYPE_LEN 6
109 #define GBSC_LEN 16
110 #define GN_LEN 4
111 #define GQUANT_LEN 5
112 #define GEI_LEN 1
113 #define GSPARE_LEN 8
114 #define MQUANT_LEN 5
115 #define MAX_NUM_GOB 12
116
117 typedef enum
118 {
119   PARSE_END_OF_BUFFER = -2,
120   PARSE_ERROR = -1,
121   PARSE_OK = 0,
122   PARSE_END_OF_FRAME,
123   PARSE_END_OF_GOB,
124 } ParseReturn;
125
126
127 #define SKIP_BITS(br,nbits) G_STMT_START {      \
128     if (!gst_bit_reader_skip (br, nbits))       \
129       return PARSE_END_OF_BUFFER;               \
130   } G_STMT_END
131
132 #define GET_BITS(br,val,nbits) G_STMT_START {             \
133     if (!gst_bit_reader_get_bits_uint32 (br, val, nbits)) \
134       return PARSE_END_OF_BUFFER;                         \
135   } G_STMT_END
136
137 /* Unchecked since we peek outside the buffer. Ok because of padding. */
138 #define PEEK_BITS(br,val,nbits) G_STMT_START {                    \
139     *val = gst_bit_reader_peek_bits_uint16_unchecked (br, nbits); \
140   } G_STMT_END
141
142
143 #define MBA_STUFFING 34
144 #define MBA_START_CODE 35
145 #define MBA_LEN 35
146 #define MBA_WID 4
147 /* [code, mask, nbits, mba] */
148 static const guint16 mba_table[MBA_LEN][MBA_WID] = {
149   {0x8000, 0x8000, 1, 1},
150   {0x6000, 0xe000, 3, 2},
151   {0x4000, 0xe000, 3, 3},
152   {0x3000, 0xf000, 4, 4},
153   {0x2000, 0xf000, 4, 5},
154   {0x1800, 0xf800, 5, 6},
155   {0x1000, 0xf800, 5, 7},
156   {0x0e00, 0xfe00, 7, 8},
157   {0x0c00, 0xfe00, 7, 9},
158   {0x0b00, 0xff00, 8, 10},
159   {0x0a00, 0xff00, 8, 11},
160   {0x0900, 0xff00, 8, 12},
161   {0x0800, 0xff00, 8, 13},
162   {0x0700, 0xff00, 8, 14},
163   {0x0600, 0xff00, 8, 15},
164   {0x05c0, 0xffc0, 10, 16},
165   {0x0580, 0xffc0, 10, 17},
166   {0x0540, 0xffc0, 10, 18},
167   {0x0500, 0xffc0, 10, 19},
168   {0x04c0, 0xffc0, 10, 20},
169   {0x0480, 0xffc0, 10, 21},
170   {0x0460, 0xffe0, 11, 22},
171   {0x0440, 0xffe0, 11, 23},
172   {0x0420, 0xffe0, 11, 24},
173   {0x0400, 0xffe0, 11, 25},
174   {0x03e0, 0xffe0, 11, 26},
175   {0x03c0, 0xffe0, 11, 27},
176   {0x03a0, 0xffe0, 11, 28},
177   {0x0380, 0xffe0, 11, 29},
178   {0x0360, 0xffe0, 11, 30},
179   {0x0340, 0xffe0, 11, 31},
180   {0x0320, 0xffe0, 11, 32},
181   {0x0300, 0xffe0, 11, 33},
182   {0x01e0, 0xffe0, 11, MBA_STUFFING},
183   {0x0001, 0xffff, 16, MBA_START_CODE},
184 };
185
186 #define MTYPE_INTRA    (1 << 0)
187 #define MTYPE_INTER    (1 << 1)
188 #define MTYPE_MC       (1 << 2)
189 #define MTYPE_FIL      (1 << 3)
190 #define MTYPE_MQUANT   (1 << 4)
191 #define MTYPE_MVD      (1 << 5)
192 #define MTYPE_CBP      (1 << 6)
193 #define MTYPE_TCOEFF   (1 << 7)
194 #define MTYPE_LEN 10
195 #define MTYPE_WID 4
196 /* [code, mask, nbits, flags] */
197 static const guint16 mtype_table[MTYPE_LEN][MTYPE_WID] = {
198   {0x8000, 0x8000, 1, MTYPE_INTER | MTYPE_CBP | MTYPE_TCOEFF},
199   {0x4000, 0xc000, 2,
200       MTYPE_INTER | MTYPE_MC | MTYPE_FIL | MTYPE_MVD | MTYPE_CBP |
201         MTYPE_TCOEFF},
202   {0x2000, 0xe000, 3, MTYPE_INTER | MTYPE_MC | MTYPE_FIL | MTYPE_MVD},
203   {0x1000, 0xf000, 4, MTYPE_INTRA | MTYPE_TCOEFF},
204   {0x0800, 0xf800, 5, MTYPE_INTER | MTYPE_MQUANT | MTYPE_CBP | MTYPE_TCOEFF},
205   {0x0400, 0xfc00, 6,
206       MTYPE_INTER | MTYPE_MC | MTYPE_FIL | MTYPE_MQUANT | MTYPE_MVD |
207         MTYPE_CBP | MTYPE_TCOEFF},
208   {0x0200, 0xfe00, 7, MTYPE_INTRA | MTYPE_MQUANT | MTYPE_TCOEFF},
209   {0x0100, 0xff00, 8,
210       MTYPE_INTER | MTYPE_MC | MTYPE_MVD | MTYPE_CBP | MTYPE_TCOEFF},
211   {0x0080, 0xff80, 9, MTYPE_INTER | MTYPE_MC | MTYPE_MVD},
212   {0x0040, 0xffc0, 10,
213       MTYPE_INTER | MTYPE_MC | MTYPE_MQUANT | MTYPE_MVD | MTYPE_CBP |
214         MTYPE_TCOEFF},
215 };
216
217 #define MVD_LEN 32
218 #define MVD_WID 5
219 /* [code, mask, nbits, mvd1, mvd2] */
220 static const guint16 mvd_table[MVD_LEN][MVD_WID] = {
221   {0x8000, 0x8000, 1, 0, 0},
222   {0x6000, 0xe000, 3, -1, -1},
223   {0x4000, 0xe000, 3, 1, 1},
224   {0x3000, 0xf000, 4, -2, 30},
225   {0x2000, 0xf000, 4, 2, -30},
226   {0x1800, 0xf800, 5, -3, 29},
227   {0x1000, 0xf800, 5, 3, -29},
228   {0x0e00, 0xfe00, 7, -4, 28},
229   {0x0c00, 0xfe00, 7, 4, -28},
230   {0x0700, 0xff00, 8, -7, 25},
231   {0x0900, 0xff00, 8, -6, 26},
232   {0x0b00, 0xff00, 8, -5, 27},
233   {0x0a00, 0xff00, 8, 5, -27},
234   {0x0800, 0xff00, 8, 6, -26},
235   {0x0600, 0xff00, 8, 7, -25},
236   {0x04c0, 0xffc0, 10, -10, 22},
237   {0x0540, 0xffc0, 10, -9, 23},
238   {0x05c0, 0xffc0, 10, -8, 24},
239   {0x0580, 0xffc0, 10, 8, -24},
240   {0x0500, 0xffc0, 10, 9, -23},
241   {0x0480, 0xffc0, 10, 10, -22},
242   {0x0320, 0xffe0, 11, -16, 16},
243   {0x0360, 0xffe0, 11, -15, 17},
244   {0x03a0, 0xffe0, 11, -14, 18},
245   {0x03e0, 0xffe0, 11, -13, 19},
246   {0x0420, 0xffe0, 11, -12, 20},
247   {0x0460, 0xffe0, 11, -11, 21},
248   {0x0440, 0xffe0, 11, 11, -21},
249   {0x0400, 0xffe0, 11, 12, -20},
250   {0x03c0, 0xffe0, 11, 13, -19},
251   {0x0380, 0xffe0, 11, 14, -18},
252   {0x0340, 0xffe0, 11, 15, -17},
253 };
254
255 #define CBP_LEN 63
256 /* [code, mask, nbits, cbp] */
257 static const guint16 cbp_table[CBP_LEN][4] = {
258   {0xe000, 0xe000, 3, 60},
259   {0xd000, 0xf000, 4, 4},
260   {0xc000, 0xf000, 4, 8},
261   {0xb000, 0xf000, 4, 16},
262   {0xa000, 0xf000, 4, 32},
263   {0x9800, 0xf800, 5, 12},
264   {0x9000, 0xf800, 5, 48},
265   {0x8800, 0xf800, 5, 20},
266   {0x8000, 0xf800, 5, 40},
267   {0x7800, 0xf800, 5, 28},
268   {0x7000, 0xf800, 5, 44},
269   {0x6800, 0xf800, 5, 52},
270   {0x6000, 0xf800, 5, 56},
271   {0x5800, 0xf800, 5, 1},
272   {0x5000, 0xf800, 5, 61},
273   {0x4800, 0xf800, 5, 2},
274   {0x4000, 0xf800, 5, 62},
275   {0x3c00, 0xfc00, 6, 24},
276   {0x3800, 0xfc00, 6, 36},
277   {0x3400, 0xfc00, 6, 3},
278   {0x3000, 0xfc00, 6, 63},
279   {0x2e00, 0xfe00, 7, 5},
280   {0x2c00, 0xfe00, 7, 9},
281   {0x2a00, 0xfe00, 7, 17},
282   {0x2800, 0xfe00, 7, 33},
283   {0x2600, 0xfe00, 7, 6},
284   {0x2400, 0xfe00, 7, 10},
285   {0x2200, 0xfe00, 7, 18},
286   {0x2000, 0xfe00, 7, 34},
287   {0x1f00, 0xff00, 8, 7},
288   {0x1e00, 0xff00, 8, 11},
289   {0x1d00, 0xff00, 8, 19},
290   {0x1c00, 0xff00, 8, 35},
291   {0x1b00, 0xff00, 8, 13},
292   {0x1a00, 0xff00, 8, 49},
293   {0x1900, 0xff00, 8, 21},
294   {0x1800, 0xff00, 8, 41},
295   {0x1700, 0xff00, 8, 14},
296   {0x1600, 0xff00, 8, 50},
297   {0x1500, 0xff00, 8, 22},
298   {0x1400, 0xff00, 8, 42},
299   {0x1300, 0xff00, 8, 15},
300   {0x1200, 0xff00, 8, 51},
301   {0x1100, 0xff00, 8, 23},
302   {0x1000, 0xff00, 8, 43},
303   {0x0f00, 0xff00, 8, 25},
304   {0x0e00, 0xff00, 8, 37},
305   {0x0d00, 0xff00, 8, 26},
306   {0x0c00, 0xff00, 8, 38},
307   {0x0b00, 0xff00, 8, 29},
308   {0x0a00, 0xff00, 8, 45},
309   {0x0900, 0xff00, 8, 53},
310   {0x0800, 0xff00, 8, 57},
311   {0x0700, 0xff00, 8, 30},
312   {0x0600, 0xff00, 8, 46},
313   {0x0500, 0xff00, 8, 54},
314   {0x0400, 0xff00, 8, 58},
315   {0x0380, 0xff80, 9, 31},
316   {0x0300, 0xff80, 9, 47},
317   {0x0280, 0xff80, 9, 55},
318   {0x0200, 0xff80, 9, 59},
319   {0x0180, 0xff80, 9, 27},
320   {0x0100, 0xff80, 9, 39},
321 };
322
323 #define TCOEFF_EOB 0xffff
324 #define TCOEFF_ESC 0xfffe
325 #define TCOEFF_LEN 65
326 /* [code, mask, nbits, run, level] */
327 static const guint16 tcoeff_table[TCOEFF_LEN][5] = {
328   {0x8000, 0xc000, 2, TCOEFF_EOB, 0},   /* Not available for first coeff */
329   /* {0x8000, 0x8000,  2,  0,  1}, *//* Available only for first Inter coeff */
330   {0xc000, 0xc000, 3, 0, 1},    /* Not available for first coeff */
331   {0x6000, 0xe000, 4, 1, 1},
332   {0x4000, 0xf000, 5, 0, 2},
333   {0x5000, 0xf000, 5, 2, 1},
334   {0x2800, 0xf800, 6, 0, 3},
335   {0x3800, 0xf800, 6, 3, 1},
336   {0x3000, 0xf800, 6, 4, 1},
337   {0x0400, 0xfc00, 6, TCOEFF_ESC, 0},
338   {0x1800, 0xfc00, 7, 1, 2},
339   {0x1c00, 0xfc00, 7, 5, 1},
340   {0x1400, 0xfc00, 7, 6, 1},
341   {0x1000, 0xfc00, 7, 7, 1},
342   {0x0c00, 0xfe00, 8, 0, 4},
343   {0x0800, 0xfe00, 8, 2, 2},
344   {0x0e00, 0xfe00, 8, 8, 1},
345   {0x0a00, 0xfe00, 8, 9, 1},
346   {0x2600, 0xff00, 9, 0, 5},
347   {0x2100, 0xff00, 9, 0, 6},
348   {0x2500, 0xff00, 9, 1, 3},
349   {0x2400, 0xff00, 9, 3, 2},
350   {0x2700, 0xff00, 9, 10, 1},
351   {0x2300, 0xff00, 9, 11, 1},
352   {0x2200, 0xff00, 9, 12, 1},
353   {0x2000, 0xff00, 9, 13, 1},
354   {0x0280, 0xffc0, 11, 0, 7},
355   {0x0300, 0xffc0, 11, 1, 4},
356   {0x02c0, 0xffc0, 11, 2, 3},
357   {0x03c0, 0xffc0, 11, 4, 2},
358   {0x0240, 0xffc0, 11, 5, 2},
359   {0x0380, 0xffc0, 11, 14, 1},
360   {0x0340, 0xffc0, 11, 15, 1},
361   {0x0200, 0xffc0, 11, 16, 1},
362   {0x01d0, 0xfff0, 13, 0, 8},
363   {0x0180, 0xfff0, 13, 0, 9},
364   {0x0130, 0xfff0, 13, 0, 10},
365   {0x0100, 0xfff0, 13, 0, 11},
366   {0x01b0, 0xfff0, 13, 1, 5},
367   {0x0140, 0xfff0, 13, 2, 4},
368   {0x01c0, 0xfff0, 13, 3, 3},
369   {0x0120, 0xfff0, 13, 4, 3},
370   {0x01e0, 0xfff0, 13, 6, 2},
371   {0x0150, 0xfff0, 13, 7, 2},
372   {0x0110, 0xfff0, 13, 8, 2},
373   {0x01f0, 0xfff0, 13, 17, 1},
374   {0x01a0, 0xfff0, 13, 18, 1},
375   {0x0190, 0xfff0, 13, 19, 1},
376   {0x0170, 0xfff0, 13, 20, 1},
377   {0x0160, 0xfff0, 13, 21, 1},
378   {0x00d0, 0xfff8, 14, 0, 12},
379   {0x00c8, 0xfff8, 14, 0, 13},
380   {0x00c0, 0xfff8, 14, 0, 14},
381   {0x00b8, 0xfff8, 14, 0, 15},
382   {0x00b0, 0xfff8, 14, 1, 6},
383   {0x00a8, 0xfff8, 14, 1, 7},
384   {0x00a0, 0xfff8, 14, 2, 5},
385   {0x0098, 0xfff8, 14, 3, 4},
386   {0x0090, 0xfff8, 14, 5, 3},
387   {0x0088, 0xfff8, 14, 9, 2},
388   {0x0080, 0xfff8, 14, 10, 2},
389   {0x00f8, 0xfff8, 14, 22, 1},
390   {0x00f0, 0xfff8, 14, 23, 1},
391   {0x00e8, 0xfff8, 14, 24, 1},
392   {0x00e0, 0xfff8, 14, 25, 1},
393   {0x00d8, 0xfff8, 14, 26, 1},
394 };
395
396 static ParseReturn
397 decode_mba (GstBitReader * br, gint * mba)
398 {
399   gint i;
400   guint16 code;
401
402   *mba = -1;
403   do {
404     PEEK_BITS (br, &code, 16);
405     for (i = 0; i < MBA_LEN; i++) {
406       if ((code & mba_table[i][1]) == mba_table[i][0]) {
407         *mba = mba_table[i][3];
408
409         if (*mba == MBA_START_CODE)
410           return PARSE_END_OF_GOB;
411         SKIP_BITS (br, mba_table[i][2]);
412         if (*mba != MBA_STUFFING)
413           return PARSE_OK;
414       }
415     }
416   } while (*mba == MBA_STUFFING);
417
418   /* 0x0 indicates end of frame since we appended 0-bytes */
419   if (code == 0x0)
420     return PARSE_END_OF_FRAME;
421
422   return PARSE_ERROR;
423 }
424
425 static ParseReturn
426 decode_mtype (GstBitReader * br, guint * mtype)
427 {
428   gint i;
429   guint16 code;
430
431   PEEK_BITS (br, &code, 16);
432   for (i = 0; i < MTYPE_LEN; i++) {
433     if ((code & mtype_table[i][1]) == mtype_table[i][0]) {
434       SKIP_BITS (br, mtype_table[i][2]);
435       *mtype = mtype_table[i][3];
436       return PARSE_OK;
437     }
438   }
439
440   return PARSE_ERROR;
441 }
442
443 static ParseReturn
444 decode_mvd (GstBitReader * br, gint * mvd1, gint * mvd2)
445 {
446   gint i;
447   guint16 code;
448
449   PEEK_BITS (br, &code, 16);
450   for (i = 0; i < MVD_LEN; i++) {
451     if ((code & mvd_table[i][1]) == mvd_table[i][0]) {
452       SKIP_BITS (br, mvd_table[i][2]);
453       *mvd1 = (gint16) mvd_table[i][3];
454       *mvd2 = (gint16) mvd_table[i][4];
455       return PARSE_OK;
456     }
457   }
458
459   return PARSE_ERROR;
460 }
461
462 static ParseReturn
463 decode_cbp (GstBitReader * br, guint * cbp)
464 {
465   gint i;
466   guint16 code;
467
468   PEEK_BITS (br, &code, 16);
469   for (i = 0; i < CBP_LEN; i++) {
470     if ((code & cbp_table[i][1]) == cbp_table[i][0]) {
471       SKIP_BITS (br, cbp_table[i][2]);
472       *cbp = cbp_table[i][3];
473       return PARSE_OK;
474     }
475   }
476
477   return PARSE_ERROR;
478 }
479
480 static ParseReturn
481 decode_tcoeff (GstBitReader * br, guint mtype)
482 {
483   gint i;
484   guint16 code;
485   gboolean eob;
486
487   /* Special handling of first coeff */
488   if (mtype & MTYPE_INTER) {
489     /* Inter, different vlc since EOB is not allowed */
490     PEEK_BITS (br, &code, 16);
491     if (code & 0x8000) {
492       SKIP_BITS (br, 2);
493       GST_TRACE ("tcoeff first inter special");
494     } else {
495       /* Fallthrough. Let the first coeff be handled like other coeffs since
496        * the vlc is the same as long as the first bit is not set. */
497     }
498   } else {
499     /* Intra, first coeff is fixed 8-bit */
500     GST_TRACE ("tcoeff first intra special");
501     SKIP_BITS (br, 8);
502   }
503
504   /* Block must end with EOB. */
505   eob = FALSE;
506   while (!eob) {
507     PEEK_BITS (br, &code, 16);
508     for (i = 0; i < TCOEFF_LEN; i++) {
509       if ((code & tcoeff_table[i][1]) == tcoeff_table[i][0]) {
510         GST_TRACE ("tcoeff vlc[%d], run=%d, level=%d", i, tcoeff_table[i][3],
511             tcoeff_table[i][4]);
512         SKIP_BITS (br, tcoeff_table[i][2]);
513         if (tcoeff_table[i][3] == TCOEFF_EOB) {
514           eob = TRUE;
515         } else if (tcoeff_table[i][3] == TCOEFF_ESC) {
516 #if 0
517           guint16 val;
518           val = gst_bit_reader_peek_bits_uint16_unchecked (br, 6 + 8);
519           GST_TRACE ("esc run=%d, level=%d", val >> 8, (gint8) (val & 0xff));
520 #endif
521           SKIP_BITS (br, 6 + 8);
522         }
523         break;
524       }
525     }
526     if (i == TCOEFF_LEN)
527       /* No matching VLC */
528       return PARSE_ERROR;
529   }
530
531   return PARSE_OK;
532 }
533
534 static gint
535 find_picture_header_offset (const guint8 * data, gsize size)
536 {
537   gint i;
538   guint32 val;
539
540   if (size < 4)
541     return -1;
542
543   val = GST_READ_UINT32_BE (data);
544   for (i = 0; i < 8; i++) {
545     if ((val >> (12 - i)) == 0x10)
546       return i;
547   }
548
549   return -1;
550 }
551
552 static ParseReturn
553 parse_picture_header (GstRtpH261Pay * pay, GstBitReader * br, gint * num_gob)
554 {
555   guint32 val;
556
557   GET_BITS (br, &val, PSC_LEN);
558   if (val != 0x10)
559     return PARSE_ERROR;
560   SKIP_BITS (br, TR_LEN);
561   GET_BITS (br, &val, PTYPE_LEN);
562   *num_gob = (val & 0x04) == 0 ? 3 : 12;
563
564   return PARSE_OK;
565 }
566
567 static ParseReturn
568 parse_gob_header (GstRtpH261Pay * pay, GstBitReader * br, Gob * gob)
569 {
570   guint32 val;
571
572   GET_BITS (br, &val, GBSC_LEN);
573   if (val != 0x01)
574     return PARSE_ERROR;
575   GET_BITS (br, &gob->gn, GN_LEN);
576   GST_TRACE_OBJECT (pay, "Parsing GOB %d", gob->gn);
577
578   GET_BITS (br, &gob->gquant, GQUANT_LEN);
579   GST_TRACE_OBJECT (pay, "GQUANT %d", gob->gquant);
580   GET_BITS (br, &val, GEI_LEN);
581   while (val != 0) {
582     SKIP_BITS (br, GSPARE_LEN);
583     GET_BITS (br, &val, GEI_LEN);
584   }
585
586   return PARSE_OK;
587 }
588
589 static ParseReturn
590 parse_mb (GstRtpH261Pay * pay, GstBitReader * br, const Macroblock * prev,
591     Macroblock * mb)
592 {
593   gint mba_diff;
594   guint cbp;
595   ParseReturn ret;
596
597   cbp = 0x3f;
598   mb->quant = prev->quant;
599
600   if ((ret = decode_mba (br, &mba_diff)) != PARSE_OK)
601     return ret;
602   mb->mba = prev->mba == 0 ? mba_diff : prev->mba + mba_diff;
603   GST_TRACE_OBJECT (pay, "Parse MBA %d (mba_diff %d)", mb->mba, mba_diff);
604
605   if ((ret = decode_mtype (br, &mb->mtype)) != PARSE_OK)
606     return ret;
607   GST_TRACE_OBJECT (pay,
608       "MTYPE: inter %d, mc %d, fil %d, mquant %d, mvd %d, cbp %d, tcoeff %d",
609       (mb->mtype & MTYPE_INTER) != 0, (mb->mtype & MTYPE_MC) != 0,
610       (mb->mtype & MTYPE_FIL) != 0, (mb->mtype & MTYPE_MQUANT) != 0,
611       (mb->mtype & MTYPE_MVD) != 0, (mb->mtype & MTYPE_CBP) != 0,
612       (mb->mtype & MTYPE_TCOEFF) != 0);
613
614   if (mb->mtype & MTYPE_MQUANT) {
615     GET_BITS (br, &mb->quant, MQUANT_LEN);
616     GST_TRACE_OBJECT (pay, "MQUANT: %d", mb->quant);
617   }
618
619   if (mb->mtype & MTYPE_MVD) {
620     gint i, pmv[2], mv[2];
621
622     if (mb->mba == 1 || mb->mba == 12 || mb->mba == 23 || mba_diff != 1 ||
623         (prev->mtype & MTYPE_INTER) == 0) {
624       pmv[0] = 0;
625       pmv[1] = 0;
626     } else {
627       pmv[0] = prev->mvx;
628       pmv[1] = prev->mvy;
629     }
630     for (i = 0; i < 2; i++) {
631       gint mvd1, mvd2;
632       if ((ret = decode_mvd (br, &mvd1, &mvd2)) != PARSE_OK)
633         return ret;
634       if (ABS (pmv[i] + mvd1) <= 15)
635         mv[i] = pmv[i] + mvd1;
636       else
637         mv[i] = pmv[i] + mvd2;
638     }
639     mb->mvx = mv[0];
640     mb->mvy = mv[1];
641   } else {
642     mb->mvx = 0;
643     mb->mvy = 0;
644   }
645
646   if (mb->mtype & MTYPE_CBP) {
647     if ((ret = decode_cbp (br, &cbp)) != PARSE_OK)
648       return ret;
649   }
650
651   /* Block layer */
652   if (mb->mtype & MTYPE_TCOEFF) {
653     gint block;
654     for (block = 0; block < 6; block++) {
655       if (cbp & (1 << (5 - block))) {
656         GST_TRACE_OBJECT (pay, "Decode TCOEFF for block %d", block);
657         if ((ret = decode_tcoeff (br, mb->mtype)) != PARSE_OK)
658           return ret;
659       }
660     }
661   }
662
663   mb->endpos = gst_bit_reader_get_pos (br);
664
665   return ret;
666 }
667
668 /* Parse macroblocks until the next MB that exceeds maxpos. At least one MB is
669  * included even if it exceeds maxpos. Returns endpos of last included MB. */
670 static ParseReturn
671 parse_mb_until_pos (GstRtpH261Pay * pay, GstBitReader * br, Gob * gob,
672     guint * endpos)
673 {
674   ParseReturn ret;
675   gint count = 0;
676   gboolean stop = FALSE;
677   guint maxpos = *endpos;
678   Macroblock mb;
679
680   GST_LOG_OBJECT (pay, "Parse until pos %u, start at pos %u, gobn %d, mba %d",
681       maxpos, gst_bit_reader_get_pos (br), gob->gn, gob->last.mba);
682
683   while (!stop) {
684     ret = parse_mb (pay, br, &gob->last, &mb);
685
686     switch (ret) {
687       case PARSE_OK:
688         if (mb.endpos > maxpos && count > 0) {
689           /* Don't include current MB */
690           stop = TRUE;
691         } else {
692           /* Update to include current MB */
693           *endpos = mb.endpos;
694           gob->last = mb;
695           count++;
696         }
697         break;
698
699       case PARSE_END_OF_FRAME:
700         *endpos = gst_bit_reader_get_pos (br);
701         GST_DEBUG_OBJECT (pay, "End of frame at pos %u (last GOBN %d MBA %d)",
702             *endpos, gob->gn, gob->last.mba);
703         stop = TRUE;
704         break;
705
706       case PARSE_END_OF_GOB:
707         /* Note that a GOB can contain nothing, so we may get here on the first
708          * iteration. */
709         *endpos = gob->last.mba == 0 ?
710             gob->startpos : gst_bit_reader_get_pos (br);
711         GST_DEBUG_OBJECT (pay, "End of gob at pos %u (last GOBN %d MBA %d)",
712             *endpos, gob->gn, gob->last.mba);
713         stop = TRUE;
714         break;
715
716       case PARSE_END_OF_BUFFER:
717       case PARSE_ERROR:
718         GST_WARNING_OBJECT (pay, "Failed to parse stream (reason %d)", ret);
719         return ret;
720         break;
721
722       default:
723         g_assert_not_reached ();
724         break;
725     }
726   }
727   gob->last.gobn = gob->gn;
728
729   if (ret == PARSE_OK) {
730     GST_DEBUG_OBJECT (pay,
731         "Split GOBN %d after MBA %d (endpos %u, maxpos %u, nextpos %u)",
732         gob->gn, gob->last.mba, *endpos, maxpos, mb.endpos);
733     gst_bit_reader_set_pos (br, *endpos);
734   }
735
736   return ret;
737 }
738
739 static guint
740 bitrange_to_bytes (guint first, guint last)
741 {
742   return (GST_ROUND_UP_8 (last) - GST_ROUND_DOWN_8 (first)) / 8;
743 }
744
745 /* Find next 16-bit GOB start code (0x0001), which may not be byte aligned.
746  * Returns the bit offset of the first bit of GBSC. */
747 static gssize
748 find_gob (GstRtpH261Pay * pay, const guint8 * data, guint size, guint pos)
749 {
750   gssize ret = -1;
751   guint offset;
752
753   GST_LOG_OBJECT (pay, "Search for GOB from pos %u", pos);
754
755   for (offset = pos / 8; offset < size - 1; offset++) {
756     if (data[offset] == 0x0) {
757       gint msb = g_bit_nth_msf (data[offset + 1], 8);
758       gint lsb = offset > 0 ? g_bit_nth_lsf (data[offset - 1], -1) : 0;
759       if (lsb == -1)
760         lsb = 8;
761       if (msb >= 0 && lsb >= msb) {
762         ret = offset * 8 - msb;
763         GST_LOG_OBJECT (pay, "Found GOB start code at bitpos %"
764             G_GSSIZE_FORMAT " (%02x %02x %02x)", ret,
765             offset > 0 ? data[offset - 1] : 0, data[offset], data[offset + 1]);
766         break;
767       }
768     }
769   }
770
771   return ret;
772 }
773
774 /* Scans after all GOB start codes and initalizes the GOB structure with start
775  * and end positions. */
776 static ParseReturn
777 gst_rtp_h261_pay_init_gobs (GstRtpH261Pay * pay, Gob * gobs, gint num_gobs,
778     const guint8 * bits, gint len, guint pos)
779 {
780   gint i;
781
782   for (i = 0; i < num_gobs; i++) {
783     gssize gobpos = find_gob (pay, bits, len, pos);
784     if (gobpos == -1) {
785       GST_WARNING_OBJECT (pay, "Found only %d of %d GOBs", i, num_gobs);
786       return PARSE_ERROR;
787     }
788     GST_LOG_OBJECT (pay, "Found GOB %d at pos %" G_GSSIZE_FORMAT, i, gobpos);
789     pos = gobpos + GBSC_LEN;
790
791     gobs[i].startpos = gobpos;
792     if (i > 0)
793       gobs[i - 1].endpos = gobpos;
794   }
795   gobs[num_gobs - 1].endpos = len * 8;
796
797   return PARSE_OK;
798 }
799
800 static GstFlowReturn
801 gst_rtp_h261_pay_fragment_push (GstRtpH261Pay * pay, const guint8 * bits,
802     guint start, guint end, const Macroblock * last_mb_in_previous_packet,
803     gboolean marker)
804 {
805   GstBuffer *outbuf;
806   guint8 *payload;
807   GstRtpH261PayHeader *header;
808   gint nbytes;
809   const Macroblock *last = last_mb_in_previous_packet;
810   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
811
812   nbytes = bitrange_to_bytes (start, end);
813
814   outbuf = gst_rtp_buffer_new_allocate (nbytes +
815       GST_RTP_H261_PAYLOAD_HEADER_LEN, 0, 0);
816   gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
817   payload = gst_rtp_buffer_get_payload (&rtp);
818   header = (GstRtpH261PayHeader *) payload;
819
820   memset (header, 0, GST_RTP_H261_PAYLOAD_HEADER_LEN);
821   header->v = 1;
822   header->sbit = start & 7;
823   header->ebit = (8 - (end & 7)) & 7;
824
825   if (last != NULL && last->mba != 0 && last->mba != 33) {
826     /* NOTE: MVD assumes that we're running on 2's complement architecture */
827     guint mbap = last->mba - 1;
828     header->gobn = last->gobn;
829     header->mbap1 = mbap >> 1;
830     header->mbap2 = mbap & 1;
831     header->quant = last->quant;
832     header->hmvd1 = last->mvx >> 3;
833     header->hmvd2 = last->mvx & 7;
834     header->vmvd = last->mvy;
835   }
836
837   memcpy (payload + GST_RTP_H261_PAYLOAD_HEADER_LEN,
838       bits + GST_ROUND_DOWN_8 (start) / 8, nbytes);
839
840   GST_BUFFER_TIMESTAMP (outbuf) = pay->timestamp;
841   gst_rtp_buffer_set_marker (&rtp, marker);
842   pay->offset = end & 7;
843
844   GST_DEBUG_OBJECT (pay,
845       "Push fragment, bytes %d, sbit %d, ebit %d, gobn %d, mbap %d, marker %d",
846       nbytes, header->sbit, header->ebit, last != NULL ? last->gobn : 0,
847       last != NULL ? MAX (last->mba - 1, 0) : 0, marker);
848
849   gst_rtp_buffer_unmap (&rtp);
850
851   return gst_rtp_base_payload_push (GST_RTP_BASE_PAYLOAD_CAST (pay), outbuf);
852 }
853
854 static GstFlowReturn
855 gst_rtp_h261_packetize_and_push (GstRtpH261Pay * pay, const guint8 * bits,
856     gsize len)
857 {
858   GstFlowReturn ret = GST_FLOW_OK;
859   GstBitReader br_;
860   GstBitReader *br = &br_;
861   guint max_payload_size =
862       gst_rtp_buffer_calc_payload_len (GST_RTP_BASE_PAYLOAD_MTU (pay) -
863       GST_RTP_H261_PAYLOAD_HEADER_LEN, 0, 0);
864   guint startpos;
865   gint num_gobs;
866   Gob gobs[MAX_NUM_GOB];
867   Gob *gob;
868   Macroblock last_mb_in_previous_packet = { 0 };
869   gboolean marker;
870   ParseReturn result;
871
872   gst_bit_reader_init (br, bits, len);
873   gst_bit_reader_set_pos (br, pay->offset);
874   startpos = pay->offset;
875
876   if (parse_picture_header (pay, br, &num_gobs) < PARSE_OK) {
877     GST_WARNING_OBJECT (pay, "Failed to parse picture header");
878     goto beach;
879   }
880
881   if (gst_rtp_h261_pay_init_gobs (pay, gobs, num_gobs, bits, len,
882           gst_bit_reader_get_pos (br)) < PARSE_OK)
883     goto beach;
884
885   /* Split, create and push packets */
886   gob = gobs;
887   marker = FALSE;
888   while (marker == FALSE && ret == GST_FLOW_OK) {
889     guint endpos;
890
891     /* Check if there is wrap around because of extremely high MTU */
892     endpos = GST_ROUND_DOWN_8 (startpos) + max_payload_size * 8;
893     if (endpos < startpos)
894       endpos = G_MAXUINT;
895
896     GST_LOG_OBJECT (pay, "Next packet startpos %u maxpos %u", startpos, endpos);
897
898     /* Find the last GOB that does not completely fit in packet */
899     for (; gob < &gobs[num_gobs - 1]; gob++) {
900       if (bitrange_to_bytes (startpos, gob->endpos) > max_payload_size) {
901         GST_LOG_OBJECT (pay, "Split gob (start %u, end %u)",
902             gob->startpos, gob->endpos);
903         break;
904       }
905     }
906
907     if (startpos <= gob->startpos) {
908       /* Fast-forward until start of GOB */
909       gst_bit_reader_set_pos (br, gob->startpos);
910       if (parse_gob_header (pay, br, gob) < PARSE_OK) {
911         GST_WARNING_OBJECT (pay, "Failed to parse GOB header");
912         goto beach;
913       }
914       gob->last.mba = 0;
915       gob->last.gobn = gob->gn;
916       gob->last.quant = gob->gquant;
917     }
918
919     /* Parse MBs to find position where to split. Can only be done on after MB
920      * or at GOB boundary. */
921     result = parse_mb_until_pos (pay, br, gob, &endpos);
922     if (result < PARSE_OK)
923       goto beach;
924
925     marker = result == PARSE_END_OF_FRAME;
926     ret = gst_rtp_h261_pay_fragment_push (pay, bits, startpos, endpos,
927         &last_mb_in_previous_packet, marker);
928
929     last_mb_in_previous_packet = gob->last;
930     if (endpos == gob->endpos)
931       gob++;
932     startpos = endpos;
933   }
934
935 beach:
936   return ret;
937 }
938
939 /* Shift buffer to packetize a continuous stream of bits (not bytes). Some
940  * payloaders/decoders are very picky about correct sbit/ebit for frames. */
941 static guint8 *
942 gst_rtp_h261_pay_shift_buffer (GstRtpH261Pay * pay, const guint8 * data,
943     gsize size, gint offset, gsize * newsize)
944 {
945   /* In order to read variable length codes at the very end of the buffer
946    * wihout peeking into possibly unallocated data, we pad with extra 0's
947    * which will generate an invalid code at the end of the buffer. */
948   guint pad = 4;
949   gsize allocsize = size + pad;
950   guint8 *bits = g_malloc (allocsize);
951   gint i;
952
953   if (offset == 0) {
954     memcpy (bits, data, size);
955     *newsize = size;
956   } else if (offset > 0) {
957     bits[0] = 0;
958     for (i = 0; i < size; i++) {
959       bits[i] |= data[i] >> offset;
960       bits[i + 1] = data[i] << (8 - offset);
961     }
962     *newsize = size + 1;
963   } else {
964     gint shift = -offset;
965     for (i = 0; i < size - 1; i++)
966       bits[i] = (data[i] << shift) | (data[i + 1] >> (8 - shift));
967     bits[i] = data[i] << shift;
968     *newsize = size;
969   }
970   for (i = *newsize; i < allocsize; i++)
971     bits[i] = 0;
972
973   return bits;
974 }
975
976 static GstFlowReturn
977 gst_rtp_h261_pay_handle_buffer (GstRTPBasePayload * payload, GstBuffer * buffer)
978 {
979   GstFlowReturn ret = GST_FLOW_OK;
980   GstRtpH261Pay *pay = GST_RTP_H261_PAY (payload);
981   gsize len;
982   guint8 *bits;
983   gint psc_offset, shift;
984   GstMapInfo map;
985
986   GST_DEBUG_OBJECT (pay, "Handle buffer of size %" G_GSIZE_FORMAT,
987       gst_buffer_get_size (buffer));
988
989   pay->timestamp = GST_BUFFER_TIMESTAMP (buffer);
990
991   if (!gst_buffer_map (buffer, &map, GST_MAP_READ) || !map.data) {
992     GST_WARNING_OBJECT (pay, "Failed to map buffer");
993     return GST_FLOW_ERROR;
994   }
995
996   psc_offset = find_picture_header_offset (map.data, map.size);
997   if (psc_offset < 0) {
998     GST_WARNING_OBJECT (pay, "Failed to find picture header offset");
999     goto beach;
1000   } else {
1001     GST_DEBUG_OBJECT (pay, "Picture header offset: %d", psc_offset);
1002   }
1003
1004   shift = pay->offset - psc_offset;
1005   bits = gst_rtp_h261_pay_shift_buffer (pay, map.data, map.size, shift, &len);
1006   ret = gst_rtp_h261_packetize_and_push (pay, bits, len);
1007   g_free (bits);
1008
1009 beach:
1010   gst_buffer_unmap (buffer, &map);
1011   gst_buffer_unref (buffer);
1012   return ret;
1013 }
1014
1015
1016 static gboolean
1017 gst_rtp_h261_pay_setcaps (GstRTPBasePayload * payload, GstCaps * caps)
1018 {
1019   gboolean res;
1020
1021   gst_rtp_base_payload_set_options (payload, "video", TRUE, "H261", 90000);
1022   res = gst_rtp_base_payload_set_outcaps (payload, NULL);
1023
1024   return res;
1025 }
1026
1027 static void
1028 gst_rtp_h261_pay_init (GstRtpH261Pay * pay)
1029 {
1030   GstRTPBasePayload *payload = GST_RTP_BASE_PAYLOAD (pay);
1031   payload->pt = GST_RTP_PAYLOAD_H261;
1032   pay->offset = 0;
1033 }
1034
1035 static void
1036 gst_rtp_h261_pay_class_init (GstRtpH261PayClass * klass)
1037 {
1038   GstElementClass *element_class;
1039   GstRTPBasePayloadClass *gstrtpbasepayload_class;
1040
1041   element_class = GST_ELEMENT_CLASS (klass);
1042   gstrtpbasepayload_class = GST_RTP_BASE_PAYLOAD_CLASS (klass);
1043
1044   gst_element_class_add_pad_template (element_class,
1045       gst_static_pad_template_get (&gst_rtp_h261_pay_src_template));
1046   gst_element_class_add_pad_template (element_class,
1047       gst_static_pad_template_get (&gst_rtp_h261_pay_sink_template));
1048
1049   gst_element_class_set_static_metadata (element_class,
1050       "RTP H261 packet payloader", "Codec/Payloader/Network/RTP",
1051       "Payload-encodes H261 video in RTP packets (RFC 4587)",
1052       "Stian Selnes <stian@pexip.com>");
1053
1054   gstrtpbasepayload_class->set_caps = gst_rtp_h261_pay_setcaps;
1055   gstrtpbasepayload_class->handle_buffer = gst_rtp_h261_pay_handle_buffer;
1056
1057   GST_DEBUG_CATEGORY_INIT (rtph261pay_debug, "rtph261pay", 0,
1058       "H261 RTP Payloader");
1059 }
1060
1061 gboolean
1062 gst_rtp_h261_pay_plugin_init (GstPlugin * plugin)
1063 {
1064   return gst_element_register (plugin, "rtph261pay",
1065       GST_RANK_SECONDARY, GST_TYPE_RTP_H261_PAY);
1066 }