1 /*
2  * RTP parser for H.261 payload format (RFC 4587)
3  * Copyright (c) 2014 Thomas Volkert <thomas@homer-conferencing.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "avformat.h"
23 #include "rtpdec_formats.h"
24 #include "libavcodec/get_bits.h"
25 
26 #define RTP_H261_PAYLOAD_HEADER_SIZE                    4
27 
28 struct PayloadContext {
29     AVIOContext *buf;
30     uint8_t      endbyte;
31     int          endbyte_bits;
32     uint32_t     timestamp;
33 };
34 
h261_new_context(void)35 static PayloadContext *h261_new_context(void)
36 {
37     return av_mallocz(sizeof(PayloadContext));
38 }
39 
h261_free_dyn_buffer(AVIOContext ** dyn_buf)40 static void h261_free_dyn_buffer(AVIOContext **dyn_buf)
41 {
42     uint8_t *ptr_dyn_buffer;
43     avio_close_dyn_buf(*dyn_buf, &ptr_dyn_buffer);
44     av_free(ptr_dyn_buffer);
45     *dyn_buf = NULL;
46 }
47 
h261_free_context(PayloadContext * pl_ctx)48 static void h261_free_context(PayloadContext *pl_ctx)
49 {
50     /* return if context is invalid */
51     if (!pl_ctx)
52         return;
53 
54     /* free buffer if it is valid */
55     if (pl_ctx->buf) {
56         h261_free_dyn_buffer(&pl_ctx->buf);
57     }
58 
59     /* free context */
60     av_free(pl_ctx);
61 }
62 
h261_init(AVFormatContext * ctx,int st_index,PayloadContext * data)63 static av_cold int h261_init(AVFormatContext *ctx, int st_index,
64                              PayloadContext *data)
65 {
66     //av_log(ctx, AV_LOG_DEBUG, "h261_init() for stream %d\n", st_index);
67 
68     if (st_index < 0)
69         return 0;
70 
71     ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
72 
73     return 0;
74 }
75 
ff_h261_handle_packet(AVFormatContext * ctx,PayloadContext * data,AVStream * st,AVPacket * pkt,uint32_t * timestamp,const uint8_t * buf,int len,uint16_t seq,int flags)76 int ff_h261_handle_packet(AVFormatContext *ctx, PayloadContext *data,
77                           AVStream *st, AVPacket *pkt, uint32_t *timestamp,
78                           const uint8_t *buf, int len, uint16_t seq, int flags)
79 {
80     int sbit, ebit, gobn, mbap, quant;
81     int res;
82 
83     //av_log(ctx, AV_LOG_DEBUG, "got h261 RTP packet with time: %u\n", timestamp);
84 
85     /* drop data of previous packets in case of non-continuous (loss) packet stream */
86     if (data->buf && data->timestamp != *timestamp) {
87         h261_free_dyn_buffer(&data->buf);
88     }
89 
90     /* sanity check for size of input packet */
91     if (len < 5 /* 4 bytes header and 1 byte payload at least */) {
92         av_log(ctx, AV_LOG_ERROR, "Too short H.261 RTP packet\n");
93         return AVERROR_INVALIDDATA;
94     }
95 
96     /*
97       decode the H.261 payload header according to section 4.1 of RFC 4587:
98       (uses 4 bytes between RTP header and H.261 stream per packet)
99 
100          0                   1                   2                   3
101          0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
102         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103         |SBIT |EBIT |I|V| GOBN  |   MBAP  |  QUANT  |  HMVD   |  VMVD   |
104         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105 
106            Start bit position (SBIT): 3 bits
107            End bit position (EBIT): 3 bits
108            INTRA-frame encoded data (I): 1 bit
109            Motion Vector flag (V): 1 bit
110            GOB number (GOBN): 4 bits
111            Macroblock address predictor (MBAP): 5 bits
112            Quantizer (QUANT): 5 bits
113            Horizontal motion vector data (HMVD): 5 bits
114            Vertical motion vector data (VMVD): 5 bits
115 
116     */
117     sbit  =  (buf[0] >> 5) & 0x07;
118     ebit  =  (buf[0] >> 2) & 0x07;
119     gobn  =  (buf[1] >> 4) & 0x0f;
120     mbap  = ((buf[1] << 1) & 0x1e) | ((buf[2] >> 7) & 0x01);
121     quant =  (buf[2] >> 2) & 0x1f;
122 
123     /* pass the H.261 payload header and continue with the actual payload */
124     buf += RTP_H261_PAYLOAD_HEADER_SIZE;
125     len -= RTP_H261_PAYLOAD_HEADER_SIZE;
126 
127     /* start frame buffering with new dynamic buffer */
128     if (!data->buf) {
129         /* sanity check: a new frame starts with gobn=0, sbit=0, mbap=0, uqnat=0 */
130         if (!gobn  && !sbit && !mbap && !quant){
131             res = avio_open_dyn_buf(&data->buf);
132             if (res < 0)
133                 return res;
134             /* update the timestamp in the frame packet with the one from the RTP packet */
135             data->timestamp = *timestamp;
136         } else {
137             /* frame not started yet, need more packets */
138             return AVERROR(EAGAIN);
139         }
140     }
141 
142     /* do the "byte merging" at the boundaries of two consecutive frame fragments */
143     if (data->endbyte_bits || sbit) {
144         if (data->endbyte_bits == sbit) {
145             data->endbyte |= buf[0] & (0xff >> sbit);
146             data->endbyte_bits = 0;
147             buf++;
148             len--;
149             avio_w8(data->buf, data->endbyte);
150         } else {
151             /* ebit/sbit values inconsistent, assuming packet loss */
152             GetBitContext gb;
153             init_get_bits(&gb, buf, len*8 - ebit);
154             skip_bits(&gb, sbit);
155             if (data->endbyte_bits) {
156                 data->endbyte |= get_bits(&gb, 8 - data->endbyte_bits);
157                 avio_w8(data->buf, data->endbyte);
158             }
159             while (get_bits_left(&gb) >= 8)
160                 avio_w8(data->buf, get_bits(&gb, 8));
161             data->endbyte_bits = get_bits_left(&gb);
162             if (data->endbyte_bits)
163                 data->endbyte = get_bits(&gb, data->endbyte_bits) <<
164                                 (8 - data->endbyte_bits);
165             ebit = 0;
166             len = 0;
167         }
168     }
169     if (ebit) {
170         if (len > 0)
171             avio_write(data->buf, buf, len - 1);
172         data->endbyte_bits = 8 - ebit;
173         data->endbyte = buf[len - 1] & (0xff << ebit);
174     } else {
175         avio_write(data->buf, buf, len);
176     }
177 
178     /* RTP marker bit means: last fragment of current frame was received;
179        otherwise, an additional fragment is needed for the current frame */
180     if (!(flags & RTP_FLAG_MARKER))
181         return AVERROR(EAGAIN);
182 
183     /* write the completed last byte from the "byte merging" */
184     if (data->endbyte_bits)
185         avio_w8(data->buf, data->endbyte);
186     data->endbyte_bits = 0;
187 
188     /* close frame buffering and create resulting A/V packet */
189     res = ff_rtp_finalize_packet(pkt, &data->buf, st->index);
190     if (res < 0)
191         return res;
192 
193     return 0;
194 }
195 
196 RTPDynamicProtocolHandler ff_h261_dynamic_handler = {
197 	.enc_name          = "H261",
198     .codec_type        = AVMEDIA_TYPE_VIDEO,
199     .codec_id          = AV_CODEC_ID_H261,
200     .init              = h261_init,
201     .parse_packet      = ff_h261_handle_packet,
202     .alloc             = h261_new_context,
203     .free              = h261_free_context,
204     .static_payload_id = 31,
205 };
206