]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec_xiph.c
bitstream: add get_bits64() to support reading more than 32 bits at once
[ffmpeg] / libavformat / rtpdec_xiph.c
1 /*
2  * Xiph RTP Protocols
3  * Copyright (c) 2009 Colin McQuillian
4  * Copyright (c) 2010 Josh Allmann
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * @brief Xiph / RTP Code
26  * @author Colin McQuillan <m.niloc@gmail.com>
27  * @author Josh Allmann <joshua.allmann@gmail.com>
28  */
29
30 #include "libavutil/avstring.h"
31 #include "libavutil/base64.h"
32 #include "libavcodec/bytestream.h"
33
34 #include <assert.h>
35
36 #include "rtpdec.h"
37 #include "rtpdec_formats.h"
38
39 /**
40  * RTP/Xiph specific private data.
41  */
42 struct PayloadContext {
43     unsigned ident;             ///< 24-bit stream configuration identifier
44     uint32_t timestamp;
45     AVIOContext* fragment;    ///< buffer for split payloads
46     uint8_t *split_buf;
47     int split_pos, split_buf_len, split_buf_size;
48     int split_pkts;
49 };
50
51 static PayloadContext *xiph_new_context(void)
52 {
53     return av_mallocz(sizeof(PayloadContext));
54 }
55
56 static inline void free_fragment_if_needed(PayloadContext * data)
57 {
58     if (data->fragment) {
59         uint8_t* p;
60         avio_close_dyn_buf(data->fragment, &p);
61         av_free(p);
62         data->fragment = NULL;
63     }
64 }
65
66 static void xiph_free_context(PayloadContext * data)
67 {
68     free_fragment_if_needed(data);
69     av_free(data->split_buf);
70     av_free(data);
71 }
72
73 static int xiph_handle_packet(AVFormatContext * ctx,
74                               PayloadContext * data,
75                               AVStream * st,
76                               AVPacket * pkt,
77                               uint32_t * timestamp,
78                               const uint8_t * buf, int len, int flags)
79 {
80
81     int ident, fragmented, tdt, num_pkts, pkt_len;
82
83     if (!buf) {
84         if (!data->split_buf || data->split_pos + 2 > data->split_buf_len ||
85             data->split_pkts <= 0) {
86             av_log(ctx, AV_LOG_ERROR, "No more data to return\n");
87             return AVERROR_INVALIDDATA;
88         }
89         pkt_len = AV_RB16(data->split_buf + data->split_pos);
90         data->split_pos += 2;
91         if (data->split_pos + pkt_len > data->split_buf_len) {
92             av_log(ctx, AV_LOG_ERROR, "Not enough data to return\n");
93             return AVERROR_INVALIDDATA;
94         }
95         if (av_new_packet(pkt, pkt_len)) {
96             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
97             return AVERROR(ENOMEM);
98         }
99         pkt->stream_index = st->index;
100         memcpy(pkt->data, data->split_buf + data->split_pos, pkt_len);
101         data->split_pos += pkt_len;
102         data->split_pkts--;
103         return data->split_pkts > 0;
104     }
105
106     if (len < 6) {
107         av_log(ctx, AV_LOG_ERROR, "Invalid %d byte packet\n", len);
108         return AVERROR_INVALIDDATA;
109     }
110
111     // read xiph rtp headers
112     ident       = AV_RB24(buf);
113     fragmented  = buf[3] >> 6;
114     tdt         = (buf[3] >> 4) & 3;
115     num_pkts    = buf[3] & 0xf;
116     pkt_len     = AV_RB16(buf + 4);
117
118     if (pkt_len > len - 6) {
119         av_log(ctx, AV_LOG_ERROR,
120                "Invalid packet length %d in %d byte packet\n", pkt_len,
121                len);
122         return AVERROR_INVALIDDATA;
123     }
124
125     if (ident != data->ident) {
126         av_log(ctx, AV_LOG_ERROR,
127                "Unimplemented Xiph SDP configuration change detected\n");
128         return AVERROR_PATCHWELCOME;
129     }
130
131     if (tdt) {
132         av_log(ctx, AV_LOG_ERROR,
133                "Unimplemented RTP Xiph packet settings (%d,%d,%d)\n",
134                fragmented, tdt, num_pkts);
135         return AVERROR_PATCHWELCOME;
136     }
137
138     buf += 6; // move past header bits
139     len -= 6;
140
141     if (fragmented == 0) {
142         if (av_new_packet(pkt, pkt_len)) {
143             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
144             return AVERROR(ENOMEM);
145         }
146         pkt->stream_index = st->index;
147         memcpy(pkt->data, buf, pkt_len);
148         buf += pkt_len;
149         len -= pkt_len;
150         num_pkts--;
151
152         if (num_pkts > 0) {
153             if (len > data->split_buf_size || !data->split_buf) {
154                 av_freep(&data->split_buf);
155                 data->split_buf_size = 2 * len;
156                 data->split_buf = av_malloc(data->split_buf_size);
157                 if (!data->split_buf) {
158                     av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
159                     av_free_packet(pkt);
160                     return AVERROR(ENOMEM);
161                 }
162             }
163             memcpy(data->split_buf, buf, len);
164             data->split_buf_len = len;
165             data->split_pos = 0;
166             data->split_pkts = num_pkts;
167             return 1;
168         }
169
170         return 0;
171
172     } else if (fragmented == 1) {
173         // start of xiph data fragment
174         int res;
175
176         // end packet has been lost somewhere, so drop buffered data
177         free_fragment_if_needed(data);
178
179         if((res = avio_open_dyn_buf(&data->fragment)) < 0)
180             return res;
181
182         avio_write(data->fragment, buf, pkt_len);
183         data->timestamp = *timestamp;
184
185     } else {
186         assert(fragmented < 4);
187         if (data->timestamp != *timestamp) {
188             // skip if fragmented timestamp is incorrect;
189             // a start packet has been lost somewhere
190             free_fragment_if_needed(data);
191             av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match!\n");
192             return AVERROR_INVALIDDATA;
193         }
194         if (!data->fragment) {
195             av_log(ctx, AV_LOG_WARNING,
196                    "Received packet without a start fragment; dropping.\n");
197             return AVERROR(EAGAIN);
198         }
199
200         // copy data to fragment buffer
201         avio_write(data->fragment, buf, pkt_len);
202
203         if (fragmented == 3) {
204             // end of xiph data packet
205             int ret = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
206             if (ret < 0) {
207                 av_log(ctx, AV_LOG_ERROR,
208                        "Error occurred when getting fragment buffer.");
209                 return ret;
210             }
211
212             return 0;
213         }
214     }
215
216    return AVERROR(EAGAIN);
217 }
218
219 /**
220  * Length encoding described in RFC5215 section 3.1.1.
221  */
222 static int get_base128(const uint8_t ** buf, const uint8_t * buf_end)
223 {
224     int n = 0;
225     for (; *buf < buf_end; ++*buf) {
226         n <<= 7;
227         n += **buf & 0x7f;
228         if (!(**buf & 0x80)) {
229             ++*buf;
230             return n;
231         }
232     }
233     return 0;
234 }
235
236 /**
237  * Based off parse_packed_headers in Vorbis RTP
238  */
239 static int
240 parse_packed_headers(const uint8_t * packed_headers,
241                      const uint8_t * packed_headers_end,
242                      AVCodecContext * codec, PayloadContext * xiph_data)
243 {
244
245     unsigned num_packed, num_headers, length, length1, length2, extradata_alloc;
246     uint8_t *ptr;
247
248     if (packed_headers_end - packed_headers < 9) {
249         av_log(codec, AV_LOG_ERROR,
250                "Invalid %td byte packed header.",
251                packed_headers_end - packed_headers);
252         return AVERROR_INVALIDDATA;
253     }
254
255     num_packed         = bytestream_get_be32(&packed_headers);
256     xiph_data->ident   = bytestream_get_be24(&packed_headers);
257     length             = bytestream_get_be16(&packed_headers);
258     num_headers        = get_base128(&packed_headers, packed_headers_end);
259     length1            = get_base128(&packed_headers, packed_headers_end);
260     length2            = get_base128(&packed_headers, packed_headers_end);
261
262     if (num_packed != 1 || num_headers > 3) {
263         av_log(codec, AV_LOG_ERROR,
264                "Unimplemented number of headers: %d packed headers, %d headers\n",
265                num_packed, num_headers);
266         return AVERROR_PATCHWELCOME;
267     }
268
269     if (packed_headers_end - packed_headers != length ||
270         length1 > length || length2 > length - length1) {
271         av_log(codec, AV_LOG_ERROR,
272                "Bad packed header lengths (%d,%d,%td,%d)\n", length1,
273                length2, packed_headers_end - packed_headers, length);
274         return AVERROR_INVALIDDATA;
275     }
276
277     /* allocate extra space:
278      * -- length/255 +2 for xiphlacing
279      * -- one for the '2' marker
280      * -- FF_INPUT_BUFFER_PADDING_SIZE required */
281     extradata_alloc = length + length/255 + 3 + FF_INPUT_BUFFER_PADDING_SIZE;
282
283     ptr = codec->extradata = av_malloc(extradata_alloc);
284     if (!ptr) {
285         av_log(codec, AV_LOG_ERROR, "Out of memory\n");
286         return AVERROR(ENOMEM);
287     }
288     *ptr++ = 2;
289     ptr += av_xiphlacing(ptr, length1);
290     ptr += av_xiphlacing(ptr, length2);
291     memcpy(ptr, packed_headers, length);
292     ptr += length;
293     codec->extradata_size = ptr - codec->extradata;
294     // clear out remaining parts of the buffer
295     memset(ptr, 0, extradata_alloc - codec->extradata_size);
296
297     return 0;
298 }
299
300 static int xiph_parse_fmtp_pair(AVStream* stream,
301                                 PayloadContext *xiph_data,
302                                 char *attr, char *value)
303 {
304     AVCodecContext *codec = stream->codec;
305     int result = 0;
306
307     if (!strcmp(attr, "sampling")) {
308         if (!strcmp(value, "YCbCr-4:2:0")) {
309             codec->pix_fmt = AV_PIX_FMT_YUV420P;
310         } else if (!strcmp(value, "YCbCr-4:4:2")) {
311             codec->pix_fmt = AV_PIX_FMT_YUV422P;
312         } else if (!strcmp(value, "YCbCr-4:4:4")) {
313             codec->pix_fmt = AV_PIX_FMT_YUV444P;
314         } else {
315             av_log(codec, AV_LOG_ERROR,
316                    "Unsupported pixel format %s\n", attr);
317             return AVERROR_INVALIDDATA;
318         }
319     } else if (!strcmp(attr, "width")) {
320         /* This is an integer between 1 and 1048561
321          * and MUST be in multiples of 16. */
322         codec->width = atoi(value);
323         return 0;
324     } else if (!strcmp(attr, "height")) {
325         /* This is an integer between 1 and 1048561
326          * and MUST be in multiples of 16. */
327         codec->height = atoi(value);
328         return 0;
329     } else if (!strcmp(attr, "delivery-method")) {
330         /* Possible values are: inline, in_band, out_band/specific_name. */
331         return AVERROR_PATCHWELCOME;
332     } else if (!strcmp(attr, "configuration-uri")) {
333         /* NOTE: configuration-uri is supported only under 2 conditions:
334          *--after the delivery-method tag
335          * --with a delivery-method value of out_band */
336         return AVERROR_PATCHWELCOME;
337     } else if (!strcmp(attr, "configuration")) {
338         /* NOTE: configuration is supported only AFTER the delivery-method tag
339          * The configuration value is a base64 encoded packed header */
340         uint8_t *decoded_packet = NULL;
341         int packet_size;
342         size_t decoded_alloc = strlen(value) / 4 * 3 + 4;
343
344         if (decoded_alloc <= INT_MAX) {
345             decoded_packet = av_malloc(decoded_alloc);
346             if (decoded_packet) {
347                 packet_size =
348                     av_base64_decode(decoded_packet, value, decoded_alloc);
349
350                 result = parse_packed_headers
351                     (decoded_packet, decoded_packet + packet_size, codec,
352                     xiph_data);
353             } else {
354                 av_log(codec, AV_LOG_ERROR,
355                        "Out of memory while decoding SDP configuration.\n");
356                 result = AVERROR(ENOMEM);
357             }
358         } else {
359             av_log(codec, AV_LOG_ERROR, "Packet too large\n");
360             result = AVERROR_INVALIDDATA;
361         }
362         av_free(decoded_packet);
363     }
364     return result;
365 }
366
367 static int xiph_parse_sdp_line(AVFormatContext *s, int st_index,
368                                PayloadContext *data, const char *line)
369 {
370     const char *p;
371
372     if (st_index < 0)
373         return 0;
374
375     if (av_strstart(line, "fmtp:", &p)) {
376         return ff_parse_fmtp(s->streams[st_index], data, p,
377                              xiph_parse_fmtp_pair);
378     }
379
380     return 0;
381 }
382
383 RTPDynamicProtocolHandler ff_theora_dynamic_handler = {
384     .enc_name         = "theora",
385     .codec_type       = AVMEDIA_TYPE_VIDEO,
386     .codec_id         = AV_CODEC_ID_THEORA,
387     .parse_sdp_a_line = xiph_parse_sdp_line,
388     .alloc            = xiph_new_context,
389     .free             = xiph_free_context,
390     .parse_packet     = xiph_handle_packet
391 };
392
393 RTPDynamicProtocolHandler ff_vorbis_dynamic_handler = {
394     .enc_name         = "vorbis",
395     .codec_type       = AVMEDIA_TYPE_AUDIO,
396     .codec_id         = AV_CODEC_ID_VORBIS,
397     .parse_sdp_a_line = xiph_parse_sdp_line,
398     .alloc            = xiph_new_context,
399     .free             = xiph_free_context,
400     .parse_packet     = xiph_handle_packet
401 };