rtsp: Add a buffer_size option
[libav.git] / libavformat / rtsp.c
1 /*
2 * RTSP/SDP client
3 * Copyright (c) 2002 Fabrice Bellard
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "libavutil/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/random_seed.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/time.h"
31 #include "avformat.h"
32 #include "avio_internal.h"
33
34 #if HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include "http.h"
41 #include "rtsp.h"
42
43 #include "rtpdec.h"
44 #include "rtpproto.h"
45 #include "rdt.h"
46 #include "rtpdec_formats.h"
47 #include "rtpenc_chain.h"
48 #include "url.h"
49 #include "rtpenc.h"
50 #include "mpegts.h"
51
52 /* Timeout values for socket poll, in ms,
53 * and read_packet(), in seconds */
54 #define POLL_TIMEOUT_MS 100
55 #define READ_PACKET_TIMEOUT_S 10
56 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
57 #define SDP_MAX_SIZE 16384
58 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
59 #define DEFAULT_REORDERING_DELAY 100000
60
61 #define OFFSET(x) offsetof(RTSPState, x)
62 #define DEC AV_OPT_FLAG_DECODING_PARAM
63 #define ENC AV_OPT_FLAG_ENCODING_PARAM
64
65 #define RTSP_FLAG_OPTS(name, longname) \
66 { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
67 { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
68
69 #define RTSP_MEDIATYPE_OPTS(name, longname) \
70 { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
71 { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
72 { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
73 { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
74
75 #define COMMON_OPTS() \
76 { "reorder_queue_size", "Number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }, \
77 { "buffer_size", "Underlying protocol send/receive buffer size", OFFSET(buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC|ENC } \
78
79
80 const AVOption ff_rtsp_options[] = {
81 { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
82 FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
83 { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
84 { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
85 { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
86 { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
87 { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {.i64 = (1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
88 RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
89 { "listen", "Wait for incoming connections", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_LISTEN}, 0, 0, DEC, "rtsp_flags" },
90 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
91 { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
92 { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
93 { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
94 COMMON_OPTS(),
95 { NULL },
96 };
97
98 static const AVOption sdp_options[] = {
99 RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
100 { "custom_io", "Use custom IO", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_CUSTOM_IO}, 0, 0, DEC, "rtsp_flags" },
101 { "rtcp_to_source", "Send RTCP packets to the source address of received packets", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_RTCP_TO_SOURCE}, 0, 0, DEC, "rtsp_flags" },
102 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
103 COMMON_OPTS(),
104 { NULL },
105 };
106
107 static const AVOption rtp_options[] = {
108 RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
109 COMMON_OPTS(),
110 { NULL },
111 };
112
113
114 static AVDictionary *map_to_opts(RTSPState *rt)
115 {
116 AVDictionary *opts = NULL;
117 char buf[256];
118
119 snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
120 av_dict_set(&opts, "buffer_size", buf, 0);
121
122 return opts;
123 }
124
125 static void get_word_until_chars(char *buf, int buf_size,
126 const char *sep, const char **pp)
127 {
128 const char *p;
129 char *q;
130
131 p = *pp;
132 p += strspn(p, SPACE_CHARS);
133 q = buf;
134 while (!strchr(sep, *p) && *p != '\0') {
135 if ((q - buf) < buf_size - 1)
136 *q++ = *p;
137 p++;
138 }
139 if (buf_size > 0)
140 *q = '\0';
141 *pp = p;
142 }
143
144 static void get_word_sep(char *buf, int buf_size, const char *sep,
145 const char **pp)
146 {
147 if (**pp == '/') (*pp)++;
148 get_word_until_chars(buf, buf_size, sep, pp);
149 }
150
151 static void get_word(char *buf, int buf_size, const char **pp)
152 {
153 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
154 }
155
156 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
157 * and end time.
158 * Used for seeking in the rtp stream.
159 */
160 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
161 {
162 char buf[256];
163
164 p += strspn(p, SPACE_CHARS);
165 if (!av_stristart(p, "npt=", &p))
166 return;
167
168 *start = AV_NOPTS_VALUE;
169 *end = AV_NOPTS_VALUE;
170
171 get_word_sep(buf, sizeof(buf), "-", &p);
172 av_parse_time(start, buf, 1);
173 if (*p == '-') {
174 p++;
175 get_word_sep(buf, sizeof(buf), "-", &p);
176 av_parse_time(end, buf, 1);
177 }
178 }
179
180 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
181 {
182 struct addrinfo hints = { 0 }, *ai = NULL;
183 hints.ai_flags = AI_NUMERICHOST;
184 if (getaddrinfo(buf, NULL, &hints, &ai))
185 return -1;
186 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
187 freeaddrinfo(ai);
188 return 0;
189 }
190
191 #if CONFIG_RTPDEC
192 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
193 RTSPStream *rtsp_st, AVStream *st)
194 {
195 AVCodecContext *codec = st ? st->codec : NULL;
196 if (!handler)
197 return;
198 if (codec)
199 codec->codec_id = handler->codec_id;
200 rtsp_st->dynamic_handler = handler;
201 if (st)
202 st->need_parsing = handler->need_parsing;
203 if (handler->priv_data_size) {
204 rtsp_st->dynamic_protocol_context = av_mallocz(handler->priv_data_size);
205 if (!rtsp_st->dynamic_protocol_context)
206 rtsp_st->dynamic_handler = NULL;
207 }
208 }
209
210 static void finalize_rtp_handler_init(AVFormatContext *s, RTSPStream *rtsp_st,
211 AVStream *st)
212 {
213 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init) {
214 int ret = rtsp_st->dynamic_handler->init(s, st ? st->index : -1,
215 rtsp_st->dynamic_protocol_context);
216 if (ret < 0) {
217 if (rtsp_st->dynamic_protocol_context) {
218 if (rtsp_st->dynamic_handler->close)
219 rtsp_st->dynamic_handler->close(
220 rtsp_st->dynamic_protocol_context);
221 av_free(rtsp_st->dynamic_protocol_context);
222 }
223 rtsp_st->dynamic_protocol_context = NULL;
224 rtsp_st->dynamic_handler = NULL;
225 }
226 }
227 }
228
229 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
230 static int sdp_parse_rtpmap(AVFormatContext *s,
231 AVStream *st, RTSPStream *rtsp_st,
232 int payload_type, const char *p)
233 {
234 AVCodecContext *codec = st->codec;
235 char buf[256];
236 int i;
237 AVCodec *c;
238 const char *c_name;
239
240 /* See if we can handle this kind of payload.
241 * The space should normally not be there but some Real streams or
242 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
243 * have a trailing space. */
244 get_word_sep(buf, sizeof(buf), "/ ", &p);
245 if (payload_type < RTP_PT_PRIVATE) {
246 /* We are in a standard case
247 * (from http://www.iana.org/assignments/rtp-parameters). */
248 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
249 }
250
251 if (codec->codec_id == AV_CODEC_ID_NONE) {
252 RTPDynamicProtocolHandler *handler =
253 ff_rtp_handler_find_by_name(buf, codec->codec_type);
254 init_rtp_handler(handler, rtsp_st, st);
255 /* If no dynamic handler was found, check with the list of standard
256 * allocated types, if such a stream for some reason happens to
257 * use a private payload type. This isn't handled in rtpdec.c, since
258 * the format name from the rtpmap line never is passed into rtpdec. */
259 if (!rtsp_st->dynamic_handler)
260 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
261 }
262
263 c = avcodec_find_decoder(codec->codec_id);
264 if (c && c->name)
265 c_name = c->name;
266 else
267 c_name = "(null)";
268
269 get_word_sep(buf, sizeof(buf), "/", &p);
270 i = atoi(buf);
271 switch (codec->codec_type) {
272 case AVMEDIA_TYPE_AUDIO:
273 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
274 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
275 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
276 if (i > 0) {
277 codec->sample_rate = i;
278 avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
279 get_word_sep(buf, sizeof(buf), "/", &p);
280 i = atoi(buf);
281 if (i > 0)
282 codec->channels = i;
283 }
284 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
285 codec->sample_rate);
286 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
287 codec->channels);
288 break;
289 case AVMEDIA_TYPE_VIDEO:
290 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
291 if (i > 0)
292 avpriv_set_pts_info(st, 32, 1, i);
293 break;
294 default:
295 break;
296 }
297 finalize_rtp_handler_init(s, rtsp_st, st);
298 return 0;
299 }
300
301 /* parse the attribute line from the fmtp a line of an sdp response. This
302 * is broken out as a function because it is used in rtp_h264.c, which is
303 * forthcoming. */
304 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
305 char *value, int value_size)
306 {
307 *p += strspn(*p, SPACE_CHARS);
308 if (**p) {
309 get_word_sep(attr, attr_size, "=", p);
310 if (**p == '=')
311 (*p)++;
312 get_word_sep(value, value_size, ";", p);
313 if (**p == ';')
314 (*p)++;
315 return 1;
316 }
317 return 0;
318 }
319
320 typedef struct SDPParseState {
321 /* SDP only */
322 struct sockaddr_storage default_ip;
323 int default_ttl;
324 int skip_media; ///< set if an unknown m= line occurs
325 int nb_default_include_source_addrs; /**< Number of source-specific multicast include source IP address (from SDP content) */
326 struct RTSPSource **default_include_source_addrs; /**< Source-specific multicast include source IP address (from SDP content) */
327 int nb_default_exclude_source_addrs; /**< Number of source-specific multicast exclude source IP address (from SDP content) */
328 struct RTSPSource **default_exclude_source_addrs; /**< Source-specific multicast exclude source IP address (from SDP content) */
329 int seen_rtpmap;
330 int seen_fmtp;
331 char delayed_fmtp[2048];
332 } SDPParseState;
333
334 static void copy_default_source_addrs(struct RTSPSource **addrs, int count,
335 struct RTSPSource ***dest, int *dest_count)
336 {
337 RTSPSource *rtsp_src, *rtsp_src2;
338 int i;
339 for (i = 0; i < count; i++) {
340 rtsp_src = addrs[i];
341 rtsp_src2 = av_malloc(sizeof(*rtsp_src2));
342 if (!rtsp_src2)
343 continue;
344 memcpy(rtsp_src2, rtsp_src, sizeof(*rtsp_src));
345 dynarray_add(dest, dest_count, rtsp_src2);
346 }
347 }
348
349 static void parse_fmtp(AVFormatContext *s, RTSPState *rt,
350 int payload_type, const char *line)
351 {
352 int i;
353
354 for (i = 0; i < rt->nb_rtsp_streams; i++) {
355 RTSPStream *rtsp_st = rt->rtsp_streams[i];
356 if (rtsp_st->sdp_payload_type == payload_type &&
357 rtsp_st->dynamic_handler &&
358 rtsp_st->dynamic_handler->parse_sdp_a_line) {
359 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
360 rtsp_st->dynamic_protocol_context, line);
361 }
362 }
363 }
364
365 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
366 int letter, const char *buf)
367 {
368 RTSPState *rt = s->priv_data;
369 char buf1[64], st_type[64];
370 const char *p;
371 enum AVMediaType codec_type;
372 int payload_type;
373 AVStream *st;
374 RTSPStream *rtsp_st;
375 RTSPSource *rtsp_src;
376 struct sockaddr_storage sdp_ip;
377 int ttl;
378
379 av_dlog(s, "sdp: %c='%s'\n", letter, buf);
380
381 p = buf;
382 if (s1->skip_media && letter != 'm')
383 return;
384 switch (letter) {
385 case 'c':
386 get_word(buf1, sizeof(buf1), &p);
387 if (strcmp(buf1, "IN") != 0)
388 return;
389 get_word(buf1, sizeof(buf1), &p);
390 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
391 return;
392 get_word_sep(buf1, sizeof(buf1), "/", &p);
393 if (get_sockaddr(buf1, &sdp_ip))
394 return;
395 ttl = 16;
396 if (*p == '/') {
397 p++;
398 get_word_sep(buf1, sizeof(buf1), "/", &p);
399 ttl = atoi(buf1);
400 }
401 if (s->nb_streams == 0) {
402 s1->default_ip = sdp_ip;
403 s1->default_ttl = ttl;
404 } else {
405 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
406 rtsp_st->sdp_ip = sdp_ip;
407 rtsp_st->sdp_ttl = ttl;
408 }
409 break;
410 case 's':
411 av_dict_set(&s->metadata, "title", p, 0);
412 break;
413 case 'i':
414 if (s->nb_streams == 0) {
415 av_dict_set(&s->metadata, "comment", p, 0);
416 break;
417 }
418 break;
419 case 'm':
420 /* new stream */
421 s1->skip_media = 0;
422 s1->seen_fmtp = 0;
423 s1->seen_rtpmap = 0;
424 codec_type = AVMEDIA_TYPE_UNKNOWN;
425 get_word(st_type, sizeof(st_type), &p);
426 if (!strcmp(st_type, "audio")) {
427 codec_type = AVMEDIA_TYPE_AUDIO;
428 } else if (!strcmp(st_type, "video")) {
429 codec_type = AVMEDIA_TYPE_VIDEO;
430 } else if (!strcmp(st_type, "application") || !strcmp(st_type, "text")) {
431 codec_type = AVMEDIA_TYPE_DATA;
432 }
433 if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
434 s1->skip_media = 1;
435 return;
436 }
437 rtsp_st = av_mallocz(sizeof(RTSPStream));
438 if (!rtsp_st)
439 return;
440 rtsp_st->stream_index = -1;
441 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
442
443 rtsp_st->sdp_ip = s1->default_ip;
444 rtsp_st->sdp_ttl = s1->default_ttl;
445
446 copy_default_source_addrs(s1->default_include_source_addrs,
447 s1->nb_default_include_source_addrs,
448 &rtsp_st->include_source_addrs,
449 &rtsp_st->nb_include_source_addrs);
450 copy_default_source_addrs(s1->default_exclude_source_addrs,
451 s1->nb_default_exclude_source_addrs,
452 &rtsp_st->exclude_source_addrs,
453 &rtsp_st->nb_exclude_source_addrs);
454
455 get_word(buf1, sizeof(buf1), &p); /* port */
456 rtsp_st->sdp_port = atoi(buf1);
457
458 get_word(buf1, sizeof(buf1), &p); /* protocol */
459 if (!strcmp(buf1, "udp"))
460 rt->transport = RTSP_TRANSPORT_RAW;
461 else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))
462 rtsp_st->feedback = 1;
463
464 /* XXX: handle list of formats */
465 get_word(buf1, sizeof(buf1), &p); /* format list */
466 rtsp_st->sdp_payload_type = atoi(buf1);
467
468 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
469 /* no corresponding stream */
470 if (rt->transport == RTSP_TRANSPORT_RAW) {
471 if (CONFIG_RTPDEC && !rt->ts)
472 rt->ts = ff_mpegts_parse_open(s);
473 } else {
474 RTPDynamicProtocolHandler *handler;
475 handler = ff_rtp_handler_find_by_id(
476 rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);
477 init_rtp_handler(handler, rtsp_st, NULL);
478 finalize_rtp_handler_init(s, rtsp_st, NULL);
479 }
480 } else if (rt->server_type == RTSP_SERVER_WMS &&
481 codec_type == AVMEDIA_TYPE_DATA) {
482 /* RTX stream, a stream that carries all the other actual
483 * audio/video streams. Don't expose this to the callers. */
484 } else {
485 st = avformat_new_stream(s, NULL);
486 if (!st)
487 return;
488 st->id = rt->nb_rtsp_streams - 1;
489 rtsp_st->stream_index = st->index;
490 st->codec->codec_type = codec_type;
491 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
492 RTPDynamicProtocolHandler *handler;
493 /* if standard payload type, we can find the codec right now */
494 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
495 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
496 st->codec->sample_rate > 0)
497 avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
498 /* Even static payload types may need a custom depacketizer */
499 handler = ff_rtp_handler_find_by_id(
500 rtsp_st->sdp_payload_type, st->codec->codec_type);
501 init_rtp_handler(handler, rtsp_st, st);
502 finalize_rtp_handler_init(s, rtsp_st, st);
503 }
504 if (rt->default_lang[0])
505 av_dict_set(&st->metadata, "language", rt->default_lang, 0);
506 }
507 /* put a default control url */
508 av_strlcpy(rtsp_st->control_url, rt->control_uri,
509 sizeof(rtsp_st->control_url));
510 break;
511 case 'a':
512 if (av_strstart(p, "control:", &p)) {
513 if (s->nb_streams == 0) {
514 if (!strncmp(p, "rtsp://", 7))
515 av_strlcpy(rt->control_uri, p,
516 sizeof(rt->control_uri));
517 } else {
518 char proto[32];
519 /* get the control url */
520 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
521
522 /* XXX: may need to add full url resolution */
523 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
524 NULL, NULL, 0, p);
525 if (proto[0] == '\0') {
526 /* relative control URL */
527 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
528 av_strlcat(rtsp_st->control_url, "/",
529 sizeof(rtsp_st->control_url));
530 av_strlcat(rtsp_st->control_url, p,
531 sizeof(rtsp_st->control_url));
532 } else
533 av_strlcpy(rtsp_st->control_url, p,
534 sizeof(rtsp_st->control_url));
535 }
536 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
537 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
538 get_word(buf1, sizeof(buf1), &p);
539 payload_type = atoi(buf1);
540 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
541 if (rtsp_st->stream_index >= 0) {
542 st = s->streams[rtsp_st->stream_index];
543 sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
544 }
545 s1->seen_rtpmap = 1;
546 if (s1->seen_fmtp) {
547 parse_fmtp(s, rt, payload_type, s1->delayed_fmtp);
548 }
549 } else if (av_strstart(p, "fmtp:", &p) ||
550 av_strstart(p, "framesize:", &p)) {
551 // let dynamic protocol handlers have a stab at the line.
552 get_word(buf1, sizeof(buf1), &p);
553 payload_type = atoi(buf1);
554 if (s1->seen_rtpmap) {
555 parse_fmtp(s, rt, payload_type, buf);
556 } else {
557 s1->seen_fmtp = 1;
558 av_strlcpy(s1->delayed_fmtp, buf, sizeof(s1->delayed_fmtp));
559 }
560 } else if (av_strstart(p, "range:", &p)) {
561 int64_t start, end;
562
563 // this is so that seeking on a streamed file can work.
564 rtsp_parse_range_npt(p, &start, &end);
565 s->start_time = start;
566 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
567 s->duration = (end == AV_NOPTS_VALUE) ?
568 AV_NOPTS_VALUE : end - start;
569 } else if (av_strstart(p, "lang:", &p)) {
570 if (s->nb_streams > 0) {
571 get_word(buf1, sizeof(buf1), &p);
572 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
573 if (rtsp_st->stream_index >= 0) {
574 st = s->streams[rtsp_st->stream_index];
575 av_dict_set(&st->metadata, "language", buf1, 0);
576 }
577 } else
578 get_word(rt->default_lang, sizeof(rt->default_lang), &p);
579 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
580 if (atoi(p) == 1)
581 rt->transport = RTSP_TRANSPORT_RDT;
582 } else if (av_strstart(p, "SampleRate:integer;", &p) &&
583 s->nb_streams > 0) {
584 st = s->streams[s->nb_streams - 1];
585 st->codec->sample_rate = atoi(p);
586 } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {
587 // RFC 4568
588 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
589 get_word(buf1, sizeof(buf1), &p); // ignore tag
590 get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);
591 p += strspn(p, SPACE_CHARS);
592 if (av_strstart(p, "inline:", &p))
593 get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);
594 } else if (av_strstart(p, "source-filter:", &p)) {
595 int exclude = 0;
596 get_word(buf1, sizeof(buf1), &p);
597 if (strcmp(buf1, "incl") && strcmp(buf1, "excl"))
598 return;
599 exclude = !strcmp(buf1, "excl");
600
601 get_word(buf1, sizeof(buf1), &p);
602 if (strcmp(buf1, "IN") != 0)
603 return;
604 get_word(buf1, sizeof(buf1), &p);
605 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6") && strcmp(buf1, "*"))
606 return;
607 // not checking that the destination address actually matches or is wildcard
608 get_word(buf1, sizeof(buf1), &p);
609
610 while (*p != '\0') {
611 rtsp_src = av_mallocz(sizeof(*rtsp_src));
612 if (!rtsp_src)
613 return;
614 get_word(rtsp_src->addr, sizeof(rtsp_src->addr), &p);
615 if (exclude) {
616 if (s->nb_streams == 0) {
617 dynarray_add(&s1->default_exclude_source_addrs, &s1->nb_default_exclude_source_addrs, rtsp_src);
618 } else {
619 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
620 dynarray_add(&rtsp_st->exclude_source_addrs, &rtsp_st->nb_exclude_source_addrs, rtsp_src);
621 }
622 } else {
623 if (s->nb_streams == 0) {
624 dynarray_add(&s1->default_include_source_addrs, &s1->nb_default_include_source_addrs, rtsp_src);
625 } else {
626 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
627 dynarray_add(&rtsp_st->include_source_addrs, &rtsp_st->nb_include_source_addrs, rtsp_src);
628 }
629 }
630 }
631 } else {
632 if (rt->server_type == RTSP_SERVER_WMS)
633 ff_wms_parse_sdp_a_line(s, p);
634 if (s->nb_streams > 0) {
635 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
636
637 if (rt->server_type == RTSP_SERVER_REAL)
638 ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
639
640 if (rtsp_st->dynamic_handler &&
641 rtsp_st->dynamic_handler->parse_sdp_a_line)
642 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
643 rtsp_st->stream_index,
644 rtsp_st->dynamic_protocol_context, buf);
645 }
646 }
647 break;
648 }
649 }
650
651 int ff_sdp_parse(AVFormatContext *s, const char *content)
652 {
653 RTSPState *rt = s->priv_data;
654 const char *p;
655 int letter, i;
656 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
657 * contain long SDP lines containing complete ASF Headers (several
658 * kB) or arrays of MDPR (RM stream descriptor) headers plus
659 * "rulebooks" describing their properties. Therefore, the SDP line
660 * buffer is large.
661 *
662 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
663 * in rtpdec_xiph.c. */
664 char buf[16384], *q;
665 SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
666
667 p = content;
668 for (;;) {
669 p += strspn(p, SPACE_CHARS);
670 letter = *p;
671 if (letter == '\0')
672 break;
673 p++;
674 if (*p != '=')
675 goto next_line;
676 p++;
677 /* get the content */
678 q = buf;
679 while (*p != '\n' && *p != '\r' && *p != '\0') {
680 if ((q - buf) < sizeof(buf) - 1)
681 *q++ = *p;
682 p++;
683 }
684 *q = '\0';
685 sdp_parse_line(s, s1, letter, buf);
686 next_line:
687 while (*p != '\n' && *p != '\0')
688 p++;
689 if (*p == '\n')
690 p++;
691 }
692
693 for (i = 0; i < s1->nb_default_include_source_addrs; i++)
694 av_free(s1->default_include_source_addrs[i]);
695 av_freep(&s1->default_include_source_addrs);
696 for (i = 0; i < s1->nb_default_exclude_source_addrs; i++)
697 av_free(s1->default_exclude_source_addrs[i]);
698 av_freep(&s1->default_exclude_source_addrs);
699
700 rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
701 if (!rt->p) return AVERROR(ENOMEM);
702 return 0;
703 }
704 #endif /* CONFIG_RTPDEC */
705
706 void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)
707 {
708 RTSPState *rt = s->priv_data;
709 int i;
710
711 for (i = 0; i < rt->nb_rtsp_streams; i++) {
712 RTSPStream *rtsp_st = rt->rtsp_streams[i];
713 if (!rtsp_st)
714 continue;
715 if (rtsp_st->transport_priv) {
716 if (s->oformat) {
717 AVFormatContext *rtpctx = rtsp_st->transport_priv;
718 av_write_trailer(rtpctx);
719 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
720 if (CONFIG_RTSP_MUXER && rtpctx->pb && send_packets)
721 ff_rtsp_tcp_write_packet(s, rtsp_st);
722 ffio_free_dyn_buf(&rtpctx->pb);
723 } else {
724 avio_close(rtpctx->pb);
725 }
726 avformat_free_context(rtpctx);
727 } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)
728 ff_rdt_parse_close(rtsp_st->transport_priv);
729 else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP)
730 ff_rtp_parse_close(rtsp_st->transport_priv);
731 }
732 rtsp_st->transport_priv = NULL;
733 if (rtsp_st->rtp_handle)
734 ffurl_close(rtsp_st->rtp_handle);
735 rtsp_st->rtp_handle = NULL;
736 }
737 }
738
739 /* close and free RTSP streams */
740 void ff_rtsp_close_streams(AVFormatContext *s)
741 {
742 RTSPState *rt = s->priv_data;
743 int i, j;
744 RTSPStream *rtsp_st;
745
746 ff_rtsp_undo_setup(s, 0);
747 for (i = 0; i < rt->nb_rtsp_streams; i++) {
748 rtsp_st = rt->rtsp_streams[i];
749 if (rtsp_st) {
750 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context) {
751 if (rtsp_st->dynamic_handler->close)
752 rtsp_st->dynamic_handler->close(
753 rtsp_st->dynamic_protocol_context);
754 av_free(rtsp_st->dynamic_protocol_context);
755 }
756 for (j = 0; j < rtsp_st->nb_include_source_addrs; j++)
757 av_free(rtsp_st->include_source_addrs[j]);
758 av_freep(&rtsp_st->include_source_addrs);
759 for (j = 0; j < rtsp_st->nb_exclude_source_addrs; j++)
760 av_free(rtsp_st->exclude_source_addrs[j]);
761 av_freep(&rtsp_st->exclude_source_addrs);
762
763 av_free(rtsp_st);
764 }
765 }
766 av_free(rt->rtsp_streams);
767 if (rt->asf_ctx) {
768 avformat_close_input(&rt->asf_ctx);
769 }
770 if (CONFIG_RTPDEC && rt->ts)
771 ff_mpegts_parse_close(rt->ts);
772 av_free(rt->p);
773 av_free(rt->recvbuf);
774 }
775
776 int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
777 {
778 RTSPState *rt = s->priv_data;
779 AVStream *st = NULL;
780 int reordering_queue_size = rt->reordering_queue_size;
781 if (reordering_queue_size < 0) {
782 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
783 reordering_queue_size = 0;
784 else
785 reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
786 }
787
788 /* open the RTP context */
789 if (rtsp_st->stream_index >= 0)
790 st = s->streams[rtsp_st->stream_index];
791 if (!st)
792 s->ctx_flags |= AVFMTCTX_NOHEADER;
793
794 if (CONFIG_RTSP_MUXER && s->oformat) {
795 int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv,
796 s, st, rtsp_st->rtp_handle,
797 RTSP_TCP_MAX_PACKET_SIZE,
798 rtsp_st->stream_index);
799 /* Ownership of rtp_handle is passed to the rtp mux context */
800 rtsp_st->rtp_handle = NULL;
801 if (ret < 0)
802 return ret;
803 st->time_base = ((AVFormatContext*)rtsp_st->transport_priv)->streams[0]->time_base;
804 } else if (rt->transport == RTSP_TRANSPORT_RAW) {
805 return 0; // Don't need to open any parser here
806 } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)
807 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
808 rtsp_st->dynamic_protocol_context,
809 rtsp_st->dynamic_handler);
810 else if (CONFIG_RTPDEC)
811 rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
812 rtsp_st->sdp_payload_type,
813 reordering_queue_size);
814
815 if (!rtsp_st->transport_priv) {
816 return AVERROR(ENOMEM);
817 } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP) {
818 if (rtsp_st->dynamic_handler) {
819 ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
820 rtsp_st->dynamic_protocol_context,
821 rtsp_st->dynamic_handler);
822 }
823 if (rtsp_st->crypto_suite[0])
824 ff_rtp_parse_set_crypto(rtsp_st->transport_priv,
825 rtsp_st->crypto_suite,
826 rtsp_st->crypto_params);
827 }
828
829 return 0;
830 }
831
832 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
833 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
834 {
835 const char *q;
836 char *p;
837 int v;
838
839 q = *pp;
840 q += strspn(q, SPACE_CHARS);
841 v = strtol(q, &p, 10);
842 if (*p == '-') {
843 p++;
844 *min_ptr = v;
845 v = strtol(p, &p, 10);
846 *max_ptr = v;
847 } else {
848 *min_ptr = v;
849 *max_ptr = v;
850 }
851 *pp = p;
852 }
853
854 /* XXX: only one transport specification is parsed */
855 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
856 {
857 char transport_protocol[16];
858 char profile[16];
859 char lower_transport[16];
860 char parameter[16];
861 RTSPTransportField *th;
862 char buf[256];
863
864 reply->nb_transports = 0;
865
866 for (;;) {
867 p += strspn(p, SPACE_CHARS);
868 if (*p == '\0')
869 break;
870
871 th = &reply->transports[reply->nb_transports];
872
873 get_word_sep(transport_protocol, sizeof(transport_protocol),
874 "/", &p);
875 if (!av_strcasecmp (transport_protocol, "rtp")) {
876 get_word_sep(profile, sizeof(profile), "/;,", &p);
877 lower_transport[0] = '\0';
878 /* rtp/avp/<protocol> */
879 if (*p == '/') {
880 get_word_sep(lower_transport, sizeof(lower_transport),
881 ";,", &p);
882 }
883 th->transport = RTSP_TRANSPORT_RTP;
884 } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
885 !av_strcasecmp (transport_protocol, "x-real-rdt")) {
886 /* x-pn-tng/<protocol> */
887 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
888 profile[0] = '\0';
889 th->transport = RTSP_TRANSPORT_RDT;
890 } else if (!av_strcasecmp(transport_protocol, "raw")) {
891 get_word_sep(profile, sizeof(profile), "/;,", &p);
892 lower_transport[0] = '\0';
893 /* raw/raw/<protocol> */
894 if (*p == '/') {
895 get_word_sep(lower_transport, sizeof(lower_transport),
896 ";,", &p);
897 }
898 th->transport = RTSP_TRANSPORT_RAW;
899 }
900 if (!av_strcasecmp(lower_transport, "TCP"))
901 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
902 else
903 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
904
905 if (*p == ';')
906 p++;
907 /* get each parameter */
908 while (*p != '\0' && *p != ',') {
909 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
910 if (!strcmp(parameter, "port")) {
911 if (*p == '=') {
912 p++;
913 rtsp_parse_range(&th->port_min, &th->port_max, &p);
914 }
915 } else if (!strcmp(parameter, "client_port")) {
916 if (*p == '=') {
917 p++;
918 rtsp_parse_range(&th->client_port_min,
919 &th->client_port_max, &p);
920 }
921 } else if (!strcmp(parameter, "server_port")) {
922 if (*p == '=') {
923 p++;
924 rtsp_parse_range(&th->server_port_min,
925 &th->server_port_max, &p);
926 }
927 } else if (!strcmp(parameter, "interleaved")) {
928 if (*p == '=') {
929 p++;
930 rtsp_parse_range(&th->interleaved_min,
931 &th->interleaved_max, &p);
932 }
933 } else if (!strcmp(parameter, "multicast")) {
934 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
935 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
936 } else if (!strcmp(parameter, "ttl")) {
937 if (*p == '=') {
938 char *end;
939 p++;
940 th->ttl = strtol(p, &end, 10);
941 p = end;
942 }
943 } else if (!strcmp(parameter, "destination")) {
944 if (*p == '=') {
945 p++;
946 get_word_sep(buf, sizeof(buf), ";,", &p);
947 get_sockaddr(buf, &th->destination);
948 }
949 } else if (!strcmp(parameter, "source")) {
950 if (*p == '=') {
951 p++;
952 get_word_sep(buf, sizeof(buf), ";,", &p);
953 av_strlcpy(th->source, buf, sizeof(th->source));
954 }
955 } else if (!strcmp(parameter, "mode")) {
956 if (*p == '=') {
957 p++;
958 get_word_sep(buf, sizeof(buf), ";, ", &p);
959 if (!strcmp(buf, "record") ||
960 !strcmp(buf, "receive"))
961 th->mode_record = 1;
962 }
963 }
964
965 while (*p != ';' && *p != '\0' && *p != ',')
966 p++;
967 if (*p == ';')
968 p++;
969 }
970 if (*p == ',')
971 p++;
972
973 reply->nb_transports++;
974 }
975 }
976
977 static void handle_rtp_info(RTSPState *rt, const char *url,
978 uint32_t seq, uint32_t rtptime)
979 {
980 int i;
981 if (!rtptime || !url[0])
982 return;
983 if (rt->transport != RTSP_TRANSPORT_RTP)
984 return;
985 for (i = 0; i < rt->nb_rtsp_streams; i++) {
986 RTSPStream *rtsp_st = rt->rtsp_streams[i];
987 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
988 if (!rtpctx)
989 continue;
990 if (!strcmp(rtsp_st->control_url, url)) {
991 rtpctx->base_timestamp = rtptime;
992 break;
993 }
994 }
995 }
996
997 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
998 {
999 int read = 0;
1000 char key[20], value[1024], url[1024] = "";
1001 uint32_t seq = 0, rtptime = 0;
1002
1003 for (;;) {
1004 p += strspn(p, SPACE_CHARS);
1005 if (!*p)
1006 break;
1007 get_word_sep(key, sizeof(key), "=", &p);
1008 if (*p != '=')
1009 break;
1010 p++;
1011 get_word_sep(value, sizeof(value), ";, ", &p);
1012 read++;
1013 if (!strcmp(key, "url"))
1014 av_strlcpy(url, value, sizeof(url));
1015 else if (!strcmp(key, "seq"))
1016 seq = strtoul(value, NULL, 10);
1017 else if (!strcmp(key, "rtptime"))
1018 rtptime = strtoul(value, NULL, 10);
1019 if (*p == ',') {
1020 handle_rtp_info(rt, url, seq, rtptime);
1021 url[0] = '\0';
1022 seq = rtptime = 0;
1023 read = 0;
1024 }
1025 if (*p)
1026 p++;
1027 }
1028 if (read > 0)
1029 handle_rtp_info(rt, url, seq, rtptime);
1030 }
1031
1032 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
1033 RTSPState *rt, const char *method)
1034 {
1035 const char *p;
1036
1037 /* NOTE: we do case independent match for broken servers */
1038 p = buf;
1039 if (av_stristart(p, "Session:", &p)) {
1040 int t;
1041 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
1042 if (av_stristart(p, ";timeout=", &p) &&
1043 (t = strtol(p, NULL, 10)) > 0) {
1044 reply->timeout = t;
1045 }
1046 } else if (av_stristart(p, "Content-Length:", &p)) {
1047 reply->content_length = strtol(p, NULL, 10);
1048 } else if (av_stristart(p, "Transport:", &p)) {
1049 rtsp_parse_transport(reply, p);
1050 } else if (av_stristart(p, "CSeq:", &p)) {
1051 reply->seq = strtol(p, NULL, 10);
1052 } else if (av_stristart(p, "Range:", &p)) {
1053 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
1054 } else if (av_stristart(p, "RealChallenge1:", &p)) {
1055 p += strspn(p, SPACE_CHARS);
1056 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
1057 } else if (av_stristart(p, "Server:", &p)) {
1058 p += strspn(p, SPACE_CHARS);
1059 av_strlcpy(reply->server, p, sizeof(reply->server));
1060 } else if (av_stristart(p, "Notice:", &p) ||
1061 av_stristart(p, "X-Notice:", &p)) {
1062 reply->notice = strtol(p, NULL, 10);
1063 } else if (av_stristart(p, "Location:", &p)) {
1064 p += strspn(p, SPACE_CHARS);
1065 av_strlcpy(reply->location, p , sizeof(reply->location));
1066 } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
1067 p += strspn(p, SPACE_CHARS);
1068 ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
1069 } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
1070 p += strspn(p, SPACE_CHARS);
1071 ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
1072 } else if (av_stristart(p, "Content-Base:", &p) && rt) {
1073 p += strspn(p, SPACE_CHARS);
1074 if (method && !strcmp(method, "DESCRIBE"))
1075 av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
1076 } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
1077 p += strspn(p, SPACE_CHARS);
1078 if (method && !strcmp(method, "PLAY"))
1079 rtsp_parse_rtp_info(rt, p);
1080 } else if (av_stristart(p, "Public:", &p) && rt) {
1081 if (strstr(p, "GET_PARAMETER") &&
1082 method && !strcmp(method, "OPTIONS"))
1083 rt->get_parameter_supported = 1;
1084 } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
1085 p += strspn(p, SPACE_CHARS);
1086 rt->accept_dynamic_rate = atoi(p);
1087 } else if (av_stristart(p, "Content-Type:", &p)) {
1088 p += strspn(p, SPACE_CHARS);
1089 av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
1090 }
1091 }
1092
1093 /* skip a RTP/TCP interleaved packet */
1094 void ff_rtsp_skip_packet(AVFormatContext *s)
1095 {
1096 RTSPState *rt = s->priv_data;
1097 int ret, len, len1;
1098 uint8_t buf[1024];
1099
1100 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
1101 if (ret != 3)
1102 return;
1103 len = AV_RB16(buf + 1);
1104
1105 av_dlog(s, "skipping RTP packet len=%d\n", len);
1106
1107 /* skip payload */
1108 while (len > 0) {
1109 len1 = len;
1110 if (len1 > sizeof(buf))
1111 len1 = sizeof(buf);
1112 ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
1113 if (ret != len1)
1114 return;
1115 len -= len1;
1116 }
1117 }
1118
1119 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
1120 unsigned char **content_ptr,
1121 int return_on_interleaved_data, const char *method)
1122 {
1123 RTSPState *rt = s->priv_data;
1124 char buf[4096], buf1[1024], *q;
1125 unsigned char ch;
1126 const char *p;
1127 int ret, content_length, line_count = 0, request = 0;
1128 unsigned char *content = NULL;
1129
1130 start:
1131 line_count = 0;
1132 request = 0;
1133 content = NULL;
1134 memset(reply, 0, sizeof(*reply));
1135
1136 /* parse reply (XXX: use buffers) */
1137 rt->last_reply[0] = '\0';
1138 for (;;) {
1139 q = buf;
1140 for (;;) {
1141 ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
1142 av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
1143 if (ret != 1)
1144 return AVERROR_EOF;
1145 if (ch == '\n')
1146 break;
1147 if (ch == '$') {
1148 /* XXX: only parse it if first char on line ? */
1149 if (return_on_interleaved_data) {
1150 return 1;
1151 } else
1152 ff_rtsp_skip_packet(s);
1153 } else if (ch != '\r') {
1154 if ((q - buf) < sizeof(buf) - 1)
1155 *q++ = ch;
1156 }
1157 }
1158 *q = '\0';
1159
1160 av_dlog(s, "line='%s'\n", buf);
1161
1162 /* test if last line */
1163 if (buf[0] == '\0')
1164 break;
1165 p = buf;
1166 if (line_count == 0) {
1167 /* get reply code */
1168 get_word(buf1, sizeof(buf1), &p);
1169 if (!strncmp(buf1, "RTSP/", 5)) {
1170 get_word(buf1, sizeof(buf1), &p);
1171 reply->status_code = atoi(buf1);
1172 av_strlcpy(reply->reason, p, sizeof(reply->reason));
1173 } else {
1174 av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
1175 get_word(buf1, sizeof(buf1), &p); // object
1176 request = 1;
1177 }
1178 } else {
1179 ff_rtsp_parse_line(reply, p, rt, method);
1180 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
1181 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1182 }
1183 line_count++;
1184 }
1185
1186 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
1187 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
1188
1189 content_length = reply->content_length;
1190 if (content_length > 0) {
1191 /* leave some room for a trailing '\0' (useful for simple parsing) */
1192 content = av_malloc(content_length + 1);
1193 if (!content)
1194 return AVERROR(ENOMEM);
1195 ffurl_read_complete(rt->rtsp_hd, content, content_length);
1196 content[content_length] = '\0';
1197 }
1198 if (content_ptr)
1199 *content_ptr = content;
1200 else
1201 av_free(content);
1202
1203 if (request) {
1204 char buf[1024];
1205 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1206 const char* ptr = buf;
1207
1208 if (!strcmp(reply->reason, "OPTIONS")) {
1209 snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
1210 if (reply->seq)
1211 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1212 if (reply->session_id[0])
1213 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1214 reply->session_id);
1215 } else {
1216 snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1217 }
1218 av_strlcat(buf, "\r\n", sizeof(buf));
1219
1220 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1221 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1222 ptr = base64buf;
1223 }
1224 ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1225
1226 rt->last_cmd_time = av_gettime_relative();
1227 /* Even if the request from the server had data, it is not the data
1228 * that the caller wants or expects. The memory could also be leaked
1229 * if the actual following reply has content data. */
1230 if (content_ptr)
1231 av_freep(content_ptr);
1232 /* If method is set, this is called from ff_rtsp_send_cmd,
1233 * where a reply to exactly this request is awaited. For
1234 * callers from within packet receiving, we just want to
1235 * return to the caller and go back to receiving packets. */
1236 if (method)
1237 goto start;
1238 return 0;
1239 }
1240
1241 if (rt->seq != reply->seq) {
1242 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1243 rt->seq, reply->seq);
1244 }
1245
1246 /* EOS */
1247 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
1248 reply->notice == 2104 /* Start-of-Stream Reached */ ||
1249 reply->notice == 2306 /* Continuous Feed Terminated */) {
1250 rt->state = RTSP_STATE_IDLE;
1251 } else if (reply->notice >= 4400 && reply->notice < 5500) {
1252 return AVERROR(EIO); /* data or server error */
1253 } else if (reply->notice == 2401 /* Ticket Expired */ ||
1254 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1255 return AVERROR(EPERM);
1256
1257 return 0;
1258 }
1259
1260 /**
1261 * Send a command to the RTSP server without waiting for the reply.
1262 *
1263 * @param s RTSP (de)muxer context
1264 * @param method the method for the request
1265 * @param url the target url for the request
1266 * @param headers extra header lines to include in the request
1267 * @param send_content if non-null, the data to send as request body content
1268 * @param send_content_length the length of the send_content data, or 0 if
1269 * send_content is null
1270 *
1271 * @return zero if success, nonzero otherwise
1272 */
1273 static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
1274 const char *method, const char *url,
1275 const char *headers,
1276 const unsigned char *send_content,
1277 int send_content_length)
1278 {
1279 RTSPState *rt = s->priv_data;
1280 char buf[4096], *out_buf;
1281 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1282
1283 /* Add in RTSP headers */
1284 out_buf = buf;
1285 rt->seq++;
1286 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1287 if (headers)
1288 av_strlcat(buf, headers, sizeof(buf));
1289 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1290 av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
1291 if (rt->session_id[0] != '\0' && (!headers ||
1292 !strstr(headers, "\nIf-Match:"))) {
1293 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
1294 }
1295 if (rt->auth[0]) {
1296 char *str = ff_http_auth_create_response(&rt->auth_state,
1297 rt->auth, url, method);
1298 if (str)
1299 av_strlcat(buf, str, sizeof(buf));
1300 av_free(str);
1301 }
1302 if (send_content_length > 0 && send_content)
1303 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
1304 av_strlcat(buf, "\r\n", sizeof(buf));
1305
1306 /* base64 encode rtsp if tunneling */
1307 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1308 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1309 out_buf = base64buf;
1310 }
1311
1312 av_dlog(s, "Sending:\n%s--\n", buf);
1313
1314 ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1315 if (send_content_length > 0 && send_content) {
1316 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1317 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1318 "with content data not supported\n");
1319 return AVERROR_PATCHWELCOME;
1320 }
1321 ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
1322 }
1323 rt->last_cmd_time = av_gettime_relative();
1324
1325 return 0;
1326 }
1327
1328 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1329 const char *url, const char *headers)
1330 {
1331 return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1332 }
1333
1334 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1335 const char *headers, RTSPMessageHeader *reply,
1336 unsigned char **content_ptr)
1337 {
1338 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1339 content_ptr, NULL, 0);
1340 }
1341
1342 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1343 const char *method, const char *url,
1344 const char *header,
1345 RTSPMessageHeader *reply,
1346 unsigned char **content_ptr,
1347 const unsigned char *send_content,
1348 int send_content_length)
1349 {
1350 RTSPState *rt = s->priv_data;
1351 HTTPAuthType cur_auth_type;
1352 int ret, attempts = 0;
1353
1354 retry:
1355 cur_auth_type = rt->auth_state.auth_type;
1356 if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
1357 send_content,
1358 send_content_length)))
1359 return ret;
1360
1361 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
1362 return ret;
1363 attempts++;
1364
1365 if (reply->status_code == 401 &&
1366 (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1367 rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
1368 goto retry;
1369
1370 if (reply->status_code > 400){
1371 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
1372 method,
1373 reply->status_code,
1374 reply->reason);
1375 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1376 }
1377
1378 return 0;
1379 }
1380
1381 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
1382 int lower_transport, const char *real_challenge)
1383 {
1384 RTSPState *rt = s->priv_data;
1385 int rtx = 0, j, i, err, interleave = 0, port_off;
1386 RTSPStream *rtsp_st;
1387 RTSPMessageHeader reply1, *reply = &reply1;
1388 char cmd[2048];
1389 const char *trans_pref;
1390
1391 if (rt->transport == RTSP_TRANSPORT_RDT)
1392 trans_pref = "x-pn-tng";
1393 else if (rt->transport == RTSP_TRANSPORT_RAW)
1394 trans_pref = "RAW/RAW";
1395 else
1396 trans_pref = "RTP/AVP";
1397
1398 /* default timeout: 1 minute */
1399 rt->timeout = 60;
1400
1401 /* for each stream, make the setup request */
1402 /* XXX: we assume the same server is used for the control of each
1403 * RTSP stream */
1404
1405 /* Choose a random starting offset within the first half of the
1406 * port range, to allow for a number of ports to try even if the offset
1407 * happens to be at the end of the random range. */
1408 port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1409 /* even random offset */
1410 port_off -= port_off & 0x01;
1411
1412 for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1413 char transport[2048];
1414
1415 /*
1416 * WMS serves all UDP data over a single connection, the RTX, which
1417 * isn't necessarily the first in the SDP but has to be the first
1418 * to be set up, else the second/third SETUP will fail with a 461.
1419 */
1420 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1421 rt->server_type == RTSP_SERVER_WMS) {
1422 if (i == 0) {
1423 /* rtx first */
1424 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1425 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1426 if (len >= 4 &&
1427 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1428 "/rtx"))
1429 break;
1430 }
1431 if (rtx == rt->nb_rtsp_streams)
1432 return -1; /* no RTX found */
1433 rtsp_st = rt->rtsp_streams[rtx];
1434 } else
1435 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1436 } else
1437 rtsp_st = rt->rtsp_streams[i];
1438
1439 /* RTP/UDP */
1440 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1441 char buf[256];
1442
1443 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1444 port = reply->transports[0].client_port_min;
1445 goto have_port;
1446 }
1447
1448 /* first try in specified port range */
1449 while (j <= rt->rtp_port_max) {
1450 AVDictionary *opts = map_to_opts(rt);
1451
1452 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1453 "?localport=%d", j);
1454 /* we will use two ports per rtp stream (rtp and rtcp) */
1455 j += 2;
1456 err = ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1457 &s->interrupt_callback, &opts);
1458
1459 av_dict_free(&opts);
1460
1461 if (!err)
1462 goto rtp_opened;
1463 }
1464
1465 av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1466 err = AVERROR(EIO);
1467 goto fail;
1468
1469 rtp_opened:
1470 port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1471 have_port:
1472 snprintf(transport, sizeof(transport) - 1,
1473 "%s/UDP;", trans_pref);
1474 if (rt->server_type != RTSP_SERVER_REAL)
1475 av_strlcat(transport, "unicast;", sizeof(transport));
1476 av_strlcatf(transport, sizeof(transport),
1477 "client_port=%d", port);
1478 if (rt->transport == RTSP_TRANSPORT_RTP &&
1479 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1480 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1481 }
1482
1483 /* RTP/TCP */
1484 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1485 /* For WMS streams, the application streams are only used for
1486 * UDP. When trying to set it up for TCP streams, the server
1487 * will return an error. Therefore, we skip those streams. */
1488 if (rt->server_type == RTSP_SERVER_WMS &&
1489 (rtsp_st->stream_index < 0 ||
1490 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1491 AVMEDIA_TYPE_DATA))
1492 continue;
1493 snprintf(transport, sizeof(transport) - 1,
1494 "%s/TCP;", trans_pref);
1495 if (rt->transport != RTSP_TRANSPORT_RDT)
1496 av_strlcat(transport, "unicast;", sizeof(transport));
1497 av_strlcatf(transport, sizeof(transport),
1498 "interleaved=%d-%d",
1499 interleave, interleave + 1);
1500 interleave += 2;
1501 }
1502
1503 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1504 snprintf(transport, sizeof(transport) - 1,
1505 "%s/UDP;multicast", trans_pref);
1506 }
1507 if (s->oformat) {
1508 av_strlcat(transport, ";mode=record", sizeof(transport));
1509 } else if (rt->server_type == RTSP_SERVER_REAL ||
1510 rt->server_type == RTSP_SERVER_WMS)
1511 av_strlcat(transport, ";mode=play", sizeof(transport));
1512 snprintf(cmd, sizeof(cmd),
1513 "Transport: %s\r\n",
1514 transport);
1515 if (rt->accept_dynamic_rate)
1516 av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
1517 if (CONFIG_RTPDEC && i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1518 char real_res[41], real_csum[9];
1519 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1520 real_challenge);
1521 av_strlcatf(cmd, sizeof(cmd),
1522 "If-Match: %s\r\n"
1523 "RealChallenge2: %s, sd=%s\r\n",
1524 rt->session_id, real_res, real_csum);
1525 }
1526 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1527 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1528 err = 1;
1529 goto fail;
1530 } else if (reply->status_code != RTSP_STATUS_OK ||
1531 reply->nb_transports != 1) {
1532 err = AVERROR_INVALIDDATA;
1533 goto fail;
1534 }
1535
1536 /* XXX: same protocol for all streams is required */
1537 if (i > 0) {
1538 if (reply->transports[0].lower_transport != rt->lower_transport ||
1539 reply->transports[0].transport != rt->transport) {
1540 err = AVERROR_INVALIDDATA;
1541 goto fail;
1542 }
1543 } else {
1544 rt->lower_transport = reply->transports[0].lower_transport;
1545 rt->transport = reply->transports[0].transport;
1546 }
1547
1548 /* Fail if the server responded with another lower transport mode
1549 * than what we requested. */
1550 if (reply->transports[0].lower_transport != lower_transport) {
1551 av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1552 err = AVERROR_INVALIDDATA;
1553 goto fail;
1554 }
1555
1556 switch(reply->transports[0].lower_transport) {
1557 case RTSP_LOWER_TRANSPORT_TCP:
1558 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1559 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1560 break;
1561
1562 case RTSP_LOWER_TRANSPORT_UDP: {
1563 char url[1024], options[30] = "";
1564 const char *peer = host;
1565
1566 if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
1567 av_strlcpy(options, "?connect=1", sizeof(options));
1568 /* Use source address if specified */
1569 if (reply->transports[0].source[0])
1570 peer = reply->transports[0].source;
1571 ff_url_join(url, sizeof(url), "rtp", NULL, peer,
1572 reply->transports[0].server_port_min, "%s", options);
1573 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1574 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1575 err = AVERROR_INVALIDDATA;
1576 goto fail;
1577 }
1578 break;
1579 }
1580 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1581 char url[1024], namebuf[50], optbuf[20] = "";
1582 struct sockaddr_storage addr;
1583 int port, ttl;
1584
1585 if (reply->transports[0].destination.ss_family) {
1586 addr = reply->transports[0].destination;
1587 port = reply->transports[0].port_min;
1588 ttl = reply->transports[0].ttl;
1589 } else {
1590 addr = rtsp_st->sdp_ip;
1591 port = rtsp_st->sdp_port;
1592 ttl = rtsp_st->sdp_ttl;
1593 }
1594 if (ttl > 0)
1595 snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
1596 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1597 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1598 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1599 port, "%s", optbuf);
1600 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
1601 &s->interrupt_callback, NULL) < 0) {
1602 err = AVERROR_INVALIDDATA;
1603 goto fail;
1604 }
1605 break;
1606 }
1607 }
1608
1609 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
1610 goto fail;
1611 }
1612
1613 if (rt->nb_rtsp_streams && reply->timeout > 0)
1614 rt->timeout = reply->timeout;
1615
1616 if (rt->server_type == RTSP_SERVER_REAL)
1617 rt->need_subscription = 1;
1618
1619 return 0;
1620
1621 fail:
1622 ff_rtsp_undo_setup(s, 0);
1623 return err;
1624 }
1625
1626 void ff_rtsp_close_connections(AVFormatContext *s)
1627 {
1628 RTSPState *rt = s->priv_data;
1629 if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1630 ffurl_close(rt->rtsp_hd);
1631 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1632 }
1633
1634 int ff_rtsp_connect(AVFormatContext *s)
1635 {
1636 RTSPState *rt = s->priv_data;
1637 char proto[128], host[1024], path[1024];
1638 char tcpname[1024], cmd[2048], auth[128];
1639 const char *lower_rtsp_proto = "tcp";
1640 int port, err, tcp_fd;
1641 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1642 int lower_transport_mask = 0;
1643 int default_port = RTSP_DEFAULT_PORT;
1644 char real_challenge[64] = "";
1645 struct sockaddr_storage peer;
1646 socklen_t peer_len = sizeof(peer);
1647
1648 if (rt->rtp_port_max < rt->rtp_port_min) {
1649 av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1650 "than min port %d\n", rt->rtp_port_max,
1651 rt->rtp_port_min);
1652 return AVERROR(EINVAL);
1653 }
1654
1655 if (!ff_network_init())
1656 return AVERROR(EIO);
1657
1658 if (s->max_delay < 0) /* Not set by the caller */
1659 s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
1660
1661 rt->control_transport = RTSP_MODE_PLAIN;
1662 if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1663 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1664 rt->control_transport = RTSP_MODE_TUNNEL;
1665 }
1666 /* Only pass through valid flags from here */
1667 rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1668
1669 redirect:
1670 /* extract hostname and port */
1671 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
1672 host, sizeof(host), &port, path, sizeof(path), s->filename);
1673
1674 if (!strcmp(proto, "rtsps")) {
1675 lower_rtsp_proto = "tls";
1676 default_port = RTSPS_DEFAULT_PORT;
1677 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1678 }
1679
1680 if (*auth) {
1681 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1682 }
1683 if (port < 0)
1684 port = default_port;
1685
1686 lower_transport_mask = rt->lower_transport_mask;
1687
1688 if (!lower_transport_mask)
1689 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1690
1691 if (s->oformat) {
1692 /* Only UDP or TCP - UDP multicast isn't supported. */
1693 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1694 (1 << RTSP_LOWER_TRANSPORT_TCP);
1695 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1696 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1697 "only UDP and TCP are supported for output.\n");
1698 err = AVERROR(EINVAL);
1699 goto fail;
1700 }
1701 }
1702
1703 /* Construct the URI used in request; this is similar to s->filename,
1704 * but with authentication credentials removed and RTSP specific options
1705 * stripped out. */
1706 ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL,
1707 host, port, "%s", path);
1708
1709 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1710 /* set up initial handshake for tunneling */
1711 char httpname[1024];
1712 char sessioncookie[17];
1713 char headers[1024];
1714
1715 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1716 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1717 av_get_random_seed(), av_get_random_seed());
1718
1719 /* GET requests */
1720 if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1721 &s->interrupt_callback) < 0) {
1722 err = AVERROR(EIO);
1723 goto fail;
1724 }
1725
1726 /* generate GET headers */
1727 snprintf(headers, sizeof(headers),
1728 "x-sessioncookie: %s\r\n"
1729 "Accept: application/x-rtsp-tunnelled\r\n"
1730 "Pragma: no-cache\r\n"
1731 "Cache-Control: no-cache\r\n",
1732 sessioncookie);
1733 av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
1734
1735 /* complete the connection */
1736 if (ffurl_connect(rt->rtsp_hd, NULL)) {
1737 err = AVERROR(EIO);
1738 goto fail;
1739 }
1740
1741 /* POST requests */
1742 if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1743 &s->interrupt_callback) < 0 ) {
1744 err = AVERROR(EIO);
1745 goto fail;
1746 }
1747
1748 /* generate POST headers */
1749 snprintf(headers, sizeof(headers),
1750 "x-sessioncookie: %s\r\n"
1751 "Content-Type: application/x-rtsp-tunnelled\r\n"
1752 "Pragma: no-cache\r\n"
1753 "Cache-Control: no-cache\r\n"
1754 "Content-Length: 32767\r\n"
1755 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1756 sessioncookie);
1757 av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
1758 av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
1759
1760 /* Initialize the authentication state for the POST session. The HTTP
1761 * protocol implementation doesn't properly handle multi-pass
1762 * authentication for POST requests, since it would require one of
1763 * the following:
1764 * - implementing Expect: 100-continue, which many HTTP servers
1765 * don't support anyway, even less the RTSP servers that do HTTP
1766 * tunneling
1767 * - sending the whole POST data until getting a 401 reply specifying
1768 * what authentication method to use, then resending all that data
1769 * - waiting for potential 401 replies directly after sending the
1770 * POST header (waiting for some unspecified time)
1771 * Therefore, we copy the full auth state, which works for both basic
1772 * and digest. (For digest, we would have to synchronize the nonce
1773 * count variable between the two sessions, if we'd do more requests
1774 * with the original session, though.)
1775 */
1776 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1777
1778 /* complete the connection */
1779 if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
1780 err = AVERROR(EIO);
1781 goto fail;
1782 }
1783 } else {
1784 /* open the tcp connection */
1785 ff_url_join(tcpname, sizeof(tcpname), lower_rtsp_proto, NULL,
1786 host, port, NULL);
1787 if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
1788 &s->interrupt_callback, NULL) < 0) {
1789 err = AVERROR(EIO);
1790 goto fail;
1791 }
1792 rt->rtsp_hd_out = rt->rtsp_hd;
1793 }
1794 rt->seq = 0;
1795
1796 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1797 if (tcp_fd < 0) {
1798 err = tcp_fd;
1799 goto fail;
1800 }
1801 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1802 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1803 NULL, 0, NI_NUMERICHOST);
1804 }
1805
1806 /* request options supported by the server; this also detects server
1807 * type */
1808 for (rt->server_type = RTSP_SERVER_RTP;;) {
1809 cmd[0] = 0;
1810 if (rt->server_type == RTSP_SERVER_REAL)
1811 av_strlcat(cmd,
1812 /*
1813 * The following entries are required for proper
1814 * streaming from a Realmedia server. They are
1815 * interdependent in some way although we currently
1816 * don't quite understand how. Values were copied
1817 * from mplayer SVN r23589.
1818 * ClientChallenge is a 16-byte ID in hex
1819 * CompanyID is a 16-byte ID in base64
1820 */
1821 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1822 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1823 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1824 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1825 sizeof(cmd));
1826 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1827 if (reply->status_code != RTSP_STATUS_OK) {
1828 err = AVERROR_INVALIDDATA;
1829 goto fail;
1830 }
1831
1832 /* detect server type if not standard-compliant RTP */
1833 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1834 rt->server_type = RTSP_SERVER_REAL;
1835 continue;
1836 } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
1837 rt->server_type = RTSP_SERVER_WMS;
1838 } else if (rt->server_type == RTSP_SERVER_REAL)
1839 strcpy(real_challenge, reply->real_challenge);
1840 break;
1841 }
1842
1843 if (CONFIG_RTSP_DEMUXER && s->iformat)
1844 err = ff_rtsp_setup_input_streams(s, reply);
1845 else if (CONFIG_RTSP_MUXER)
1846 err = ff_rtsp_setup_output_streams(s, host);
1847 if (err)
1848 goto fail;
1849
1850 do {
1851 int lower_transport = ff_log2_tab[lower_transport_mask &
1852 ~(lower_transport_mask - 1)];
1853
1854 err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
1855 rt->server_type == RTSP_SERVER_REAL ?
1856 real_challenge : NULL);
1857 if (err < 0)
1858 goto fail;
1859 lower_transport_mask &= ~(1 << lower_transport);
1860 if (lower_transport_mask == 0 && err == 1) {
1861 err = AVERROR(EPROTONOSUPPORT);
1862 goto fail;
1863 }
1864 } while (err);
1865
1866 rt->lower_transport_mask = lower_transport_mask;
1867 av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
1868 rt->state = RTSP_STATE_IDLE;
1869 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1870 return 0;
1871 fail:
1872 ff_rtsp_close_streams(s);
1873 ff_rtsp_close_connections(s);
1874 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1875 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1876 rt->session_id[0] = '\0';
1877 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1878 reply->status_code,
1879 s->filename);
1880 goto redirect;
1881 }
1882 ff_network_close();
1883 return err;
1884 }
1885 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1886
1887 #if CONFIG_RTPDEC
1888 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1889 uint8_t *buf, int buf_size, int64_t wait_end)
1890 {
1891 RTSPState *rt = s->priv_data;
1892 RTSPStream *rtsp_st;
1893 int n, i, ret, tcp_fd, timeout_cnt = 0;
1894 int max_p = 0;
1895 struct pollfd *p = rt->p;
1896 int *fds = NULL, fdsnum, fdsidx;
1897
1898 for (;;) {
1899 if (ff_check_interrupt(&s->interrupt_callback))
1900 return AVERROR_EXIT;
1901 if (wait_end && wait_end - av_gettime_relative() < 0)
1902 return AVERROR(EAGAIN);
1903 max_p = 0;
1904 if (rt->rtsp_hd) {
1905 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1906 p[max_p].fd = tcp_fd;
1907 p[max_p++].events = POLLIN;
1908 } else {
1909 tcp_fd = -1;
1910 }
1911 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1912 rtsp_st = rt->rtsp_streams[i];
1913 if (rtsp_st->rtp_handle) {
1914 if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
1915 &fds, &fdsnum)) {
1916 av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
1917 return ret;
1918 }
1919 if (fdsnum != 2) {
1920 av_log(s, AV_LOG_ERROR,
1921 "Number of fds %d not supported\n", fdsnum);
1922 return AVERROR_INVALIDDATA;
1923 }
1924 for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
1925 p[max_p].fd = fds[fdsidx];
1926 p[max_p++].events = POLLIN;
1927 }
1928 av_free(fds);
1929 }
1930 }
1931 n = poll(p, max_p, POLL_TIMEOUT_MS);
1932 if (n > 0) {
1933 int j = 1 - (tcp_fd == -1);
1934 timeout_cnt = 0;
1935 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1936 rtsp_st = rt->rtsp_streams[i];
1937 if (rtsp_st->rtp_handle) {
1938 if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
1939 ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
1940 if (ret > 0) {
1941 *prtsp_st = rtsp_st;
1942 return ret;
1943 }
1944 }
1945 j+=2;
1946 }
1947 }
1948 #if CONFIG_RTSP_DEMUXER
1949 if (tcp_fd != -1 && p[0].revents & POLLIN) {
1950 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
1951 if (rt->state == RTSP_STATE_STREAMING) {
1952 if (!ff_rtsp_parse_streaming_commands(s))
1953 return AVERROR_EOF;
1954 else
1955 av_log(s, AV_LOG_WARNING,
1956 "Unable to answer to TEARDOWN\n");
1957 } else
1958 return 0;
1959 } else {
1960 RTSPMessageHeader reply;
1961 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1962 if (ret < 0)
1963 return ret;
1964 /* XXX: parse message */
1965 if (rt->state != RTSP_STATE_STREAMING)
1966 return 0;
1967 }
1968 }
1969 #endif
1970 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1971 return AVERROR(ETIMEDOUT);
1972 } else if (n < 0 && errno != EINTR)
1973 return AVERROR(errno);
1974 }
1975 }
1976
1977 static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
1978 const uint8_t *buf, int len)
1979 {
1980 RTSPState *rt = s->priv_data;
1981 int i;
1982 if (len < 0)
1983 return len;
1984 if (rt->nb_rtsp_streams == 1) {
1985 *rtsp_st = rt->rtsp_streams[0];
1986 return len;
1987 }
1988 if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
1989 if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
1990 int no_ssrc = 0;
1991 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1992 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1993 if (!rtpctx)
1994 continue;
1995 if (rtpctx->ssrc == AV_RB32(&buf[4])) {
1996 *rtsp_st = rt->rtsp_streams[i];
1997 return len;
1998 }
1999 if (!rtpctx->ssrc)
2000 no_ssrc = 1;
2001 }
2002 if (no_ssrc) {
2003 av_log(s, AV_LOG_WARNING,
2004 "Unable to pick stream for packet - SSRC not known for "
2005 "all streams\n");
2006 return AVERROR(EAGAIN);
2007 }
2008 } else {
2009 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2010 if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
2011 *rtsp_st = rt->rtsp_streams[i];
2012 return len;
2013 }
2014 }
2015 }
2016 }
2017 av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
2018 return AVERROR(EAGAIN);
2019 }
2020
2021 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
2022 {
2023 RTSPState *rt = s->priv_data;
2024 int ret, len;
2025 RTSPStream *rtsp_st, *first_queue_st = NULL;
2026 int64_t wait_end = 0;
2027
2028 if (rt->nb_byes == rt->nb_rtsp_streams)
2029 return AVERROR_EOF;
2030
2031 /* get next frames from the same RTP packet */
2032 if (rt->cur_transport_priv) {
2033 if (rt->transport == RTSP_TRANSPORT_RDT) {
2034 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
2035 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
2036 ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
2037 } else if (CONFIG_RTPDEC && rt->ts) {
2038 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
2039 if (ret >= 0) {
2040 rt->recvbuf_pos += ret;
2041 ret = rt->recvbuf_pos < rt->recvbuf_len;
2042 }
2043 } else
2044 ret = -1;
2045 if (ret == 0) {
2046 rt->cur_transport_priv = NULL;
2047 return 0;
2048 } else if (ret == 1) {
2049 return 0;
2050 } else
2051 rt->cur_transport_priv = NULL;
2052 }
2053
2054 redo:
2055 if (rt->transport == RTSP_TRANSPORT_RTP) {
2056 int i;
2057 int64_t first_queue_time = 0;
2058 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2059 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
2060 int64_t queue_time;
2061 if (!rtpctx)
2062 continue;
2063 queue_time = ff_rtp_queued_packet_time(rtpctx);
2064 if (queue_time && (queue_time - first_queue_time < 0 ||
2065 !first_queue_time)) {
2066 first_queue_time = queue_time;
2067 first_queue_st = rt->rtsp_streams[i];
2068 }
2069 }
2070 if (first_queue_time) {
2071 wait_end = first_queue_time + s->max_delay;
2072 } else {
2073 wait_end = 0;
2074 first_queue_st = NULL;
2075 }
2076 }
2077
2078 /* read next RTP packet */
2079 if (!rt->recvbuf) {
2080 rt->recvbuf = av_malloc(RECVBUF_SIZE);
2081 if (!rt->recvbuf)
2082 return AVERROR(ENOMEM);
2083 }
2084
2085 switch(rt->lower_transport) {
2086 default:
2087 #if CONFIG_RTSP_DEMUXER
2088 case RTSP_LOWER_TRANSPORT_TCP:
2089 len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
2090 break;
2091 #endif
2092 case RTSP_LOWER_TRANSPORT_UDP:
2093 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
2094 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2095 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2096 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
2097 break;
2098 case RTSP_LOWER_TRANSPORT_CUSTOM:
2099 if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
2100 wait_end && wait_end < av_gettime_relative())
2101 len = AVERROR(EAGAIN);
2102 else
2103 len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
2104 len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
2105 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2106 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);
2107 break;
2108 }
2109 if (len == AVERROR(EAGAIN) && first_queue_st &&
2110 rt->transport == RTSP_TRANSPORT_RTP) {
2111 rtsp_st = first_queue_st;
2112 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
2113 goto end;
2114 }
2115 if (len < 0)
2116 return len;
2117 if (len == 0)
2118 return AVERROR_EOF;
2119 if (rt->transport == RTSP_TRANSPORT_RDT) {
2120 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2121 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
2122 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2123 if (rtsp_st->feedback) {
2124 AVIOContext *pb = NULL;
2125 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)
2126 pb = s->pb;
2127 ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
2128 }
2129 if (ret < 0) {
2130 /* Either bad packet, or a RTCP packet. Check if the
2131 * first_rtcp_ntp_time field was initialized. */
2132 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
2133 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
2134 /* first_rtcp_ntp_time has been initialized for this stream,
2135 * copy the same value to all other uninitialized streams,
2136 * in order to map their timestamp origin to the same ntp time
2137 * as this one. */
2138 int i;
2139 AVStream *st = NULL;
2140 if (rtsp_st->stream_index >= 0)
2141 st = s->streams[rtsp_st->stream_index];
2142 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2143 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
2144 AVStream *st2 = NULL;
2145 if (rt->rtsp_streams[i]->stream_index >= 0)
2146 st2 = s->streams[rt->rtsp_streams[i]->stream_index];
2147 if (rtpctx2 && st && st2 &&
2148 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2149 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
2150 rtpctx2->rtcp_ts_offset = av_rescale_q(
2151 rtpctx->rtcp_ts_offset, st->time_base,
2152 st2->time_base);
2153 }
2154 }
2155 }
2156 if (ret == -RTCP_BYE) {
2157 rt->nb_byes++;
2158
2159 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
2160 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
2161
2162 if (rt->nb_byes == rt->nb_rtsp_streams)
2163 return AVERROR_EOF;
2164 }
2165 }
2166 } else if (CONFIG_RTPDEC && rt->ts) {
2167 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
2168 if (ret >= 0) {
2169 if (ret < len) {
2170 rt->recvbuf_len = len;
2171 rt->recvbuf_pos = ret;
2172 rt->cur_transport_priv = rt->ts;
2173 return 1;
2174 } else {
2175 ret = 0;
2176 }
2177 }
2178 } else {
2179 return AVERROR_INVALIDDATA;
2180 }
2181 end:
2182 if (ret < 0)
2183 goto redo;
2184 if (ret == 1)
2185 /* more packets may follow, so we save the RTP context */
2186 rt->cur_transport_priv = rtsp_st->transport_priv;
2187
2188 return ret;
2189 }
2190 #endif /* CONFIG_RTPDEC */
2191
2192 #if CONFIG_SDP_DEMUXER
2193 static int sdp_probe(AVProbeData *p1)
2194 {
2195 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2196
2197 /* we look for a line beginning "c=IN IP" */
2198 while (p < p_end && *p != '\0') {
2199 if (p + sizeof("c=IN IP") - 1 < p_end &&
2200 av_strstart(p, "c=IN IP", NULL))
2201 return AVPROBE_SCORE_EXTENSION;
2202
2203 while (p < p_end - 1 && *p != '\n') p++;
2204 if (++p >= p_end)
2205 break;
2206 if (*p == '\r')
2207 p++;
2208 }
2209 return 0;
2210 }
2211
2212 static void append_source_addrs(char *buf, int size, const char *name,
2213 int count, struct RTSPSource **addrs)
2214 {
2215 int i;
2216 if (!count)
2217 return;
2218 av_strlcatf(buf, size, "&%s=%s", name, addrs[0]->addr);
2219 for (i = 1; i < count; i++)
2220 av_strlcatf(buf, size, ",%s", addrs[i]->addr);
2221 }
2222
2223 static int sdp_read_header(AVFormatContext *s)
2224 {
2225 RTSPState *rt = s->priv_data;
2226 RTSPStream *rtsp_st;
2227 int size, i, err;
2228 char *content;
2229 char url[1024];
2230
2231 if (!ff_network_init())
2232 return AVERROR(EIO);
2233
2234 if (s->max_delay < 0) /* Not set by the caller */
2235 s->max_delay = DEFAULT_REORDERING_DELAY;
2236 if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
2237 rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;
2238
2239 /* read the whole sdp file */
2240 /* XXX: better loading */
2241 content = av_malloc(SDP_MAX_SIZE);
2242 size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
2243 if (size <= 0) {
2244 av_free(content);
2245 return AVERROR_INVALIDDATA;
2246 }
2247 content[size] ='\0';
2248
2249 err = ff_sdp_parse(s, content);
2250 av_free(content);
2251 if (err) goto fail;
2252
2253 /* open each RTP stream */
2254 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2255 char namebuf[50];
2256 rtsp_st = rt->rtsp_streams[i];
2257
2258 if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
2259 AVDictionary *opts = map_to_opts(rt);
2260
2261 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2262 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2263 ff_url_join(url, sizeof(url), "rtp", NULL,
2264 namebuf, rtsp_st->sdp_port,
2265 "?localport=%d&ttl=%d&connect=%d&write_to_source=%d",
2266 rtsp_st->sdp_port, rtsp_st->sdp_ttl,
2267 rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0,
2268 rt->rtsp_flags & RTSP_FLAG_RTCP_TO_SOURCE ? 1 : 0);
2269
2270 append_source_addrs(url, sizeof(url), "sources",
2271 rtsp_st->nb_include_source_addrs,
2272 rtsp_st->include_source_addrs);
2273 append_source_addrs(url, sizeof(url), "block",
2274 rtsp_st->nb_exclude_source_addrs,
2275 rtsp_st->exclude_source_addrs);
2276 err = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
2277 &s->interrupt_callback, &opts);
2278
2279 av_dict_free(&opts);
2280
2281 if (err < 0) {
2282 err = AVERROR_INVALIDDATA;
2283 goto fail;
2284 }
2285 }
2286 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
2287 goto fail;
2288 }
2289 return 0;
2290 fail:
2291 ff_rtsp_close_streams(s);
2292 ff_network_close();
2293 return err;
2294 }
2295
2296 static int sdp_read_close(AVFormatContext *s)
2297 {
2298 ff_rtsp_close_streams(s);
2299 ff_network_close();
2300 return 0;
2301 }
2302
2303 static const AVClass sdp_demuxer_class = {
2304 .class_name = "SDP demuxer",
2305 .item_name = av_default_item_name,
2306 .option = sdp_options,
2307 .version = LIBAVUTIL_VERSION_INT,
2308 };
2309
2310 AVInputFormat ff_sdp_demuxer = {
2311 .name = "sdp",
2312 .long_name = NULL_IF_CONFIG_SMALL("SDP"),
2313 .priv_data_size = sizeof(RTSPState),
2314 .read_probe = sdp_probe,
2315 .read_header = sdp_read_header,
2316 .read_packet = ff_rtsp_fetch_packet,
2317 .read_close = sdp_read_close,
2318 .priv_class = &sdp_demuxer_class,
2319 };
2320 #endif /* CONFIG_SDP_DEMUXER */
2321
2322 #if CONFIG_RTP_DEMUXER
2323 static int rtp_probe(AVProbeData *p)
2324 {
2325 if (av_strstart(p->filename, "rtp:", NULL))
2326 return AVPROBE_SCORE_MAX;
2327 return 0;
2328 }
2329
2330 static int rtp_read_header(AVFormatContext *s)
2331 {
2332 uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
2333 char host[500], sdp[500];
2334 int ret, port;
2335 URLContext* in = NULL;
2336 int payload_type;
2337 AVCodecContext codec = { 0 };
2338 struct sockaddr_storage addr;
2339 AVIOContext pb;
2340 socklen_t addrlen = sizeof(addr);
2341 RTSPState *rt = s->priv_data;
2342
2343 if (!ff_network_init())
2344 return AVERROR(EIO);
2345
2346 ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
2347 &s->interrupt_callback, NULL);
2348 if (ret)
2349 goto fail;
2350
2351 while (1) {
2352 ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
2353 if (ret == AVERROR(EAGAIN))
2354 continue;
2355 if (ret < 0)
2356 goto fail;
2357 if (ret < 12) {
2358 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2359 continue;
2360 }
2361
2362 if ((recvbuf[0] & 0xc0) != 0x80) {
2363 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2364 "received\n");
2365 continue;
2366 }
2367
2368 if (RTP_PT_IS_RTCP(recvbuf[1]))
2369 continue;
2370
2371 payload_type = recvbuf[1] & 0x7f;
2372 break;
2373 }
2374 getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2375 ffurl_close(in);
2376 in = NULL;
2377
2378 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2379 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2380 "without an SDP file describing it\n",
2381 payload_type);
2382 goto fail;
2383 }
2384 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2385 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2386 "properly you need an SDP file "
2387 "describing it\n");
2388 }
2389
2390 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2391 NULL, 0, s->filename);
2392
2393 snprintf(sdp, sizeof(sdp),
2394 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2395 addr.ss_family == AF_INET ? 4 : 6, host,
2396 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2397 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2398 port, payload_type);
2399 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2400
2401 ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2402 s->pb = &pb;
2403
2404 /* sdp_read_header initializes this again */
2405 ff_network_close();
2406
2407 rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2408
2409 ret = sdp_read_header(s);
2410 s->pb = NULL;
2411 return ret;
2412
2413 fail:
2414 if (in)
2415 ffurl_close(in);
2416 ff_network_close();
2417 return ret;
2418 }
2419
2420 static const AVClass rtp_demuxer_class = {
2421 .class_name = "RTP demuxer",
2422 .item_name = av_default_item_name,
2423 .option = rtp_options,
2424 .version = LIBAVUTIL_VERSION_INT,
2425 };
2426
2427 AVInputFormat ff_rtp_demuxer = {
2428 .name = "rtp",
2429 .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
2430 .priv_data_size = sizeof(RTSPState),
2431 .read_probe = rtp_probe,
2432 .read_header = rtp_read_header,
2433 .read_packet = ff_rtsp_fetch_packet,
2434 .read_close = sdp_read_close,
2435 .flags = AVFMT_NOFILE,
2436 .priv_class = &rtp_demuxer_class,
2437 };
2438 #endif /* CONFIG_RTP_DEMUXER */