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