]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec_xiph.c
Merge remote-tracking branch 'qatar/master'
[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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/base64.h"
34 #include "libavcodec/bytestream.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 av_cold int xiph_vorbis_init(AVFormatContext *ctx, int st_index,
74                                     PayloadContext *data)
75 {
76     if (st_index < 0)
77         return 0;
78     ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_HEADERS;
79     return 0;
80 }
81
82
83 static int xiph_handle_packet(AVFormatContext *ctx, PayloadContext *data,
84                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
85                               const uint8_t *buf, int len, uint16_t seq,
86                               int flags)
87 {
88
89     int ident, fragmented, tdt, num_pkts, pkt_len;
90
91     if (!buf) {
92         if (!data->split_buf || data->split_pos + 2 > data->split_buf_len ||
93             data->split_pkts <= 0) {
94             av_log(ctx, AV_LOG_ERROR, "No more data to return\n");
95             return AVERROR_INVALIDDATA;
96         }
97         pkt_len = AV_RB16(data->split_buf + data->split_pos);
98         data->split_pos += 2;
99         if (data->split_pos + pkt_len > data->split_buf_len) {
100             av_log(ctx, AV_LOG_ERROR, "Not enough data to return\n");
101             return AVERROR_INVALIDDATA;
102         }
103         if (av_new_packet(pkt, pkt_len)) {
104             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
105             return AVERROR(ENOMEM);
106         }
107         pkt->stream_index = st->index;
108         memcpy(pkt->data, data->split_buf + data->split_pos, pkt_len);
109         data->split_pos += pkt_len;
110         data->split_pkts--;
111         return data->split_pkts > 0;
112     }
113
114     if (len < 6) {
115         av_log(ctx, AV_LOG_ERROR, "Invalid %d byte packet\n", len);
116         return AVERROR_INVALIDDATA;
117     }
118
119     // read xiph rtp headers
120     ident       = AV_RB24(buf);
121     fragmented  = buf[3] >> 6;
122     tdt         = (buf[3] >> 4) & 3;
123     num_pkts    = buf[3] & 0xf;
124     pkt_len     = AV_RB16(buf + 4);
125
126     if (pkt_len > len - 6) {
127         av_log(ctx, AV_LOG_ERROR,
128                "Invalid packet length %d in %d byte packet\n", pkt_len,
129                len);
130         return AVERROR_INVALIDDATA;
131     }
132
133     if (ident != data->ident) {
134         av_log(ctx, AV_LOG_ERROR,
135                "Unimplemented Xiph SDP configuration change detected\n");
136         return AVERROR_PATCHWELCOME;
137     }
138
139     if (tdt) {
140         av_log(ctx, AV_LOG_ERROR,
141                "Unimplemented RTP Xiph packet settings (%d,%d,%d)\n",
142                fragmented, tdt, num_pkts);
143         return AVERROR_PATCHWELCOME;
144     }
145
146     buf += 6; // move past header bits
147     len -= 6;
148
149     if (fragmented == 0) {
150         if (av_new_packet(pkt, pkt_len)) {
151             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
152             return AVERROR(ENOMEM);
153         }
154         pkt->stream_index = st->index;
155         memcpy(pkt->data, buf, pkt_len);
156         buf += pkt_len;
157         len -= pkt_len;
158         num_pkts--;
159
160         if (num_pkts > 0) {
161             if (len > data->split_buf_size || !data->split_buf) {
162                 av_freep(&data->split_buf);
163                 data->split_buf_size = 2 * len;
164                 data->split_buf = av_malloc(data->split_buf_size);
165                 if (!data->split_buf) {
166                     av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
167                     av_free_packet(pkt);
168                     return AVERROR(ENOMEM);
169                 }
170             }
171             memcpy(data->split_buf, buf, len);
172             data->split_buf_len = len;
173             data->split_pos = 0;
174             data->split_pkts = num_pkts;
175             return 1;
176         }
177
178         return 0;
179
180     } else if (fragmented == 1) {
181         // start of xiph data fragment
182         int res;
183
184         // end packet has been lost somewhere, so drop buffered data
185         free_fragment_if_needed(data);
186
187         if((res = avio_open_dyn_buf(&data->fragment)) < 0)
188             return res;
189
190         avio_write(data->fragment, buf, pkt_len);
191         data->timestamp = *timestamp;
192
193     } else {
194         av_assert1(fragmented < 4);
195         if (data->timestamp != *timestamp) {
196             // skip if fragmented timestamp is incorrect;
197             // a start packet has been lost somewhere
198             free_fragment_if_needed(data);
199             av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match!\n");
200             return AVERROR_INVALIDDATA;
201         }
202         if (!data->fragment) {
203             av_log(ctx, AV_LOG_WARNING,
204                    "Received packet without a start fragment; dropping.\n");
205             return AVERROR(EAGAIN);
206         }
207
208         // copy data to fragment buffer
209         avio_write(data->fragment, buf, pkt_len);
210
211         if (fragmented == 3) {
212             // end of xiph data packet
213             int ret = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
214             if (ret < 0) {
215                 av_log(ctx, AV_LOG_ERROR,
216                        "Error occurred when getting fragment buffer.");
217                 return ret;
218             }
219
220             return 0;
221         }
222     }
223
224    return AVERROR(EAGAIN);
225 }
226
227 /**
228  * Length encoding described in RFC5215 section 3.1.1.
229  */
230 static int get_base128(const uint8_t ** buf, const uint8_t * buf_end)
231 {
232     int n = 0;
233     for (; *buf < buf_end; ++*buf) {
234         n <<= 7;
235         n += **buf & 0x7f;
236         if (!(**buf & 0x80)) {
237             ++*buf;
238             return n;
239         }
240     }
241     return 0;
242 }
243
244 /**
245  * Based off parse_packed_headers in Vorbis RTP
246  */
247 static int
248 parse_packed_headers(const uint8_t * packed_headers,
249                      const uint8_t * packed_headers_end,
250                      AVCodecContext * codec, PayloadContext * xiph_data)
251 {
252
253     unsigned num_packed, num_headers, length, length1, length2, extradata_alloc;
254     uint8_t *ptr;
255
256     if (packed_headers_end - packed_headers < 9) {
257         av_log(codec, AV_LOG_ERROR,
258                "Invalid %td byte packed header.",
259                packed_headers_end - packed_headers);
260         return AVERROR_INVALIDDATA;
261     }
262
263     num_packed         = bytestream_get_be32(&packed_headers);
264     xiph_data->ident   = bytestream_get_be24(&packed_headers);
265     length             = bytestream_get_be16(&packed_headers);
266     num_headers        = get_base128(&packed_headers, packed_headers_end);
267     length1            = get_base128(&packed_headers, packed_headers_end);
268     length2            = get_base128(&packed_headers, packed_headers_end);
269
270     if (num_packed != 1 || num_headers > 3) {
271         av_log(codec, AV_LOG_ERROR,
272                "Unimplemented number of headers: %d packed headers, %d headers\n",
273                num_packed, num_headers);
274         return AVERROR_PATCHWELCOME;
275     }
276
277     if (packed_headers_end - packed_headers != length ||
278         length1 > length || length2 > length - length1) {
279         av_log(codec, AV_LOG_ERROR,
280                "Bad packed header lengths (%d,%d,%td,%d)\n", length1,
281                length2, packed_headers_end - packed_headers, length);
282         return AVERROR_INVALIDDATA;
283     }
284
285     /* allocate extra space:
286      * -- length/255 +2 for xiphlacing
287      * -- one for the '2' marker
288      * -- FF_INPUT_BUFFER_PADDING_SIZE required */
289     extradata_alloc = length + length/255 + 3 + FF_INPUT_BUFFER_PADDING_SIZE;
290
291     ptr = codec->extradata = av_malloc(extradata_alloc);
292     if (!ptr) {
293         av_log(codec, AV_LOG_ERROR, "Out of memory\n");
294         return AVERROR(ENOMEM);
295     }
296     *ptr++ = 2;
297     ptr += av_xiphlacing(ptr, length1);
298     ptr += av_xiphlacing(ptr, length2);
299     memcpy(ptr, packed_headers, length);
300     ptr += length;
301     codec->extradata_size = ptr - codec->extradata;
302     // clear out remaining parts of the buffer
303     memset(ptr, 0, extradata_alloc - codec->extradata_size);
304
305     return 0;
306 }
307
308 static int xiph_parse_fmtp_pair(AVStream* stream,
309                                 PayloadContext *xiph_data,
310                                 char *attr, char *value)
311 {
312     AVCodecContext *codec = stream->codec;
313     int result = 0;
314
315     if (!strcmp(attr, "sampling")) {
316         if (!strcmp(value, "YCbCr-4:2:0")) {
317             codec->pix_fmt = AV_PIX_FMT_YUV420P;
318         } else if (!strcmp(value, "YCbCr-4:4:2")) {
319             codec->pix_fmt = AV_PIX_FMT_YUV422P;
320         } else if (!strcmp(value, "YCbCr-4:4:4")) {
321             codec->pix_fmt = AV_PIX_FMT_YUV444P;
322         } else {
323             av_log(codec, AV_LOG_ERROR,
324                    "Unsupported pixel format %s\n", attr);
325             return AVERROR_INVALIDDATA;
326         }
327     } else if (!strcmp(attr, "width")) {
328         /* This is an integer between 1 and 1048561
329          * and MUST be in multiples of 16. */
330         codec->width = atoi(value);
331         return 0;
332     } else if (!strcmp(attr, "height")) {
333         /* This is an integer between 1 and 1048561
334          * and MUST be in multiples of 16. */
335         codec->height = atoi(value);
336         return 0;
337     } else if (!strcmp(attr, "delivery-method")) {
338         /* Possible values are: inline, in_band, out_band/specific_name. */
339         return AVERROR_PATCHWELCOME;
340     } else if (!strcmp(attr, "configuration-uri")) {
341         /* NOTE: configuration-uri is supported only under 2 conditions:
342          *--after the delivery-method tag
343          * --with a delivery-method value of out_band */
344         return AVERROR_PATCHWELCOME;
345     } else if (!strcmp(attr, "configuration")) {
346         /* NOTE: configuration is supported only AFTER the delivery-method tag
347          * The configuration value is a base64 encoded packed header */
348         uint8_t *decoded_packet = NULL;
349         int packet_size;
350         size_t decoded_alloc = strlen(value) / 4 * 3 + 4;
351
352         if (decoded_alloc <= INT_MAX) {
353             decoded_packet = av_malloc(decoded_alloc);
354             if (decoded_packet) {
355                 packet_size =
356                     av_base64_decode(decoded_packet, value, decoded_alloc);
357
358                 result = parse_packed_headers
359                     (decoded_packet, decoded_packet + packet_size, codec,
360                     xiph_data);
361             } else {
362                 av_log(codec, AV_LOG_ERROR,
363                        "Out of memory while decoding SDP configuration.\n");
364                 result = AVERROR(ENOMEM);
365             }
366         } else {
367             av_log(codec, AV_LOG_ERROR, "Packet too large\n");
368             result = AVERROR_INVALIDDATA;
369         }
370         av_free(decoded_packet);
371     }
372     return result;
373 }
374
375 static int xiph_parse_sdp_line(AVFormatContext *s, int st_index,
376                                PayloadContext *data, const char *line)
377 {
378     const char *p;
379
380     if (st_index < 0)
381         return 0;
382
383     if (av_strstart(line, "fmtp:", &p)) {
384         return ff_parse_fmtp(s->streams[st_index], data, p,
385                              xiph_parse_fmtp_pair);
386     }
387
388     return 0;
389 }
390
391 RTPDynamicProtocolHandler ff_theora_dynamic_handler = {
392     .enc_name         = "theora",
393     .codec_type       = AVMEDIA_TYPE_VIDEO,
394     .codec_id         = AV_CODEC_ID_THEORA,
395     .parse_sdp_a_line = xiph_parse_sdp_line,
396     .alloc            = xiph_new_context,
397     .free             = xiph_free_context,
398     .parse_packet     = xiph_handle_packet
399 };
400
401 RTPDynamicProtocolHandler ff_vorbis_dynamic_handler = {
402     .enc_name         = "vorbis",
403     .codec_type       = AVMEDIA_TYPE_AUDIO,
404     .codec_id         = AV_CODEC_ID_VORBIS,
405     .init             = xiph_vorbis_init,
406     .parse_sdp_a_line = xiph_parse_sdp_line,
407     .alloc            = xiph_new_context,
408     .free             = xiph_free_context,
409     .parse_packet     = xiph_handle_packet
410 };