rtsp: Accept options via private avoptions instead of URL options
[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 "avformat.h"
30 #include "avio_internal.h"
31
32 #include <sys/time.h>
33 #if HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #include <strings.h>
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 "rdt.h"
45 #include "rtpdec_formats.h"
46 #include "rtpenc_chain.h"
47 #include "url.h"
48 #include "rtpenc.h"
49
50 //#define DEBUG
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
60 #define OFFSET(x) offsetof(RTSPState, x)
61 #define DEC AV_OPT_FLAG_DECODING_PARAM
62 #define ENC AV_OPT_FLAG_ENCODING_PARAM
63 const AVOption ff_rtsp_options[] = {
64 { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {0}, 0, 1, DEC },
65 FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
66 { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
67 { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
68 { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
69 { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
70 { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {(1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
71 { "rtsp_flags", "RTSP flags", OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" },
72 { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" },
73 { NULL },
74 };
75
76 static void get_word_until_chars(char *buf, int buf_size,
77 const char *sep, const char **pp)
78 {
79 const char *p;
80 char *q;
81
82 p = *pp;
83 p += strspn(p, SPACE_CHARS);
84 q = buf;
85 while (!strchr(sep, *p) && *p != '\0') {
86 if ((q - buf) < buf_size - 1)
87 *q++ = *p;
88 p++;
89 }
90 if (buf_size > 0)
91 *q = '\0';
92 *pp = p;
93 }
94
95 static void get_word_sep(char *buf, int buf_size, const char *sep,
96 const char **pp)
97 {
98 if (**pp == '/') (*pp)++;
99 get_word_until_chars(buf, buf_size, sep, pp);
100 }
101
102 static void get_word(char *buf, int buf_size, const char **pp)
103 {
104 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
105 }
106
107 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
108 * and end time.
109 * Used for seeking in the rtp stream.
110 */
111 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
112 {
113 char buf[256];
114
115 p += strspn(p, SPACE_CHARS);
116 if (!av_stristart(p, "npt=", &p))
117 return;
118
119 *start = AV_NOPTS_VALUE;
120 *end = AV_NOPTS_VALUE;
121
122 get_word_sep(buf, sizeof(buf), "-", &p);
123 av_parse_time(start, buf, 1);
124 if (*p == '-') {
125 p++;
126 get_word_sep(buf, sizeof(buf), "-", &p);
127 av_parse_time(end, buf, 1);
128 }
129 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
130 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
131 }
132
133 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
134 {
135 struct addrinfo hints, *ai = NULL;
136 memset(&hints, 0, sizeof(hints));
137 hints.ai_flags = AI_NUMERICHOST;
138 if (getaddrinfo(buf, NULL, &hints, &ai))
139 return -1;
140 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
141 freeaddrinfo(ai);
142 return 0;
143 }
144
145 #if CONFIG_RTPDEC
146 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
147 RTSPStream *rtsp_st, AVCodecContext *codec)
148 {
149 if (!handler)
150 return;
151 codec->codec_id = handler->codec_id;
152 rtsp_st->dynamic_handler = handler;
153 if (handler->alloc)
154 rtsp_st->dynamic_protocol_context = handler->alloc();
155 }
156
157 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
158 static int sdp_parse_rtpmap(AVFormatContext *s,
159 AVStream *st, RTSPStream *rtsp_st,
160 int payload_type, const char *p)
161 {
162 AVCodecContext *codec = st->codec;
163 char buf[256];
164 int i;
165 AVCodec *c;
166 const char *c_name;
167
168 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
169 * see if we can handle this kind of payload.
170 * The space should normally not be there but some Real streams or
171 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
172 * have a trailing space. */
173 get_word_sep(buf, sizeof(buf), "/ ", &p);
174 if (payload_type >= RTP_PT_PRIVATE) {
175 RTPDynamicProtocolHandler *handler =
176 ff_rtp_handler_find_by_name(buf, codec->codec_type);
177 init_rtp_handler(handler, rtsp_st, codec);
178 /* If no dynamic handler was found, check with the list of standard
179 * allocated types, if such a stream for some reason happens to
180 * use a private payload type. This isn't handled in rtpdec.c, since
181 * the format name from the rtpmap line never is passed into rtpdec. */
182 if (!rtsp_st->dynamic_handler)
183 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
184 } else {
185 /* We are in a standard case
186 * (from http://www.iana.org/assignments/rtp-parameters). */
187 /* search into AVRtpPayloadTypes[] */
188 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
189 }
190
191 c = avcodec_find_decoder(codec->codec_id);
192 if (c && c->name)
193 c_name = c->name;
194 else
195 c_name = "(null)";
196
197 get_word_sep(buf, sizeof(buf), "/", &p);
198 i = atoi(buf);
199 switch (codec->codec_type) {
200 case AVMEDIA_TYPE_AUDIO:
201 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
202 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
203 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
204 if (i > 0) {
205 codec->sample_rate = i;
206 av_set_pts_info(st, 32, 1, codec->sample_rate);
207 get_word_sep(buf, sizeof(buf), "/", &p);
208 i = atoi(buf);
209 if (i > 0)
210 codec->channels = i;
211 // TODO: there is a bug here; if it is a mono stream, and
212 // less than 22000Hz, faad upconverts to stereo and twice
213 // the frequency. No problem, but the sample rate is being
214 // set here by the sdp line. Patch on its way. (rdm)
215 }
216 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
217 codec->sample_rate);
218 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
219 codec->channels);
220 break;
221 case AVMEDIA_TYPE_VIDEO:
222 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
223 if (i > 0)
224 av_set_pts_info(st, 32, 1, i);
225 break;
226 default:
227 break;
228 }
229 return 0;
230 }
231
232 /* parse the attribute line from the fmtp a line of an sdp response. This
233 * is broken out as a function because it is used in rtp_h264.c, which is
234 * forthcoming. */
235 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
236 char *value, int value_size)
237 {
238 *p += strspn(*p, SPACE_CHARS);
239 if (**p) {
240 get_word_sep(attr, attr_size, "=", p);
241 if (**p == '=')
242 (*p)++;
243 get_word_sep(value, value_size, ";", p);
244 if (**p == ';')
245 (*p)++;
246 return 1;
247 }
248 return 0;
249 }
250
251 typedef struct SDPParseState {
252 /* SDP only */
253 struct sockaddr_storage default_ip;
254 int default_ttl;
255 int skip_media; ///< set if an unknown m= line occurs
256 } SDPParseState;
257
258 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
259 int letter, const char *buf)
260 {
261 RTSPState *rt = s->priv_data;
262 char buf1[64], st_type[64];
263 const char *p;
264 enum AVMediaType codec_type;
265 int payload_type, i;
266 AVStream *st;
267 RTSPStream *rtsp_st;
268 struct sockaddr_storage sdp_ip;
269 int ttl;
270
271 av_dlog(s, "sdp: %c='%s'\n", letter, buf);
272
273 p = buf;
274 if (s1->skip_media && letter != 'm')
275 return;
276 switch (letter) {
277 case 'c':
278 get_word(buf1, sizeof(buf1), &p);
279 if (strcmp(buf1, "IN") != 0)
280 return;
281 get_word(buf1, sizeof(buf1), &p);
282 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
283 return;
284 get_word_sep(buf1, sizeof(buf1), "/", &p);
285 if (get_sockaddr(buf1, &sdp_ip))
286 return;
287 ttl = 16;
288 if (*p == '/') {
289 p++;
290 get_word_sep(buf1, sizeof(buf1), "/", &p);
291 ttl = atoi(buf1);
292 }
293 if (s->nb_streams == 0) {
294 s1->default_ip = sdp_ip;
295 s1->default_ttl = ttl;
296 } else {
297 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
298 rtsp_st->sdp_ip = sdp_ip;
299 rtsp_st->sdp_ttl = ttl;
300 }
301 break;
302 case 's':
303 av_dict_set(&s->metadata, "title", p, 0);
304 break;
305 case 'i':
306 if (s->nb_streams == 0) {
307 av_dict_set(&s->metadata, "comment", p, 0);
308 break;
309 }
310 break;
311 case 'm':
312 /* new stream */
313 s1->skip_media = 0;
314 get_word(st_type, sizeof(st_type), &p);
315 if (!strcmp(st_type, "audio")) {
316 codec_type = AVMEDIA_TYPE_AUDIO;
317 } else if (!strcmp(st_type, "video")) {
318 codec_type = AVMEDIA_TYPE_VIDEO;
319 } else if (!strcmp(st_type, "application")) {
320 codec_type = AVMEDIA_TYPE_DATA;
321 } else {
322 s1->skip_media = 1;
323 return;
324 }
325 rtsp_st = av_mallocz(sizeof(RTSPStream));
326 if (!rtsp_st)
327 return;
328 rtsp_st->stream_index = -1;
329 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
330
331 rtsp_st->sdp_ip = s1->default_ip;
332 rtsp_st->sdp_ttl = s1->default_ttl;
333
334 get_word(buf1, sizeof(buf1), &p); /* port */
335 rtsp_st->sdp_port = atoi(buf1);
336
337 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
338
339 /* XXX: handle list of formats */
340 get_word(buf1, sizeof(buf1), &p); /* format list */
341 rtsp_st->sdp_payload_type = atoi(buf1);
342
343 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
344 /* no corresponding stream */
345 } else {
346 st = av_new_stream(s, rt->nb_rtsp_streams - 1);
347 if (!st)
348 return;
349 rtsp_st->stream_index = st->index;
350 st->codec->codec_type = codec_type;
351 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
352 RTPDynamicProtocolHandler *handler;
353 /* if standard payload type, we can find the codec right now */
354 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
355 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
356 st->codec->sample_rate > 0)
357 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
358 /* Even static payload types may need a custom depacketizer */
359 handler = ff_rtp_handler_find_by_id(
360 rtsp_st->sdp_payload_type, st->codec->codec_type);
361 init_rtp_handler(handler, rtsp_st, st->codec);
362 }
363 }
364 /* put a default control url */
365 av_strlcpy(rtsp_st->control_url, rt->control_uri,
366 sizeof(rtsp_st->control_url));
367 break;
368 case 'a':
369 if (av_strstart(p, "control:", &p)) {
370 if (s->nb_streams == 0) {
371 if (!strncmp(p, "rtsp://", 7))
372 av_strlcpy(rt->control_uri, p,
373 sizeof(rt->control_uri));
374 } else {
375 char proto[32];
376 /* get the control url */
377 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
378
379 /* XXX: may need to add full url resolution */
380 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
381 NULL, NULL, 0, p);
382 if (proto[0] == '\0') {
383 /* relative control URL */
384 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
385 av_strlcat(rtsp_st->control_url, "/",
386 sizeof(rtsp_st->control_url));
387 av_strlcat(rtsp_st->control_url, p,
388 sizeof(rtsp_st->control_url));
389 } else
390 av_strlcpy(rtsp_st->control_url, p,
391 sizeof(rtsp_st->control_url));
392 }
393 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
394 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
395 get_word(buf1, sizeof(buf1), &p);
396 payload_type = atoi(buf1);
397 st = s->streams[s->nb_streams - 1];
398 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
399 sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
400 } else if (av_strstart(p, "fmtp:", &p) ||
401 av_strstart(p, "framesize:", &p)) {
402 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
403 // let dynamic protocol handlers have a stab at the line.
404 get_word(buf1, sizeof(buf1), &p);
405 payload_type = atoi(buf1);
406 for (i = 0; i < rt->nb_rtsp_streams; i++) {
407 rtsp_st = rt->rtsp_streams[i];
408 if (rtsp_st->sdp_payload_type == payload_type &&
409 rtsp_st->dynamic_handler &&
410 rtsp_st->dynamic_handler->parse_sdp_a_line)
411 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
412 rtsp_st->dynamic_protocol_context, buf);
413 }
414 } else if (av_strstart(p, "range:", &p)) {
415 int64_t start, end;
416
417 // this is so that seeking on a streamed file can work.
418 rtsp_parse_range_npt(p, &start, &end);
419 s->start_time = start;
420 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
421 s->duration = (end == AV_NOPTS_VALUE) ?
422 AV_NOPTS_VALUE : end - start;
423 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
424 if (atoi(p) == 1)
425 rt->transport = RTSP_TRANSPORT_RDT;
426 } else if (av_strstart(p, "SampleRate:integer;", &p) &&
427 s->nb_streams > 0) {
428 st = s->streams[s->nb_streams - 1];
429 st->codec->sample_rate = atoi(p);
430 } else {
431 if (rt->server_type == RTSP_SERVER_WMS)
432 ff_wms_parse_sdp_a_line(s, p);
433 if (s->nb_streams > 0) {
434 if (rt->server_type == RTSP_SERVER_REAL)
435 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
436
437 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
438 if (rtsp_st->dynamic_handler &&
439 rtsp_st->dynamic_handler->parse_sdp_a_line)
440 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
441 s->nb_streams - 1,
442 rtsp_st->dynamic_protocol_context, buf);
443 }
444 }
445 break;
446 }
447 }
448
449 int ff_sdp_parse(AVFormatContext *s, const char *content)
450 {
451 RTSPState *rt = s->priv_data;
452 const char *p;
453 int letter;
454 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
455 * contain long SDP lines containing complete ASF Headers (several
456 * kB) or arrays of MDPR (RM stream descriptor) headers plus
457 * "rulebooks" describing their properties. Therefore, the SDP line
458 * buffer is large.
459 *
460 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
461 * in rtpdec_xiph.c. */
462 char buf[16384], *q;
463 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
464
465 memset(s1, 0, sizeof(SDPParseState));
466 p = content;
467 for (;;) {
468 p += strspn(p, SPACE_CHARS);
469 letter = *p;
470 if (letter == '\0')
471 break;
472 p++;
473 if (*p != '=')
474 goto next_line;
475 p++;
476 /* get the content */
477 q = buf;
478 while (*p != '\n' && *p != '\r' && *p != '\0') {
479 if ((q - buf) < sizeof(buf) - 1)
480 *q++ = *p;
481 p++;
482 }
483 *q = '\0';
484 sdp_parse_line(s, s1, letter, buf);
485 next_line:
486 while (*p != '\n' && *p != '\0')
487 p++;
488 if (*p == '\n')
489 p++;
490 }
491 rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
492 if (!rt->p) return AVERROR(ENOMEM);
493 return 0;
494 }
495 #endif /* CONFIG_RTPDEC */
496
497 void ff_rtsp_undo_setup(AVFormatContext *s)
498 {
499 RTSPState *rt = s->priv_data;
500 int i;
501
502 for (i = 0; i < rt->nb_rtsp_streams; i++) {
503 RTSPStream *rtsp_st = rt->rtsp_streams[i];
504 if (!rtsp_st)
505 continue;
506 if (rtsp_st->transport_priv) {
507 if (s->oformat) {
508 AVFormatContext *rtpctx = rtsp_st->transport_priv;
509 av_write_trailer(rtpctx);
510 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
511 uint8_t *ptr;
512 avio_close_dyn_buf(rtpctx->pb, &ptr);
513 av_free(ptr);
514 } else {
515 avio_close(rtpctx->pb);
516 }
517 avformat_free_context(rtpctx);
518 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
519 ff_rdt_parse_close(rtsp_st->transport_priv);
520 else if (CONFIG_RTPDEC)
521 ff_rtp_parse_close(rtsp_st->transport_priv);
522 }
523 rtsp_st->transport_priv = NULL;
524 if (rtsp_st->rtp_handle)
525 ffurl_close(rtsp_st->rtp_handle);
526 rtsp_st->rtp_handle = NULL;
527 }
528 }
529
530 /* close and free RTSP streams */
531 void ff_rtsp_close_streams(AVFormatContext *s)
532 {
533 RTSPState *rt = s->priv_data;
534 int i;
535 RTSPStream *rtsp_st;
536
537 ff_rtsp_undo_setup(s);
538 for (i = 0; i < rt->nb_rtsp_streams; i++) {
539 rtsp_st = rt->rtsp_streams[i];
540 if (rtsp_st) {
541 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
542 rtsp_st->dynamic_handler->free(
543 rtsp_st->dynamic_protocol_context);
544 av_free(rtsp_st);
545 }
546 }
547 av_free(rt->rtsp_streams);
548 if (rt->asf_ctx) {
549 av_close_input_stream (rt->asf_ctx);
550 rt->asf_ctx = NULL;
551 }
552 av_free(rt->p);
553 av_free(rt->recvbuf);
554 }
555
556 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
557 {
558 RTSPState *rt = s->priv_data;
559 AVStream *st = NULL;
560
561 /* open the RTP context */
562 if (rtsp_st->stream_index >= 0)
563 st = s->streams[rtsp_st->stream_index];
564 if (!st)
565 s->ctx_flags |= AVFMTCTX_NOHEADER;
566
567 if (s->oformat && CONFIG_RTSP_MUXER) {
568 rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
569 rtsp_st->rtp_handle,
570 RTSP_TCP_MAX_PACKET_SIZE);
571 /* Ownership of rtp_handle is passed to the rtp mux context */
572 rtsp_st->rtp_handle = NULL;
573 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
574 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
575 rtsp_st->dynamic_protocol_context,
576 rtsp_st->dynamic_handler);
577 else if (CONFIG_RTPDEC)
578 rtsp_st->transport_priv = ff_rtp_parse_open(s, st, rtsp_st->rtp_handle,
579 rtsp_st->sdp_payload_type,
580 (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
581 ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
582
583 if (!rtsp_st->transport_priv) {
584 return AVERROR(ENOMEM);
585 } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
586 if (rtsp_st->dynamic_handler) {
587 ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
588 rtsp_st->dynamic_protocol_context,
589 rtsp_st->dynamic_handler);
590 }
591 }
592
593 return 0;
594 }
595
596 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
597 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
598 {
599 const char *p;
600 int v;
601
602 p = *pp;
603 p += strspn(p, SPACE_CHARS);
604 v = strtol(p, (char **)&p, 10);
605 if (*p == '-') {
606 p++;
607 *min_ptr = v;
608 v = strtol(p, (char **)&p, 10);
609 *max_ptr = v;
610 } else {
611 *min_ptr = v;
612 *max_ptr = v;
613 }
614 *pp = p;
615 }
616
617 /* XXX: only one transport specification is parsed */
618 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
619 {
620 char transport_protocol[16];
621 char profile[16];
622 char lower_transport[16];
623 char parameter[16];
624 RTSPTransportField *th;
625 char buf[256];
626
627 reply->nb_transports = 0;
628
629 for (;;) {
630 p += strspn(p, SPACE_CHARS);
631 if (*p == '\0')
632 break;
633
634 th = &reply->transports[reply->nb_transports];
635
636 get_word_sep(transport_protocol, sizeof(transport_protocol),
637 "/", &p);
638 if (!strcasecmp (transport_protocol, "rtp")) {
639 get_word_sep(profile, sizeof(profile), "/;,", &p);
640 lower_transport[0] = '\0';
641 /* rtp/avp/<protocol> */
642 if (*p == '/') {
643 get_word_sep(lower_transport, sizeof(lower_transport),
644 ";,", &p);
645 }
646 th->transport = RTSP_TRANSPORT_RTP;
647 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
648 !strcasecmp (transport_protocol, "x-real-rdt")) {
649 /* x-pn-tng/<protocol> */
650 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
651 profile[0] = '\0';
652 th->transport = RTSP_TRANSPORT_RDT;
653 }
654 if (!strcasecmp(lower_transport, "TCP"))
655 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
656 else
657 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
658
659 if (*p == ';')
660 p++;
661 /* get each parameter */
662 while (*p != '\0' && *p != ',') {
663 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
664 if (!strcmp(parameter, "port")) {
665 if (*p == '=') {
666 p++;
667 rtsp_parse_range(&th->port_min, &th->port_max, &p);
668 }
669 } else if (!strcmp(parameter, "client_port")) {
670 if (*p == '=') {
671 p++;
672 rtsp_parse_range(&th->client_port_min,
673 &th->client_port_max, &p);
674 }
675 } else if (!strcmp(parameter, "server_port")) {
676 if (*p == '=') {
677 p++;
678 rtsp_parse_range(&th->server_port_min,
679 &th->server_port_max, &p);
680 }
681 } else if (!strcmp(parameter, "interleaved")) {
682 if (*p == '=') {
683 p++;
684 rtsp_parse_range(&th->interleaved_min,
685 &th->interleaved_max, &p);
686 }
687 } else if (!strcmp(parameter, "multicast")) {
688 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
689 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
690 } else if (!strcmp(parameter, "ttl")) {
691 if (*p == '=') {
692 p++;
693 th->ttl = strtol(p, (char **)&p, 10);
694 }
695 } else if (!strcmp(parameter, "destination")) {
696 if (*p == '=') {
697 p++;
698 get_word_sep(buf, sizeof(buf), ";,", &p);
699 get_sockaddr(buf, &th->destination);
700 }
701 } else if (!strcmp(parameter, "source")) {
702 if (*p == '=') {
703 p++;
704 get_word_sep(buf, sizeof(buf), ";,", &p);
705 av_strlcpy(th->source, buf, sizeof(th->source));
706 }
707 }
708
709 while (*p != ';' && *p != '\0' && *p != ',')
710 p++;
711 if (*p == ';')
712 p++;
713 }
714 if (*p == ',')
715 p++;
716
717 reply->nb_transports++;
718 }
719 }
720
721 static void handle_rtp_info(RTSPState *rt, const char *url,
722 uint32_t seq, uint32_t rtptime)
723 {
724 int i;
725 if (!rtptime || !url[0])
726 return;
727 if (rt->transport != RTSP_TRANSPORT_RTP)
728 return;
729 for (i = 0; i < rt->nb_rtsp_streams; i++) {
730 RTSPStream *rtsp_st = rt->rtsp_streams[i];
731 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
732 if (!rtpctx)
733 continue;
734 if (!strcmp(rtsp_st->control_url, url)) {
735 rtpctx->base_timestamp = rtptime;
736 break;
737 }
738 }
739 }
740
741 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
742 {
743 int read = 0;
744 char key[20], value[1024], url[1024] = "";
745 uint32_t seq = 0, rtptime = 0;
746
747 for (;;) {
748 p += strspn(p, SPACE_CHARS);
749 if (!*p)
750 break;
751 get_word_sep(key, sizeof(key), "=", &p);
752 if (*p != '=')
753 break;
754 p++;
755 get_word_sep(value, sizeof(value), ";, ", &p);
756 read++;
757 if (!strcmp(key, "url"))
758 av_strlcpy(url, value, sizeof(url));
759 else if (!strcmp(key, "seq"))
760 seq = strtoul(value, NULL, 10);
761 else if (!strcmp(key, "rtptime"))
762 rtptime = strtoul(value, NULL, 10);
763 if (*p == ',') {
764 handle_rtp_info(rt, url, seq, rtptime);
765 url[0] = '\0';
766 seq = rtptime = 0;
767 read = 0;
768 }
769 if (*p)
770 p++;
771 }
772 if (read > 0)
773 handle_rtp_info(rt, url, seq, rtptime);
774 }
775
776 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
777 RTSPState *rt, const char *method)
778 {
779 const char *p;
780
781 /* NOTE: we do case independent match for broken servers */
782 p = buf;
783 if (av_stristart(p, "Session:", &p)) {
784 int t;
785 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
786 if (av_stristart(p, ";timeout=", &p) &&
787 (t = strtol(p, NULL, 10)) > 0) {
788 reply->timeout = t;
789 }
790 } else if (av_stristart(p, "Content-Length:", &p)) {
791 reply->content_length = strtol(p, NULL, 10);
792 } else if (av_stristart(p, "Transport:", &p)) {
793 rtsp_parse_transport(reply, p);
794 } else if (av_stristart(p, "CSeq:", &p)) {
795 reply->seq = strtol(p, NULL, 10);
796 } else if (av_stristart(p, "Range:", &p)) {
797 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
798 } else if (av_stristart(p, "RealChallenge1:", &p)) {
799 p += strspn(p, SPACE_CHARS);
800 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
801 } else if (av_stristart(p, "Server:", &p)) {
802 p += strspn(p, SPACE_CHARS);
803 av_strlcpy(reply->server, p, sizeof(reply->server));
804 } else if (av_stristart(p, "Notice:", &p) ||
805 av_stristart(p, "X-Notice:", &p)) {
806 reply->notice = strtol(p, NULL, 10);
807 } else if (av_stristart(p, "Location:", &p)) {
808 p += strspn(p, SPACE_CHARS);
809 av_strlcpy(reply->location, p , sizeof(reply->location));
810 } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
811 p += strspn(p, SPACE_CHARS);
812 ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
813 } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
814 p += strspn(p, SPACE_CHARS);
815 ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
816 } else if (av_stristart(p, "Content-Base:", &p) && rt) {
817 p += strspn(p, SPACE_CHARS);
818 if (method && !strcmp(method, "DESCRIBE"))
819 av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
820 } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
821 p += strspn(p, SPACE_CHARS);
822 if (method && !strcmp(method, "PLAY"))
823 rtsp_parse_rtp_info(rt, p);
824 } else if (av_stristart(p, "Public:", &p) && rt) {
825 if (strstr(p, "GET_PARAMETER") &&
826 method && !strcmp(method, "OPTIONS"))
827 rt->get_parameter_supported = 1;
828 } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
829 p += strspn(p, SPACE_CHARS);
830 rt->accept_dynamic_rate = atoi(p);
831 }
832 }
833
834 /* skip a RTP/TCP interleaved packet */
835 void ff_rtsp_skip_packet(AVFormatContext *s)
836 {
837 RTSPState *rt = s->priv_data;
838 int ret, len, len1;
839 uint8_t buf[1024];
840
841 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
842 if (ret != 3)
843 return;
844 len = AV_RB16(buf + 1);
845
846 av_dlog(s, "skipping RTP packet len=%d\n", len);
847
848 /* skip payload */
849 while (len > 0) {
850 len1 = len;
851 if (len1 > sizeof(buf))
852 len1 = sizeof(buf);
853 ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
854 if (ret != len1)
855 return;
856 len -= len1;
857 }
858 }
859
860 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
861 unsigned char **content_ptr,
862 int return_on_interleaved_data, const char *method)
863 {
864 RTSPState *rt = s->priv_data;
865 char buf[4096], buf1[1024], *q;
866 unsigned char ch;
867 const char *p;
868 int ret, content_length, line_count = 0;
869 unsigned char *content = NULL;
870
871 memset(reply, 0, sizeof(*reply));
872
873 /* parse reply (XXX: use buffers) */
874 rt->last_reply[0] = '\0';
875 for (;;) {
876 q = buf;
877 for (;;) {
878 ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
879 av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
880 if (ret != 1)
881 return AVERROR_EOF;
882 if (ch == '\n')
883 break;
884 if (ch == '$') {
885 /* XXX: only parse it if first char on line ? */
886 if (return_on_interleaved_data) {
887 return 1;
888 } else
889 ff_rtsp_skip_packet(s);
890 } else if (ch != '\r') {
891 if ((q - buf) < sizeof(buf) - 1)
892 *q++ = ch;
893 }
894 }
895 *q = '\0';
896
897 av_dlog(s, "line='%s'\n", buf);
898
899 /* test if last line */
900 if (buf[0] == '\0')
901 break;
902 p = buf;
903 if (line_count == 0) {
904 /* get reply code */
905 get_word(buf1, sizeof(buf1), &p);
906 get_word(buf1, sizeof(buf1), &p);
907 reply->status_code = atoi(buf1);
908 av_strlcpy(reply->reason, p, sizeof(reply->reason));
909 } else {
910 ff_rtsp_parse_line(reply, p, rt, method);
911 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
912 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
913 }
914 line_count++;
915 }
916
917 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
918 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
919
920 content_length = reply->content_length;
921 if (content_length > 0) {
922 /* leave some room for a trailing '\0' (useful for simple parsing) */
923 content = av_malloc(content_length + 1);
924 ffurl_read_complete(rt->rtsp_hd, content, content_length);
925 content[content_length] = '\0';
926 }
927 if (content_ptr)
928 *content_ptr = content;
929 else
930 av_free(content);
931
932 if (rt->seq != reply->seq) {
933 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
934 rt->seq, reply->seq);
935 }
936
937 /* EOS */
938 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
939 reply->notice == 2104 /* Start-of-Stream Reached */ ||
940 reply->notice == 2306 /* Continuous Feed Terminated */) {
941 rt->state = RTSP_STATE_IDLE;
942 } else if (reply->notice >= 4400 && reply->notice < 5500) {
943 return AVERROR(EIO); /* data or server error */
944 } else if (reply->notice == 2401 /* Ticket Expired */ ||
945 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
946 return AVERROR(EPERM);
947
948 return 0;
949 }
950
951 /**
952 * Send a command to the RTSP server without waiting for the reply.
953 *
954 * @param s RTSP (de)muxer context
955 * @param method the method for the request
956 * @param url the target url for the request
957 * @param headers extra header lines to include in the request
958 * @param send_content if non-null, the data to send as request body content
959 * @param send_content_length the length of the send_content data, or 0 if
960 * send_content is null
961 *
962 * @return zero if success, nonzero otherwise
963 */
964 static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
965 const char *method, const char *url,
966 const char *headers,
967 const unsigned char *send_content,
968 int send_content_length)
969 {
970 RTSPState *rt = s->priv_data;
971 char buf[4096], *out_buf;
972 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
973
974 /* Add in RTSP headers */
975 out_buf = buf;
976 rt->seq++;
977 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
978 if (headers)
979 av_strlcat(buf, headers, sizeof(buf));
980 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
981 if (rt->session_id[0] != '\0' && (!headers ||
982 !strstr(headers, "\nIf-Match:"))) {
983 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
984 }
985 if (rt->auth[0]) {
986 char *str = ff_http_auth_create_response(&rt->auth_state,
987 rt->auth, url, method);
988 if (str)
989 av_strlcat(buf, str, sizeof(buf));
990 av_free(str);
991 }
992 if (send_content_length > 0 && send_content)
993 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
994 av_strlcat(buf, "\r\n", sizeof(buf));
995
996 /* base64 encode rtsp if tunneling */
997 if (rt->control_transport == RTSP_MODE_TUNNEL) {
998 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
999 out_buf = base64buf;
1000 }
1001
1002 av_dlog(s, "Sending:\n%s--\n", buf);
1003
1004 ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1005 if (send_content_length > 0 && send_content) {
1006 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1007 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1008 "with content data not supported\n");
1009 return AVERROR_PATCHWELCOME;
1010 }
1011 ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
1012 }
1013 rt->last_cmd_time = av_gettime();
1014
1015 return 0;
1016 }
1017
1018 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1019 const char *url, const char *headers)
1020 {
1021 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1022 }
1023
1024 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1025 const char *headers, RTSPMessageHeader *reply,
1026 unsigned char **content_ptr)
1027 {
1028 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1029 content_ptr, NULL, 0);
1030 }
1031
1032 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1033 const char *method, const char *url,
1034 const char *header,
1035 RTSPMessageHeader *reply,
1036 unsigned char **content_ptr,
1037 const unsigned char *send_content,
1038 int send_content_length)
1039 {
1040 RTSPState *rt = s->priv_data;
1041 HTTPAuthType cur_auth_type;
1042 int ret;
1043
1044 retry:
1045 cur_auth_type = rt->auth_state.auth_type;
1046 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
1047 send_content,
1048 send_content_length)))
1049 return ret;
1050
1051 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
1052 return ret;
1053
1054 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
1055 rt->auth_state.auth_type != HTTP_AUTH_NONE)
1056 goto retry;
1057
1058 if (reply->status_code > 400){
1059 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
1060 method,
1061 reply->status_code,
1062 reply->reason);
1063 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1064 }
1065
1066 return 0;
1067 }
1068
1069 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
1070 int lower_transport, const char *real_challenge)
1071 {
1072 RTSPState *rt = s->priv_data;
1073 int rtx, j, i, err, interleave = 0;
1074 RTSPStream *rtsp_st;
1075 RTSPMessageHeader reply1, *reply = &reply1;
1076 char cmd[2048];
1077 const char *trans_pref;
1078
1079 if (rt->transport == RTSP_TRANSPORT_RDT)
1080 trans_pref = "x-pn-tng";
1081 else
1082 trans_pref = "RTP/AVP";
1083
1084 /* default timeout: 1 minute */
1085 rt->timeout = 60;
1086
1087 /* for each stream, make the setup request */
1088 /* XXX: we assume the same server is used for the control of each
1089 * RTSP stream */
1090
1091 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1092 char transport[2048];
1093
1094 /*
1095 * WMS serves all UDP data over a single connection, the RTX, which
1096 * isn't necessarily the first in the SDP but has to be the first
1097 * to be set up, else the second/third SETUP will fail with a 461.
1098 */
1099 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1100 rt->server_type == RTSP_SERVER_WMS) {
1101 if (i == 0) {
1102 /* rtx first */
1103 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1104 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1105 if (len >= 4 &&
1106 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1107 "/rtx"))
1108 break;
1109 }
1110 if (rtx == rt->nb_rtsp_streams)
1111 return -1; /* no RTX found */
1112 rtsp_st = rt->rtsp_streams[rtx];
1113 } else
1114 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1115 } else
1116 rtsp_st = rt->rtsp_streams[i];
1117
1118 /* RTP/UDP */
1119 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1120 char buf[256];
1121
1122 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1123 port = reply->transports[0].client_port_min;
1124 goto have_port;
1125 }
1126
1127 /* first try in specified port range */
1128 if (RTSP_RTP_PORT_MIN != 0) {
1129 while (j <= RTSP_RTP_PORT_MAX) {
1130 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1131 "?localport=%d", j);
1132 /* we will use two ports per rtp stream (rtp and rtcp) */
1133 j += 2;
1134 if (ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE) == 0)
1135 goto rtp_opened;
1136 }
1137 }
1138
1139 av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1140 err = AVERROR(EIO);
1141 goto fail;
1142
1143 rtp_opened:
1144 port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1145 have_port:
1146 snprintf(transport, sizeof(transport) - 1,
1147 "%s/UDP;", trans_pref);
1148 if (rt->server_type != RTSP_SERVER_REAL)
1149 av_strlcat(transport, "unicast;", sizeof(transport));
1150 av_strlcatf(transport, sizeof(transport),
1151 "client_port=%d", port);
1152 if (rt->transport == RTSP_TRANSPORT_RTP &&
1153 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1154 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1155 }
1156
1157 /* RTP/TCP */
1158 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1159 /* For WMS streams, the application streams are only used for
1160 * UDP. When trying to set it up for TCP streams, the server
1161 * will return an error. Therefore, we skip those streams. */
1162 if (rt->server_type == RTSP_SERVER_WMS &&
1163 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1164 AVMEDIA_TYPE_DATA)
1165 continue;
1166 snprintf(transport, sizeof(transport) - 1,
1167 "%s/TCP;", trans_pref);
1168 if (rt->transport != RTSP_TRANSPORT_RDT)
1169 av_strlcat(transport, "unicast;", sizeof(transport));
1170 av_strlcatf(transport, sizeof(transport),
1171 "interleaved=%d-%d",
1172 interleave, interleave + 1);
1173 interleave += 2;
1174 }
1175
1176 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1177 snprintf(transport, sizeof(transport) - 1,
1178 "%s/UDP;multicast", trans_pref);
1179 }
1180 if (s->oformat) {
1181 av_strlcat(transport, ";mode=receive", sizeof(transport));
1182 } else if (rt->server_type == RTSP_SERVER_REAL ||
1183 rt->server_type == RTSP_SERVER_WMS)
1184 av_strlcat(transport, ";mode=play", sizeof(transport));
1185 snprintf(cmd, sizeof(cmd),
1186 "Transport: %s\r\n",
1187 transport);
1188 if (rt->accept_dynamic_rate)
1189 av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
1190 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
1191 char real_res[41], real_csum[9];
1192 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1193 real_challenge);
1194 av_strlcatf(cmd, sizeof(cmd),
1195 "If-Match: %s\r\n"
1196 "RealChallenge2: %s, sd=%s\r\n",
1197 rt->session_id, real_res, real_csum);
1198 }
1199 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1200 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1201 err = 1;
1202 goto fail;
1203 } else if (reply->status_code != RTSP_STATUS_OK ||
1204 reply->nb_transports != 1) {
1205 err = AVERROR_INVALIDDATA;
1206 goto fail;
1207 }
1208
1209 /* XXX: same protocol for all streams is required */
1210 if (i > 0) {
1211 if (reply->transports[0].lower_transport != rt->lower_transport ||
1212 reply->transports[0].transport != rt->transport) {
1213 err = AVERROR_INVALIDDATA;
1214 goto fail;
1215 }
1216 } else {
1217 rt->lower_transport = reply->transports[0].lower_transport;
1218 rt->transport = reply->transports[0].transport;
1219 }
1220
1221 /* Fail if the server responded with another lower transport mode
1222 * than what we requested. */
1223 if (reply->transports[0].lower_transport != lower_transport) {
1224 av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1225 err = AVERROR_INVALIDDATA;
1226 goto fail;
1227 }
1228
1229 switch(reply->transports[0].lower_transport) {
1230 case RTSP_LOWER_TRANSPORT_TCP:
1231 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1232 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1233 break;
1234
1235 case RTSP_LOWER_TRANSPORT_UDP: {
1236 char url[1024], options[30] = "";
1237
1238 if (rt->filter_source)
1239 av_strlcpy(options, "?connect=1", sizeof(options));
1240 /* Use source address if specified */
1241 if (reply->transports[0].source[0]) {
1242 ff_url_join(url, sizeof(url), "rtp", NULL,
1243 reply->transports[0].source,
1244 reply->transports[0].server_port_min, "%s", options);
1245 } else {
1246 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1247 reply->transports[0].server_port_min, "%s", options);
1248 }
1249 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1250 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1251 err = AVERROR_INVALIDDATA;
1252 goto fail;
1253 }
1254 /* Try to initialize the connection state in a
1255 * potential NAT router by sending dummy packets.
1256 * RTP/RTCP dummy packets are used for RDT, too.
1257 */
1258 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1259 CONFIG_RTPDEC)
1260 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
1261 break;
1262 }
1263 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1264 char url[1024], namebuf[50];
1265 struct sockaddr_storage addr;
1266 int port, ttl;
1267
1268 if (reply->transports[0].destination.ss_family) {
1269 addr = reply->transports[0].destination;
1270 port = reply->transports[0].port_min;
1271 ttl = reply->transports[0].ttl;
1272 } else {
1273 addr = rtsp_st->sdp_ip;
1274 port = rtsp_st->sdp_port;
1275 ttl = rtsp_st->sdp_ttl;
1276 }
1277 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1278 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1279 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1280 port, "?ttl=%d", ttl);
1281 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE) < 0) {
1282 err = AVERROR_INVALIDDATA;
1283 goto fail;
1284 }
1285 break;
1286 }
1287 }
1288
1289 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1290 goto fail;
1291 }
1292
1293 if (reply->timeout > 0)
1294 rt->timeout = reply->timeout;
1295
1296 if (rt->server_type == RTSP_SERVER_REAL)
1297 rt->need_subscription = 1;
1298
1299 return 0;
1300
1301 fail:
1302 ff_rtsp_undo_setup(s);
1303 return err;
1304 }
1305
1306 void ff_rtsp_close_connections(AVFormatContext *s)
1307 {
1308 RTSPState *rt = s->priv_data;
1309 if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1310 ffurl_close(rt->rtsp_hd);
1311 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1312 }
1313
1314 int ff_rtsp_connect(AVFormatContext *s)
1315 {
1316 RTSPState *rt = s->priv_data;
1317 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1318 char *option_list, *option, *filename;
1319 int port, err, tcp_fd;
1320 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1321 int lower_transport_mask = 0;
1322 char real_challenge[64] = "";
1323 struct sockaddr_storage peer;
1324 socklen_t peer_len = sizeof(peer);
1325
1326 if (!ff_network_init())
1327 return AVERROR(EIO);
1328
1329 rt->control_transport = RTSP_MODE_PLAIN;
1330 if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1331 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1332 rt->control_transport = RTSP_MODE_TUNNEL;
1333 }
1334 /* Only pass through valid flags from here */
1335 rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1336 if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
1337 rt->filter_source = 1;
1338
1339 redirect:
1340 lower_transport_mask = rt->lower_transport_mask;
1341 /* extract hostname and port */
1342 av_url_split(NULL, 0, auth, sizeof(auth),
1343 host, sizeof(host), &port, path, sizeof(path), s->filename);
1344 if (*auth) {
1345 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1346 }
1347 if (port < 0)
1348 port = RTSP_DEFAULT_PORT;
1349
1350 #if FF_API_RTSP_URL_OPTIONS
1351 /* search for options */
1352 option_list = strrchr(path, '?');
1353 if (option_list) {
1354 /* Strip out the RTSP specific options, write out the rest of
1355 * the options back into the same string. */
1356 filename = option_list;
1357 while (option_list) {
1358 int handled = 1;
1359 /* move the option pointer */
1360 option = ++option_list;
1361 option_list = strchr(option_list, '&');
1362 if (option_list)
1363 *option_list = 0;
1364
1365 /* handle the options */
1366 if (!strcmp(option, "udp")) {
1367 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1368 } else if (!strcmp(option, "multicast")) {
1369 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1370 } else if (!strcmp(option, "tcp")) {
1371 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1372 } else if(!strcmp(option, "http")) {
1373 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1374 rt->control_transport = RTSP_MODE_TUNNEL;
1375 } else if (!strcmp(option, "filter_src")) {
1376 rt->filter_source = 1;
1377 } else {
1378 /* Write options back into the buffer, using memmove instead
1379 * of strcpy since the strings may overlap. */
1380 int len = strlen(option);
1381 memmove(++filename, option, len);
1382 filename += len;
1383 if (option_list) *filename = '&';
1384 handled = 0;
1385 }
1386 if (handled)
1387 av_log(s, AV_LOG_WARNING, "Options passed via URL are "
1388 "deprecated, use -rtsp_transport "
1389 "and -rtsp_flags instead.\n");
1390 }
1391 *filename = 0;
1392 }
1393 #endif
1394
1395 if (!lower_transport_mask)
1396 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1397
1398 if (s->oformat) {
1399 /* Only UDP or TCP - UDP multicast isn't supported. */
1400 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1401 (1 << RTSP_LOWER_TRANSPORT_TCP);
1402 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1403 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1404 "only UDP and TCP are supported for output.\n");
1405 err = AVERROR(EINVAL);
1406 goto fail;
1407 }
1408 }
1409
1410 /* Construct the URI used in request; this is similar to s->filename,
1411 * but with authentication credentials removed and RTSP specific options
1412 * stripped out. */
1413 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1414 host, port, "%s", path);
1415
1416 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1417 /* set up initial handshake for tunneling */
1418 char httpname[1024];
1419 char sessioncookie[17];
1420 char headers[1024];
1421
1422 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1423 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1424 av_get_random_seed(), av_get_random_seed());
1425
1426 /* GET requests */
1427 if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ) < 0) {
1428 err = AVERROR(EIO);
1429 goto fail;
1430 }
1431
1432 /* generate GET headers */
1433 snprintf(headers, sizeof(headers),
1434 "x-sessioncookie: %s\r\n"
1435 "Accept: application/x-rtsp-tunnelled\r\n"
1436 "Pragma: no-cache\r\n"
1437 "Cache-Control: no-cache\r\n",
1438 sessioncookie);
1439 ff_http_set_headers(rt->rtsp_hd, headers);
1440
1441 /* complete the connection */
1442 if (ffurl_connect(rt->rtsp_hd)) {
1443 err = AVERROR(EIO);
1444 goto fail;
1445 }
1446
1447 /* POST requests */
1448 if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE) < 0 ) {
1449 err = AVERROR(EIO);
1450 goto fail;
1451 }
1452
1453 /* generate POST headers */
1454 snprintf(headers, sizeof(headers),
1455 "x-sessioncookie: %s\r\n"
1456 "Content-Type: application/x-rtsp-tunnelled\r\n"
1457 "Pragma: no-cache\r\n"
1458 "Cache-Control: no-cache\r\n"
1459 "Content-Length: 32767\r\n"
1460 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1461 sessioncookie);
1462 ff_http_set_headers(rt->rtsp_hd_out, headers);
1463 ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1464
1465 /* Initialize the authentication state for the POST session. The HTTP
1466 * protocol implementation doesn't properly handle multi-pass
1467 * authentication for POST requests, since it would require one of
1468 * the following:
1469 * - implementing Expect: 100-continue, which many HTTP servers
1470 * don't support anyway, even less the RTSP servers that do HTTP
1471 * tunneling
1472 * - sending the whole POST data until getting a 401 reply specifying
1473 * what authentication method to use, then resending all that data
1474 * - waiting for potential 401 replies directly after sending the
1475 * POST header (waiting for some unspecified time)
1476 * Therefore, we copy the full auth state, which works for both basic
1477 * and digest. (For digest, we would have to synchronize the nonce
1478 * count variable between the two sessions, if we'd do more requests
1479 * with the original session, though.)
1480 */
1481 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1482
1483 /* complete the connection */
1484 if (ffurl_connect(rt->rtsp_hd_out)) {
1485 err = AVERROR(EIO);
1486 goto fail;
1487 }
1488 } else {
1489 /* open the tcp connection */
1490 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1491 if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE) < 0) {
1492 err = AVERROR(EIO);
1493 goto fail;
1494 }
1495 rt->rtsp_hd_out = rt->rtsp_hd;
1496 }
1497 rt->seq = 0;
1498
1499 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1500 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1501 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1502 NULL, 0, NI_NUMERICHOST);
1503 }
1504
1505 /* request options supported by the server; this also detects server
1506 * type */
1507 for (rt->server_type = RTSP_SERVER_RTP;;) {
1508 cmd[0] = 0;
1509 if (rt->server_type == RTSP_SERVER_REAL)
1510 av_strlcat(cmd,
1511 /*
1512 * The following entries are required for proper
1513 * streaming from a Realmedia server. They are
1514 * interdependent in some way although we currently
1515 * don't quite understand how. Values were copied
1516 * from mplayer SVN r23589.
1517 * ClientChallenge is a 16-byte ID in hex
1518 * CompanyID is a 16-byte ID in base64
1519 */
1520 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1521 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1522 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1523 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1524 sizeof(cmd));
1525 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1526 if (reply->status_code != RTSP_STATUS_OK) {
1527 err = AVERROR_INVALIDDATA;
1528 goto fail;
1529 }
1530
1531 /* detect server type if not standard-compliant RTP */
1532 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1533 rt->server_type = RTSP_SERVER_REAL;
1534 continue;
1535 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1536 rt->server_type = RTSP_SERVER_WMS;
1537 } else if (rt->server_type == RTSP_SERVER_REAL)
1538 strcpy(real_challenge, reply->real_challenge);
1539 break;
1540 }
1541
1542 if (s->iformat && CONFIG_RTSP_DEMUXER)
1543 err = ff_rtsp_setup_input_streams(s, reply);
1544 else if (CONFIG_RTSP_MUXER)
1545 err = ff_rtsp_setup_output_streams(s, host);
1546 if (err)
1547 goto fail;
1548
1549 do {
1550 int lower_transport = ff_log2_tab[lower_transport_mask &
1551 ~(lower_transport_mask - 1)];
1552
1553 err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
1554 rt->server_type == RTSP_SERVER_REAL ?
1555 real_challenge : NULL);
1556 if (err < 0)
1557 goto fail;
1558 lower_transport_mask &= ~(1 << lower_transport);
1559 if (lower_transport_mask == 0 && err == 1) {
1560 err = AVERROR(EPROTONOSUPPORT);
1561 goto fail;
1562 }
1563 } while (err);
1564
1565 rt->lower_transport_mask = lower_transport_mask;
1566 av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
1567 rt->state = RTSP_STATE_IDLE;
1568 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1569 return 0;
1570 fail:
1571 ff_rtsp_close_streams(s);
1572 ff_rtsp_close_connections(s);
1573 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1574 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1575 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1576 reply->status_code,
1577 s->filename);
1578 goto redirect;
1579 }
1580 ff_network_close();
1581 return err;
1582 }
1583 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1584
1585 #if CONFIG_RTPDEC
1586 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1587 uint8_t *buf, int buf_size, int64_t wait_end)
1588 {
1589 RTSPState *rt = s->priv_data;
1590 RTSPStream *rtsp_st;
1591 int n, i, ret, tcp_fd, timeout_cnt = 0;
1592 int max_p = 0;
1593 struct pollfd *p = rt->p;
1594
1595 for (;;) {
1596 if (url_interrupt_cb())
1597 return AVERROR_EXIT;
1598 if (wait_end && wait_end - av_gettime() < 0)
1599 return AVERROR(EAGAIN);
1600 max_p = 0;
1601 if (rt->rtsp_hd) {
1602 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1603 p[max_p].fd = tcp_fd;
1604 p[max_p++].events = POLLIN;
1605 } else {
1606 tcp_fd = -1;
1607 }
1608 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1609 rtsp_st = rt->rtsp_streams[i];
1610 if (rtsp_st->rtp_handle) {
1611 p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
1612 p[max_p++].events = POLLIN;
1613 p[max_p].fd = ff_rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1614 p[max_p++].events = POLLIN;
1615 }
1616 }
1617 n = poll(p, max_p, POLL_TIMEOUT_MS);
1618 if (n > 0) {
1619 int j = 1 - (tcp_fd == -1);
1620 timeout_cnt = 0;
1621 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1622 rtsp_st = rt->rtsp_streams[i];
1623 if (rtsp_st->rtp_handle) {
1624 if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
1625 ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
1626 if (ret > 0) {
1627 *prtsp_st = rtsp_st;
1628 return ret;
1629 }
1630 }
1631 j+=2;
1632 }
1633 }
1634 #if CONFIG_RTSP_DEMUXER
1635 if (tcp_fd != -1 && p[0].revents & POLLIN) {
1636 RTSPMessageHeader reply;
1637
1638 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1639 if (ret < 0)
1640 return ret;
1641 /* XXX: parse message */
1642 if (rt->state != RTSP_STATE_STREAMING)
1643 return 0;
1644 }
1645 #endif
1646 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1647 return AVERROR(ETIMEDOUT);
1648 } else if (n < 0 && errno != EINTR)
1649 return AVERROR(errno);
1650 }
1651 }
1652
1653 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1654 {
1655 RTSPState *rt = s->priv_data;
1656 int ret, len;
1657 RTSPStream *rtsp_st, *first_queue_st = NULL;
1658 int64_t wait_end = 0;
1659
1660 if (rt->nb_byes == rt->nb_rtsp_streams)
1661 return AVERROR_EOF;
1662
1663 /* get next frames from the same RTP packet */
1664 if (rt->cur_transport_priv) {
1665 if (rt->transport == RTSP_TRANSPORT_RDT) {
1666 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1667 } else
1668 ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1669 if (ret == 0) {
1670 rt->cur_transport_priv = NULL;
1671 return 0;
1672 } else if (ret == 1) {
1673 return 0;
1674 } else
1675 rt->cur_transport_priv = NULL;
1676 }
1677
1678 if (rt->transport == RTSP_TRANSPORT_RTP) {
1679 int i;
1680 int64_t first_queue_time = 0;
1681 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1682 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1683 int64_t queue_time;
1684 if (!rtpctx)
1685 continue;
1686 queue_time = ff_rtp_queued_packet_time(rtpctx);
1687 if (queue_time && (queue_time - first_queue_time < 0 ||
1688 !first_queue_time)) {
1689 first_queue_time = queue_time;
1690 first_queue_st = rt->rtsp_streams[i];
1691 }
1692 }
1693 if (first_queue_time)
1694 wait_end = first_queue_time + s->max_delay;
1695 }
1696
1697 /* read next RTP packet */
1698 redo:
1699 if (!rt->recvbuf) {
1700 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1701 if (!rt->recvbuf)
1702 return AVERROR(ENOMEM);
1703 }
1704
1705 switch(rt->lower_transport) {
1706 default:
1707 #if CONFIG_RTSP_DEMUXER
1708 case RTSP_LOWER_TRANSPORT_TCP:
1709 len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1710 break;
1711 #endif
1712 case RTSP_LOWER_TRANSPORT_UDP:
1713 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1714 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
1715 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1716 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1717 break;
1718 }
1719 if (len == AVERROR(EAGAIN) && first_queue_st &&
1720 rt->transport == RTSP_TRANSPORT_RTP) {
1721 rtsp_st = first_queue_st;
1722 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
1723 goto end;
1724 }
1725 if (len < 0)
1726 return len;
1727 if (len == 0)
1728 return AVERROR_EOF;
1729 if (rt->transport == RTSP_TRANSPORT_RDT) {
1730 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1731 } else {
1732 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1733 if (ret < 0) {
1734 /* Either bad packet, or a RTCP packet. Check if the
1735 * first_rtcp_ntp_time field was initialized. */
1736 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1737 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1738 /* first_rtcp_ntp_time has been initialized for this stream,
1739 * copy the same value to all other uninitialized streams,
1740 * in order to map their timestamp origin to the same ntp time
1741 * as this one. */
1742 int i;
1743 AVStream *st = NULL;
1744 if (rtsp_st->stream_index >= 0)
1745 st = s->streams[rtsp_st->stream_index];
1746 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1747 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1748 AVStream *st2 = NULL;
1749 if (rt->rtsp_streams[i]->stream_index >= 0)
1750 st2 = s->streams[rt->rtsp_streams[i]->stream_index];
1751 if (rtpctx2 && st && st2 &&
1752 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
1753 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1754 rtpctx2->rtcp_ts_offset = av_rescale_q(
1755 rtpctx->rtcp_ts_offset, st->time_base,
1756 st2->time_base);
1757 }
1758 }
1759 }
1760 if (ret == -RTCP_BYE) {
1761 rt->nb_byes++;
1762
1763 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1764 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1765
1766 if (rt->nb_byes == rt->nb_rtsp_streams)
1767 return AVERROR_EOF;
1768 }
1769 }
1770 }
1771 end:
1772 if (ret < 0)
1773 goto redo;
1774 if (ret == 1)
1775 /* more packets may follow, so we save the RTP context */
1776 rt->cur_transport_priv = rtsp_st->transport_priv;
1777
1778 return ret;
1779 }
1780 #endif /* CONFIG_RTPDEC */
1781
1782 #if CONFIG_SDP_DEMUXER
1783 static int sdp_probe(AVProbeData *p1)
1784 {
1785 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1786
1787 /* we look for a line beginning "c=IN IP" */
1788 while (p < p_end && *p != '\0') {
1789 if (p + sizeof("c=IN IP") - 1 < p_end &&
1790 av_strstart(p, "c=IN IP", NULL))
1791 return AVPROBE_SCORE_MAX / 2;
1792
1793 while (p < p_end - 1 && *p != '\n') p++;
1794 if (++p >= p_end)
1795 break;
1796 if (*p == '\r')
1797 p++;
1798 }
1799 return 0;
1800 }
1801
1802 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
1803 {
1804 RTSPState *rt = s->priv_data;
1805 RTSPStream *rtsp_st;
1806 int size, i, err;
1807 char *content;
1808 char url[1024];
1809
1810 if (!ff_network_init())
1811 return AVERROR(EIO);
1812
1813 /* read the whole sdp file */
1814 /* XXX: better loading */
1815 content = av_malloc(SDP_MAX_SIZE);
1816 size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
1817 if (size <= 0) {
1818 av_free(content);
1819 return AVERROR_INVALIDDATA;
1820 }
1821 content[size] ='\0';
1822
1823 err = ff_sdp_parse(s, content);
1824 av_free(content);
1825 if (err) goto fail;
1826
1827 /* open each RTP stream */
1828 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1829 char namebuf[50];
1830 rtsp_st = rt->rtsp_streams[i];
1831
1832 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
1833 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1834 ff_url_join(url, sizeof(url), "rtp", NULL,
1835 namebuf, rtsp_st->sdp_port,
1836 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
1837 rtsp_st->sdp_ttl);
1838 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE) < 0) {
1839 err = AVERROR_INVALIDDATA;
1840 goto fail;
1841 }
1842 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1843 goto fail;
1844 }
1845 return 0;
1846 fail:
1847 ff_rtsp_close_streams(s);
1848 ff_network_close();
1849 return err;
1850 }
1851
1852 static int sdp_read_close(AVFormatContext *s)
1853 {
1854 ff_rtsp_close_streams(s);
1855 ff_network_close();
1856 return 0;
1857 }
1858
1859 AVInputFormat ff_sdp_demuxer = {
1860 .name = "sdp",
1861 .long_name = NULL_IF_CONFIG_SMALL("SDP"),
1862 .priv_data_size = sizeof(RTSPState),
1863 .read_probe = sdp_probe,
1864 .read_header = sdp_read_header,
1865 .read_packet = ff_rtsp_fetch_packet,
1866 .read_close = sdp_read_close,
1867 };
1868 #endif /* CONFIG_SDP_DEMUXER */
1869
1870 #if CONFIG_RTP_DEMUXER
1871 static int rtp_probe(AVProbeData *p)
1872 {
1873 if (av_strstart(p->filename, "rtp:", NULL))
1874 return AVPROBE_SCORE_MAX;
1875 return 0;
1876 }
1877
1878 static int rtp_read_header(AVFormatContext *s,
1879 AVFormatParameters *ap)
1880 {
1881 uint8_t recvbuf[1500];
1882 char host[500], sdp[500];
1883 int ret, port;
1884 URLContext* in = NULL;
1885 int payload_type;
1886 AVCodecContext codec;
1887 struct sockaddr_storage addr;
1888 AVIOContext pb;
1889 socklen_t addrlen = sizeof(addr);
1890
1891 if (!ff_network_init())
1892 return AVERROR(EIO);
1893
1894 ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ);
1895 if (ret)
1896 goto fail;
1897
1898 while (1) {
1899 ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
1900 if (ret == AVERROR(EAGAIN))
1901 continue;
1902 if (ret < 0)
1903 goto fail;
1904 if (ret < 12) {
1905 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
1906 continue;
1907 }
1908
1909 if ((recvbuf[0] & 0xc0) != 0x80) {
1910 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
1911 "received\n");
1912 continue;
1913 }
1914
1915 payload_type = recvbuf[1] & 0x7f;
1916 break;
1917 }
1918 getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
1919 ffurl_close(in);
1920 in = NULL;
1921
1922 memset(&codec, 0, sizeof(codec));
1923 if (ff_rtp_get_codec_info(&codec, payload_type)) {
1924 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
1925 "without an SDP file describing it\n",
1926 payload_type);
1927 goto fail;
1928 }
1929 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
1930 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
1931 "properly you need an SDP file "
1932 "describing it\n");
1933 }
1934
1935 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
1936 NULL, 0, s->filename);
1937
1938 snprintf(sdp, sizeof(sdp),
1939 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
1940 addr.ss_family == AF_INET ? 4 : 6, host,
1941 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
1942 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
1943 port, payload_type);
1944 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
1945
1946 ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
1947 s->pb = &pb;
1948
1949 /* sdp_read_header initializes this again */
1950 ff_network_close();
1951
1952 ret = sdp_read_header(s, ap);
1953 s->pb = NULL;
1954 return ret;
1955
1956 fail:
1957 if (in)
1958 ffurl_close(in);
1959 ff_network_close();
1960 return ret;
1961 }
1962
1963 AVInputFormat ff_rtp_demuxer = {
1964 .name = "rtp",
1965 .long_name = NULL_IF_CONFIG_SMALL("RTP input format"),
1966 .priv_data_size = sizeof(RTSPState),
1967 .read_probe = rtp_probe,
1968 .read_header = rtp_read_header,
1969 .read_packet = ff_rtsp_fetch_packet,
1970 .read_close = sdp_read_close,
1971 .flags = AVFMT_NOFILE,
1972 };
1973 #endif /* CONFIG_RTP_DEMUXER */
1974