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