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