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