3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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.
12 * FFmpeg 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/random_seed.h"
30 #include <sys/select.h>
35 #include "os_support.h"
41 #include "rtpdec_formats.h"
44 //#define DEBUG_RTP_TCP
46 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
47 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
50 /* Timeout values for socket select, in ms,
51 * and read_packet(), in seconds */
52 #define SELECT_TIMEOUT_MS 100
53 #define READ_PACKET_TIMEOUT_S 10
54 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
55 #define SDP_MAX_SIZE 16384
57 static void get_word_until_chars(char *buf, int buf_size,
58 const char *sep, const char **pp)
64 p += strspn(p, SPACE_CHARS);
66 while (!strchr(sep, *p) && *p != '\0') {
67 if ((q - buf) < buf_size - 1)
76 static void get_word_sep(char *buf, int buf_size, const char *sep,
79 if (**pp == '/') (*pp)++;
80 get_word_until_chars(buf, buf_size, sep, pp);
83 static void get_word(char *buf, int buf_size, const char **pp)
85 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
88 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
89 static int sdp_parse_rtpmap(AVFormatContext *s,
90 AVCodecContext *codec, RTSPStream *rtsp_st,
91 int payload_type, const char *p)
98 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
99 * see if we can handle this kind of payload.
100 * The space should normally not be there but some Real streams or
101 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
102 * have a trailing space. */
103 get_word_sep(buf, sizeof(buf), "/ ", &p);
104 if (payload_type >= RTP_PT_PRIVATE) {
105 RTPDynamicProtocolHandler *handler;
106 for (handler = RTPFirstDynamicPayloadHandler;
107 handler; handler = handler->next) {
108 if (!strcasecmp(buf, handler->enc_name) &&
109 codec->codec_type == handler->codec_type) {
110 codec->codec_id = handler->codec_id;
111 rtsp_st->dynamic_handler = handler;
113 rtsp_st->dynamic_protocol_context = handler->open();
117 /* If no dynamic handler was found, check with the list of standard
118 * allocated types, if such a stream for some reason happens to
119 * use a private payload type. This isn't handled in rtpdec.c, since
120 * the format name from the rtpmap line never is passed into rtpdec. */
121 if (!rtsp_st->dynamic_handler)
122 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
124 /* We are in a standard case
125 * (from http://www.iana.org/assignments/rtp-parameters). */
126 /* search into AVRtpPayloadTypes[] */
127 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
130 c = avcodec_find_decoder(codec->codec_id);
136 get_word_sep(buf, sizeof(buf), "/", &p);
138 switch (codec->codec_type) {
139 case AVMEDIA_TYPE_AUDIO:
140 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
141 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
142 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
144 codec->sample_rate = i;
145 get_word_sep(buf, sizeof(buf), "/", &p);
149 // TODO: there is a bug here; if it is a mono stream, and
150 // less than 22000Hz, faad upconverts to stereo and twice
151 // the frequency. No problem, but the sample rate is being
152 // set here by the sdp line. Patch on its way. (rdm)
154 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
156 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
159 case AVMEDIA_TYPE_VIDEO:
160 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
168 /* parse the attribute line from the fmtp a line of an sdp response. This
169 * is broken out as a function because it is used in rtp_h264.c, which is
171 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
172 char *value, int value_size)
174 *p += strspn(*p, SPACE_CHARS);
176 get_word_sep(attr, attr_size, "=", p);
179 get_word_sep(value, value_size, ";", p);
187 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
189 * Used for seeking in the rtp stream.
191 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
195 p += strspn(p, SPACE_CHARS);
196 if (!av_stristart(p, "npt=", &p))
199 *start = AV_NOPTS_VALUE;
200 *end = AV_NOPTS_VALUE;
202 get_word_sep(buf, sizeof(buf), "-", &p);
203 *start = parse_date(buf, 1);
206 get_word_sep(buf, sizeof(buf), "-", &p);
207 *end = parse_date(buf, 1);
209 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
210 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
213 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
215 struct addrinfo hints, *ai = NULL;
216 memset(&hints, 0, sizeof(hints));
217 hints.ai_flags = AI_NUMERICHOST;
218 if (getaddrinfo(buf, NULL, &hints, &ai))
220 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
225 typedef struct SDPParseState {
227 struct sockaddr_storage default_ip;
229 int skip_media; ///< set if an unknown m= line occurs
232 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
233 int letter, const char *buf)
235 RTSPState *rt = s->priv_data;
236 char buf1[64], st_type[64];
238 enum AVMediaType codec_type;
242 struct sockaddr_storage sdp_ip;
245 dprintf(s, "sdp: %c='%s'\n", letter, buf);
248 if (s1->skip_media && letter != 'm')
252 get_word(buf1, sizeof(buf1), &p);
253 if (strcmp(buf1, "IN") != 0)
255 get_word(buf1, sizeof(buf1), &p);
256 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
258 get_word_sep(buf1, sizeof(buf1), "/", &p);
259 if (get_sockaddr(buf1, &sdp_ip))
264 get_word_sep(buf1, sizeof(buf1), "/", &p);
267 if (s->nb_streams == 0) {
268 s1->default_ip = sdp_ip;
269 s1->default_ttl = ttl;
271 st = s->streams[s->nb_streams - 1];
272 rtsp_st = st->priv_data;
273 rtsp_st->sdp_ip = sdp_ip;
274 rtsp_st->sdp_ttl = ttl;
278 av_metadata_set2(&s->metadata, "title", p, 0);
281 if (s->nb_streams == 0) {
282 av_metadata_set2(&s->metadata, "comment", p, 0);
289 get_word(st_type, sizeof(st_type), &p);
290 if (!strcmp(st_type, "audio")) {
291 codec_type = AVMEDIA_TYPE_AUDIO;
292 } else if (!strcmp(st_type, "video")) {
293 codec_type = AVMEDIA_TYPE_VIDEO;
294 } else if (!strcmp(st_type, "application")) {
295 codec_type = AVMEDIA_TYPE_DATA;
300 rtsp_st = av_mallocz(sizeof(RTSPStream));
303 rtsp_st->stream_index = -1;
304 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
306 rtsp_st->sdp_ip = s1->default_ip;
307 rtsp_st->sdp_ttl = s1->default_ttl;
309 get_word(buf1, sizeof(buf1), &p); /* port */
310 rtsp_st->sdp_port = atoi(buf1);
312 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
314 /* XXX: handle list of formats */
315 get_word(buf1, sizeof(buf1), &p); /* format list */
316 rtsp_st->sdp_payload_type = atoi(buf1);
318 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
319 /* no corresponding stream */
321 st = av_new_stream(s, 0);
324 st->priv_data = rtsp_st;
325 rtsp_st->stream_index = st->index;
326 st->codec->codec_type = codec_type;
327 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
328 /* if standard payload type, we can find the codec right now */
329 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
332 /* put a default control url */
333 av_strlcpy(rtsp_st->control_url, rt->control_uri,
334 sizeof(rtsp_st->control_url));
337 if (av_strstart(p, "control:", &p)) {
338 if (s->nb_streams == 0) {
339 if (!strncmp(p, "rtsp://", 7))
340 av_strlcpy(rt->control_uri, p,
341 sizeof(rt->control_uri));
344 /* get the control url */
345 st = s->streams[s->nb_streams - 1];
346 rtsp_st = st->priv_data;
348 /* XXX: may need to add full url resolution */
349 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
351 if (proto[0] == '\0') {
352 /* relative control URL */
353 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
354 av_strlcat(rtsp_st->control_url, "/",
355 sizeof(rtsp_st->control_url));
356 av_strlcat(rtsp_st->control_url, p,
357 sizeof(rtsp_st->control_url));
359 av_strlcpy(rtsp_st->control_url, p,
360 sizeof(rtsp_st->control_url));
362 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
363 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
364 get_word(buf1, sizeof(buf1), &p);
365 payload_type = atoi(buf1);
366 st = s->streams[s->nb_streams - 1];
367 rtsp_st = st->priv_data;
368 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
369 } else if (av_strstart(p, "fmtp:", &p) ||
370 av_strstart(p, "framesize:", &p)) {
371 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
372 // let dynamic protocol handlers have a stab at the line.
373 get_word(buf1, sizeof(buf1), &p);
374 payload_type = atoi(buf1);
375 for (i = 0; i < s->nb_streams; i++) {
377 rtsp_st = st->priv_data;
378 if (rtsp_st->sdp_payload_type == payload_type &&
379 rtsp_st->dynamic_handler &&
380 rtsp_st->dynamic_handler->parse_sdp_a_line)
381 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
382 rtsp_st->dynamic_protocol_context, buf);
384 } else if (av_strstart(p, "range:", &p)) {
387 // this is so that seeking on a streamed file can work.
388 rtsp_parse_range_npt(p, &start, &end);
389 s->start_time = start;
390 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
391 s->duration = (end == AV_NOPTS_VALUE) ?
392 AV_NOPTS_VALUE : end - start;
393 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
395 rt->transport = RTSP_TRANSPORT_RDT;
397 if (rt->server_type == RTSP_SERVER_WMS)
398 ff_wms_parse_sdp_a_line(s, p);
399 if (s->nb_streams > 0) {
400 if (rt->server_type == RTSP_SERVER_REAL)
401 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
403 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
404 if (rtsp_st->dynamic_handler &&
405 rtsp_st->dynamic_handler->parse_sdp_a_line)
406 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
408 rtsp_st->dynamic_protocol_context, buf);
415 static int sdp_parse(AVFormatContext *s, const char *content)
419 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
420 * contain long SDP lines containing complete ASF Headers (several
421 * kB) or arrays of MDPR (RM stream descriptor) headers plus
422 * "rulebooks" describing their properties. Therefore, the SDP line
425 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
426 * in rtpdec_xiph.c. */
428 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
430 memset(s1, 0, sizeof(SDPParseState));
433 p += strspn(p, SPACE_CHARS);
441 /* get the content */
443 while (*p != '\n' && *p != '\r' && *p != '\0') {
444 if ((q - buf) < sizeof(buf) - 1)
449 sdp_parse_line(s, s1, letter, buf);
451 while (*p != '\n' && *p != '\0')
459 /* close and free RTSP streams */
460 void ff_rtsp_close_streams(AVFormatContext *s)
462 RTSPState *rt = s->priv_data;
466 for (i = 0; i < rt->nb_rtsp_streams; i++) {
467 rtsp_st = rt->rtsp_streams[i];
469 if (rtsp_st->transport_priv) {
471 AVFormatContext *rtpctx = rtsp_st->transport_priv;
472 av_write_trailer(rtpctx);
473 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
475 url_close_dyn_buf(rtpctx->pb, &ptr);
478 url_fclose(rtpctx->pb);
480 av_metadata_free(&rtpctx->streams[0]->metadata);
481 av_metadata_free(&rtpctx->metadata);
482 av_free(rtpctx->streams[0]);
484 } else if (rt->transport == RTSP_TRANSPORT_RDT)
485 ff_rdt_parse_close(rtsp_st->transport_priv);
487 rtp_parse_close(rtsp_st->transport_priv);
489 if (rtsp_st->rtp_handle)
490 url_close(rtsp_st->rtp_handle);
491 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
492 rtsp_st->dynamic_handler->close(
493 rtsp_st->dynamic_protocol_context);
496 av_free(rt->rtsp_streams);
498 av_close_input_stream (rt->asf_ctx);
503 static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
506 RTSPState *rt = s->priv_data;
507 AVFormatContext *rtpctx;
509 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
514 /* Allocate an AVFormatContext for each output stream */
515 rtpctx = avformat_alloc_context();
519 rtpctx->oformat = rtp_format;
520 if (!av_new_stream(rtpctx, 0)) {
524 /* Copy the max delay setting; the rtp muxer reads this. */
525 rtpctx->max_delay = s->max_delay;
526 /* Copy other stream parameters. */
527 rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
529 /* Set the synchronized start time. */
530 rtpctx->start_time_realtime = rt->start_time;
532 /* Remove the local codec, link to the original codec
533 * context instead, to give the rtp muxer access to
534 * codec parameters. */
535 av_free(rtpctx->streams[0]->codec);
536 rtpctx->streams[0]->codec = st->codec;
539 url_fdopen(&rtpctx->pb, handle);
541 url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
542 ret = av_write_header(rtpctx);
546 url_fclose(rtpctx->pb);
549 url_close_dyn_buf(rtpctx->pb, &ptr);
552 av_free(rtpctx->streams[0]);
557 /* Copy the RTP AVStream timebase back to the original AVStream */
558 st->time_base = rtpctx->streams[0]->time_base;
562 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
564 RTSPState *rt = s->priv_data;
567 /* open the RTP context */
568 if (rtsp_st->stream_index >= 0)
569 st = s->streams[rtsp_st->stream_index];
571 s->ctx_flags |= AVFMTCTX_NOHEADER;
574 rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
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)
578 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
579 rtsp_st->dynamic_protocol_context,
580 rtsp_st->dynamic_handler);
582 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
583 rtsp_st->sdp_payload_type);
585 if (!rtsp_st->transport_priv) {
586 return AVERROR(ENOMEM);
587 } else if (rt->transport != RTSP_TRANSPORT_RDT) {
588 if (rtsp_st->dynamic_handler) {
589 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
590 rtsp_st->dynamic_protocol_context,
591 rtsp_st->dynamic_handler);
598 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
599 static int rtsp_probe(AVProbeData *p)
601 if (av_strstart(p->filename, "rtsp:", NULL))
602 return AVPROBE_SCORE_MAX;
606 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
612 p += strspn(p, SPACE_CHARS);
613 v = strtol(p, (char **)&p, 10);
617 v = strtol(p, (char **)&p, 10);
626 /* XXX: only one transport specification is parsed */
627 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
629 char transport_protocol[16];
631 char lower_transport[16];
633 RTSPTransportField *th;
636 reply->nb_transports = 0;
639 p += strspn(p, SPACE_CHARS);
643 th = &reply->transports[reply->nb_transports];
645 get_word_sep(transport_protocol, sizeof(transport_protocol),
647 if (!strcasecmp (transport_protocol, "rtp")) {
648 get_word_sep(profile, sizeof(profile), "/;,", &p);
649 lower_transport[0] = '\0';
650 /* rtp/avp/<protocol> */
652 get_word_sep(lower_transport, sizeof(lower_transport),
655 th->transport = RTSP_TRANSPORT_RTP;
656 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
657 !strcasecmp (transport_protocol, "x-real-rdt")) {
658 /* x-pn-tng/<protocol> */
659 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
661 th->transport = RTSP_TRANSPORT_RDT;
663 if (!strcasecmp(lower_transport, "TCP"))
664 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
666 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
670 /* get each parameter */
671 while (*p != '\0' && *p != ',') {
672 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
673 if (!strcmp(parameter, "port")) {
676 rtsp_parse_range(&th->port_min, &th->port_max, &p);
678 } else if (!strcmp(parameter, "client_port")) {
681 rtsp_parse_range(&th->client_port_min,
682 &th->client_port_max, &p);
684 } else if (!strcmp(parameter, "server_port")) {
687 rtsp_parse_range(&th->server_port_min,
688 &th->server_port_max, &p);
690 } else if (!strcmp(parameter, "interleaved")) {
693 rtsp_parse_range(&th->interleaved_min,
694 &th->interleaved_max, &p);
696 } else if (!strcmp(parameter, "multicast")) {
697 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
698 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
699 } else if (!strcmp(parameter, "ttl")) {
702 th->ttl = strtol(p, (char **)&p, 10);
704 } else if (!strcmp(parameter, "destination")) {
707 get_word_sep(buf, sizeof(buf), ";,", &p);
708 get_sockaddr(buf, &th->destination);
710 } else if (!strcmp(parameter, "source")) {
713 get_word_sep(buf, sizeof(buf), ";,", &p);
714 av_strlcpy(th->source, buf, sizeof(th->source));
718 while (*p != ';' && *p != '\0' && *p != ',')
726 reply->nb_transports++;
730 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
731 HTTPAuthState *auth_state)
735 /* NOTE: we do case independent match for broken servers */
737 if (av_stristart(p, "Session:", &p)) {
739 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
740 if (av_stristart(p, ";timeout=", &p) &&
741 (t = strtol(p, NULL, 10)) > 0) {
744 } else if (av_stristart(p, "Content-Length:", &p)) {
745 reply->content_length = strtol(p, NULL, 10);
746 } else if (av_stristart(p, "Transport:", &p)) {
747 rtsp_parse_transport(reply, p);
748 } else if (av_stristart(p, "CSeq:", &p)) {
749 reply->seq = strtol(p, NULL, 10);
750 } else if (av_stristart(p, "Range:", &p)) {
751 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
752 } else if (av_stristart(p, "RealChallenge1:", &p)) {
753 p += strspn(p, SPACE_CHARS);
754 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
755 } else if (av_stristart(p, "Server:", &p)) {
756 p += strspn(p, SPACE_CHARS);
757 av_strlcpy(reply->server, p, sizeof(reply->server));
758 } else if (av_stristart(p, "Notice:", &p) ||
759 av_stristart(p, "X-Notice:", &p)) {
760 reply->notice = strtol(p, NULL, 10);
761 } else if (av_stristart(p, "Location:", &p)) {
762 p += strspn(p, SPACE_CHARS);
763 av_strlcpy(reply->location, p , sizeof(reply->location));
764 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
765 p += strspn(p, SPACE_CHARS);
766 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
767 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
768 p += strspn(p, SPACE_CHARS);
769 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
773 /* skip a RTP/TCP interleaved packet */
774 void ff_rtsp_skip_packet(AVFormatContext *s)
776 RTSPState *rt = s->priv_data;
780 ret = url_read_complete(rt->rtsp_hd, buf, 3);
783 len = AV_RB16(buf + 1);
785 dprintf(s, "skipping RTP packet len=%d\n", len);
790 if (len1 > sizeof(buf))
792 ret = url_read_complete(rt->rtsp_hd, buf, len1);
799 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
800 unsigned char **content_ptr,
801 int return_on_interleaved_data)
803 RTSPState *rt = s->priv_data;
804 char buf[4096], buf1[1024], *q;
807 int ret, content_length, line_count = 0;
808 unsigned char *content = NULL;
810 memset(reply, 0, sizeof(*reply));
812 /* parse reply (XXX: use buffers) */
813 rt->last_reply[0] = '\0';
817 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
819 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
826 /* XXX: only parse it if first char on line ? */
827 if (return_on_interleaved_data) {
830 ff_rtsp_skip_packet(s);
831 } else if (ch != '\r') {
832 if ((q - buf) < sizeof(buf) - 1)
838 dprintf(s, "line='%s'\n", buf);
840 /* test if last line */
844 if (line_count == 0) {
846 get_word(buf1, sizeof(buf1), &p);
847 get_word(buf1, sizeof(buf1), &p);
848 reply->status_code = atoi(buf1);
849 av_strlcpy(reply->reason, p, sizeof(reply->reason));
851 ff_rtsp_parse_line(reply, p, &rt->auth_state);
852 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
853 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
858 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
859 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
861 content_length = reply->content_length;
862 if (content_length > 0) {
863 /* leave some room for a trailing '\0' (useful for simple parsing) */
864 content = av_malloc(content_length + 1);
865 (void)url_read_complete(rt->rtsp_hd, content, content_length);
866 content[content_length] = '\0';
869 *content_ptr = content;
873 if (rt->seq != reply->seq) {
874 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
875 rt->seq, reply->seq);
879 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
880 reply->notice == 2104 /* Start-of-Stream Reached */ ||
881 reply->notice == 2306 /* Continuous Feed Terminated */) {
882 rt->state = RTSP_STATE_IDLE;
883 } else if (reply->notice >= 4400 && reply->notice < 5500) {
884 return AVERROR(EIO); /* data or server error */
885 } else if (reply->notice == 2401 /* Ticket Expired */ ||
886 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
887 return AVERROR(EPERM);
892 int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
893 const char *method, const char *url,
895 const unsigned char *send_content,
896 int send_content_length)
898 RTSPState *rt = s->priv_data;
899 char buf[4096], *out_buf;
900 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
902 /* Add in RTSP headers */
905 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
907 av_strlcat(buf, headers, sizeof(buf));
908 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
909 if (rt->session_id[0] != '\0' && (!headers ||
910 !strstr(headers, "\nIf-Match:"))) {
911 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
914 char *str = ff_http_auth_create_response(&rt->auth_state,
915 rt->auth, url, method);
917 av_strlcat(buf, str, sizeof(buf));
920 if (send_content_length > 0 && send_content)
921 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
922 av_strlcat(buf, "\r\n", sizeof(buf));
924 /* base64 encode rtsp if tunneling */
925 if (rt->control_transport == RTSP_MODE_TUNNEL) {
926 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
930 dprintf(s, "Sending:\n%s--\n", buf);
932 url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
933 if (send_content_length > 0 && send_content) {
934 if (rt->control_transport == RTSP_MODE_TUNNEL) {
935 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
936 "with content data not supported\n");
937 return AVERROR_PATCHWELCOME;
939 url_write(rt->rtsp_hd_out, send_content, send_content_length);
941 rt->last_cmd_time = av_gettime();
946 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
947 const char *url, const char *headers)
949 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
952 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
953 const char *headers, RTSPMessageHeader *reply,
954 unsigned char **content_ptr)
956 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
957 content_ptr, NULL, 0);
960 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
961 const char *method, const char *url,
963 RTSPMessageHeader *reply,
964 unsigned char **content_ptr,
965 const unsigned char *send_content,
966 int send_content_length)
968 RTSPState *rt = s->priv_data;
969 HTTPAuthType cur_auth_type;
973 cur_auth_type = rt->auth_state.auth_type;
974 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
976 send_content_length)))
979 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
982 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
983 rt->auth_state.auth_type != HTTP_AUTH_NONE)
986 if (reply->status_code > 400){
987 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
991 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
998 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
1000 static int make_setup_request(AVFormatContext *s, const char *host, int port,
1001 int lower_transport, const char *real_challenge)
1003 RTSPState *rt = s->priv_data;
1004 int rtx, j, i, err, interleave = 0;
1005 RTSPStream *rtsp_st;
1006 RTSPMessageHeader reply1, *reply = &reply1;
1008 const char *trans_pref;
1010 if (rt->transport == RTSP_TRANSPORT_RDT)
1011 trans_pref = "x-pn-tng";
1013 trans_pref = "RTP/AVP";
1015 /* default timeout: 1 minute */
1018 /* for each stream, make the setup request */
1019 /* XXX: we assume the same server is used for the control of each
1022 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1023 char transport[2048];
1026 * WMS serves all UDP data over a single connection, the RTX, which
1027 * isn't necessarily the first in the SDP but has to be the first
1028 * to be set up, else the second/third SETUP will fail with a 461.
1030 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1031 rt->server_type == RTSP_SERVER_WMS) {
1034 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1035 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1037 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1041 if (rtx == rt->nb_rtsp_streams)
1042 return -1; /* no RTX found */
1043 rtsp_st = rt->rtsp_streams[rtx];
1045 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1047 rtsp_st = rt->rtsp_streams[i];
1050 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1053 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1054 port = reply->transports[0].client_port_min;
1058 /* first try in specified port range */
1059 if (RTSP_RTP_PORT_MIN != 0) {
1060 while (j <= RTSP_RTP_PORT_MAX) {
1061 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1062 "?localport=%d", j);
1063 /* we will use two ports per rtp stream (rtp and rtcp) */
1065 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1071 /* then try on any port */
1072 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1073 err = AVERROR_INVALIDDATA;
1079 port = rtp_get_local_port(rtsp_st->rtp_handle);
1081 snprintf(transport, sizeof(transport) - 1,
1082 "%s/UDP;", trans_pref);
1083 if (rt->server_type != RTSP_SERVER_REAL)
1084 av_strlcat(transport, "unicast;", sizeof(transport));
1085 av_strlcatf(transport, sizeof(transport),
1086 "client_port=%d", port);
1087 if (rt->transport == RTSP_TRANSPORT_RTP &&
1088 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1089 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1093 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1094 /** For WMS streams, the application streams are only used for
1095 * UDP. When trying to set it up for TCP streams, the server
1096 * will return an error. Therefore, we skip those streams. */
1097 if (rt->server_type == RTSP_SERVER_WMS &&
1098 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1101 snprintf(transport, sizeof(transport) - 1,
1102 "%s/TCP;", trans_pref);
1103 if (rt->server_type == RTSP_SERVER_WMS)
1104 av_strlcat(transport, "unicast;", sizeof(transport));
1105 av_strlcatf(transport, sizeof(transport),
1106 "interleaved=%d-%d",
1107 interleave, interleave + 1);
1111 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1112 snprintf(transport, sizeof(transport) - 1,
1113 "%s/UDP;multicast", trans_pref);
1116 av_strlcat(transport, ";mode=receive", sizeof(transport));
1117 } else if (rt->server_type == RTSP_SERVER_REAL ||
1118 rt->server_type == RTSP_SERVER_WMS)
1119 av_strlcat(transport, ";mode=play", sizeof(transport));
1120 snprintf(cmd, sizeof(cmd),
1121 "Transport: %s\r\n",
1123 if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1124 char real_res[41], real_csum[9];
1125 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1127 av_strlcatf(cmd, sizeof(cmd),
1129 "RealChallenge2: %s, sd=%s\r\n",
1130 rt->session_id, real_res, real_csum);
1132 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1133 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1136 } else if (reply->status_code != RTSP_STATUS_OK ||
1137 reply->nb_transports != 1) {
1138 err = AVERROR_INVALIDDATA;
1142 /* XXX: same protocol for all streams is required */
1144 if (reply->transports[0].lower_transport != rt->lower_transport ||
1145 reply->transports[0].transport != rt->transport) {
1146 err = AVERROR_INVALIDDATA;
1150 rt->lower_transport = reply->transports[0].lower_transport;
1151 rt->transport = reply->transports[0].transport;
1154 /* close RTP connection if not chosen */
1155 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1156 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1157 url_close(rtsp_st->rtp_handle);
1158 rtsp_st->rtp_handle = NULL;
1161 switch(reply->transports[0].lower_transport) {
1162 case RTSP_LOWER_TRANSPORT_TCP:
1163 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1164 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1167 case RTSP_LOWER_TRANSPORT_UDP: {
1170 /* Use source address if specified */
1171 if (reply->transports[0].source[0]) {
1172 ff_url_join(url, sizeof(url), "rtp", NULL,
1173 reply->transports[0].source,
1174 reply->transports[0].server_port_min, NULL);
1176 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1177 reply->transports[0].server_port_min, NULL);
1179 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1180 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1181 err = AVERROR_INVALIDDATA;
1184 /* Try to initialize the connection state in a
1185 * potential NAT router by sending dummy packets.
1186 * RTP/RTCP dummy packets are used for RDT, too.
1188 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1189 rtp_send_punch_packets(rtsp_st->rtp_handle);
1192 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1193 char url[1024], namebuf[50];
1194 struct sockaddr_storage addr;
1197 if (reply->transports[0].destination.ss_family) {
1198 addr = reply->transports[0].destination;
1199 port = reply->transports[0].port_min;
1200 ttl = reply->transports[0].ttl;
1202 addr = rtsp_st->sdp_ip;
1203 port = rtsp_st->sdp_port;
1204 ttl = rtsp_st->sdp_ttl;
1206 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1207 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1208 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1209 port, "?ttl=%d", ttl);
1210 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1211 err = AVERROR_INVALIDDATA;
1218 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1222 if (reply->timeout > 0)
1223 rt->timeout = reply->timeout;
1225 if (rt->server_type == RTSP_SERVER_REAL)
1226 rt->need_subscription = 1;
1231 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1232 if (rt->rtsp_streams[i]->rtp_handle) {
1233 url_close(rt->rtsp_streams[i]->rtp_handle);
1234 rt->rtsp_streams[i]->rtp_handle = NULL;
1240 static int rtsp_read_play(AVFormatContext *s)
1242 RTSPState *rt = s->priv_data;
1243 RTSPMessageHeader reply1, *reply = &reply1;
1247 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1250 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1251 if (rt->state == RTSP_STATE_PAUSED) {
1254 snprintf(cmd, sizeof(cmd),
1255 "Range: npt=%0.3f-\r\n",
1256 (double)rt->seek_timestamp / AV_TIME_BASE);
1258 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1259 if (reply->status_code != RTSP_STATUS_OK) {
1262 if (reply->range_start != AV_NOPTS_VALUE &&
1263 rt->transport == RTSP_TRANSPORT_RTP) {
1264 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1265 RTSPStream *rtsp_st = rt->rtsp_streams[i];
1266 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1267 AVStream *st = NULL;
1270 if (rtsp_st->stream_index >= 0)
1271 st = s->streams[rtsp_st->stream_index];
1272 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
1273 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1275 rtpctx->range_start_offset = av_rescale_q(reply->range_start,
1281 rt->state = RTSP_STATE_STREAMING;
1285 static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1287 RTSPState *rt = s->priv_data;
1289 unsigned char *content = NULL;
1292 /* describe the stream */
1293 snprintf(cmd, sizeof(cmd),
1294 "Accept: application/sdp\r\n");
1295 if (rt->server_type == RTSP_SERVER_REAL) {
1297 * The Require: attribute is needed for proper streaming from
1298 * Realmedia servers.
1301 "Require: com.real.retain-entity-for-setup\r\n",
1304 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1306 return AVERROR_INVALIDDATA;
1307 if (reply->status_code != RTSP_STATUS_OK) {
1309 return AVERROR_INVALIDDATA;
1312 /* now we got the SDP description, we parse it */
1313 ret = sdp_parse(s, (const char *)content);
1316 return AVERROR_INVALIDDATA;
1321 static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1323 RTSPState *rt = s->priv_data;
1324 RTSPMessageHeader reply1, *reply = &reply1;
1327 AVFormatContext sdp_ctx, *ctx_array[1];
1329 rt->start_time = av_gettime();
1331 /* Announce the stream */
1332 sdp = av_mallocz(SDP_MAX_SIZE);
1334 return AVERROR(ENOMEM);
1335 /* We create the SDP based on the RTSP AVFormatContext where we
1336 * aren't allowed to change the filename field. (We create the SDP
1337 * based on the RTSP context since the contexts for the RTP streams
1338 * don't exist yet.) In order to specify a custom URL with the actual
1339 * peer IP instead of the originally specified hostname, we create
1340 * a temporary copy of the AVFormatContext, where the custom URL is set.
1342 * FIXME: Create the SDP without copying the AVFormatContext.
1343 * This either requires setting up the RTP stream AVFormatContexts
1344 * already here (complicating things immensely) or getting a more
1345 * flexible SDP creation interface.
1348 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1349 "rtsp", NULL, addr, -1, NULL);
1350 ctx_array[0] = &sdp_ctx;
1351 if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
1353 return AVERROR_INVALIDDATA;
1355 av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
1356 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1357 "Content-Type: application/sdp\r\n",
1358 reply, NULL, sdp, strlen(sdp));
1360 if (reply->status_code != RTSP_STATUS_OK)
1361 return AVERROR_INVALIDDATA;
1363 /* Set up the RTSPStreams for each AVStream */
1364 for (i = 0; i < s->nb_streams; i++) {
1365 RTSPStream *rtsp_st;
1366 AVStream *st = s->streams[i];
1368 rtsp_st = av_mallocz(sizeof(RTSPStream));
1370 return AVERROR(ENOMEM);
1371 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1373 st->priv_data = rtsp_st;
1374 rtsp_st->stream_index = i;
1376 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1377 /* Note, this must match the relative uri set in the sdp content */
1378 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1385 void ff_rtsp_close_connections(AVFormatContext *s)
1387 RTSPState *rt = s->priv_data;
1388 if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1389 url_close(rt->rtsp_hd);
1390 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1393 int ff_rtsp_connect(AVFormatContext *s)
1395 RTSPState *rt = s->priv_data;
1396 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1397 char *option_list, *option, *filename;
1398 int port, err, tcp_fd;
1399 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1400 int lower_transport_mask = 0;
1401 char real_challenge[64];
1402 struct sockaddr_storage peer;
1403 socklen_t peer_len = sizeof(peer);
1405 if (!ff_network_init())
1406 return AVERROR(EIO);
1408 rt->control_transport = RTSP_MODE_PLAIN;
1409 /* extract hostname and port */
1410 av_url_split(NULL, 0, auth, sizeof(auth),
1411 host, sizeof(host), &port, path, sizeof(path), s->filename);
1413 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1416 port = RTSP_DEFAULT_PORT;
1418 /* search for options */
1419 option_list = strrchr(path, '?');
1421 /* Strip out the RTSP specific options, write out the rest of
1422 * the options back into the same string. */
1423 filename = option_list;
1424 while (option_list) {
1425 /* move the option pointer */
1426 option = ++option_list;
1427 option_list = strchr(option_list, '&');
1431 /* handle the options */
1432 if (!strcmp(option, "udp")) {
1433 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1434 } else if (!strcmp(option, "multicast")) {
1435 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1436 } else if (!strcmp(option, "tcp")) {
1437 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1438 } else if(!strcmp(option, "http")) {
1439 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1440 rt->control_transport = RTSP_MODE_TUNNEL;
1442 /* Write options back into the buffer, using memmove instead
1443 * of strcpy since the strings may overlap. */
1444 int len = strlen(option);
1445 memmove(++filename, option, len);
1447 if (option_list) *filename = '&';
1453 if (!lower_transport_mask)
1454 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1457 /* Only UDP or TCP - UDP multicast isn't supported. */
1458 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1459 (1 << RTSP_LOWER_TRANSPORT_TCP);
1460 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1461 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1462 "only UDP and TCP are supported for output.\n");
1463 err = AVERROR(EINVAL);
1468 /* Construct the URI used in request; this is similar to s->filename,
1469 * but with authentication credentials removed and RTSP specific options
1471 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1472 host, port, "%s", path);
1474 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1475 /* set up initial handshake for tunneling */
1476 char httpname[1024];
1477 char sessioncookie[17];
1480 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1481 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1482 av_get_random_seed(), av_get_random_seed());
1485 if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
1490 /* generate GET headers */
1491 snprintf(headers, sizeof(headers),
1492 "x-sessioncookie: %s\r\n"
1493 "Accept: application/x-rtsp-tunnelled\r\n"
1494 "Pragma: no-cache\r\n"
1495 "Cache-Control: no-cache\r\n",
1497 ff_http_set_headers(rt->rtsp_hd, headers);
1499 /* complete the connection */
1500 if (url_connect(rt->rtsp_hd)) {
1506 if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1511 /* generate POST headers */
1512 snprintf(headers, sizeof(headers),
1513 "x-sessioncookie: %s\r\n"
1514 "Content-Type: application/x-rtsp-tunnelled\r\n"
1515 "Pragma: no-cache\r\n"
1516 "Cache-Control: no-cache\r\n"
1517 "Content-Length: 32767\r\n"
1518 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1520 ff_http_set_headers(rt->rtsp_hd_out, headers);
1521 ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1523 /* Initialize the authentication state for the POST session. The HTTP
1524 * protocol implementation doesn't properly handle multi-pass
1525 * authentication for POST requests, since it would require one of
1527 * - implementing Expect: 100-continue, which many HTTP servers
1528 * don't support anyway, even less the RTSP servers that do HTTP
1530 * - sending the whole POST data until getting a 401 reply specifying
1531 * what authentication method to use, then resending all that data
1532 * - waiting for potential 401 replies directly after sending the
1533 * POST header (waiting for some unspecified time)
1534 * Therefore, we copy the full auth state, which works for both basic
1535 * and digest. (For digest, we would have to synchronize the nonce
1536 * count variable between the two sessions, if we'd do more requests
1537 * with the original session, though.)
1539 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1541 /* complete the connection */
1542 if (url_connect(rt->rtsp_hd_out)) {
1547 /* open the tcp connection */
1548 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1549 if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
1553 rt->rtsp_hd_out = rt->rtsp_hd;
1557 tcp_fd = url_get_file_handle(rt->rtsp_hd);
1558 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1559 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1560 NULL, 0, NI_NUMERICHOST);
1563 /* request options supported by the server; this also detects server
1565 for (rt->server_type = RTSP_SERVER_RTP;;) {
1567 if (rt->server_type == RTSP_SERVER_REAL)
1570 * The following entries are required for proper
1571 * streaming from a Realmedia server. They are
1572 * interdependent in some way although we currently
1573 * don't quite understand how. Values were copied
1574 * from mplayer SVN r23589.
1575 * @param CompanyID is a 16-byte ID in base64
1576 * @param ClientChallenge is a 16-byte ID in hex
1578 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1579 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1580 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1581 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1583 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1584 if (reply->status_code != RTSP_STATUS_OK) {
1585 err = AVERROR_INVALIDDATA;
1589 /* detect server type if not standard-compliant RTP */
1590 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1591 rt->server_type = RTSP_SERVER_REAL;
1593 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1594 rt->server_type = RTSP_SERVER_WMS;
1595 } else if (rt->server_type == RTSP_SERVER_REAL)
1596 strcpy(real_challenge, reply->real_challenge);
1601 err = rtsp_setup_input_streams(s, reply);
1603 err = rtsp_setup_output_streams(s, host);
1608 int lower_transport = ff_log2_tab[lower_transport_mask &
1609 ~(lower_transport_mask - 1)];
1611 err = make_setup_request(s, host, port, lower_transport,
1612 rt->server_type == RTSP_SERVER_REAL ?
1613 real_challenge : NULL);
1616 lower_transport_mask &= ~(1 << lower_transport);
1617 if (lower_transport_mask == 0 && err == 1) {
1618 err = FF_NETERROR(EPROTONOSUPPORT);
1623 rt->state = RTSP_STATE_IDLE;
1624 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1627 ff_rtsp_close_streams(s);
1628 ff_rtsp_close_connections(s);
1629 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1630 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1631 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1641 #if CONFIG_RTSP_DEMUXER
1642 static int rtsp_read_header(AVFormatContext *s,
1643 AVFormatParameters *ap)
1645 RTSPState *rt = s->priv_data;
1648 ret = ff_rtsp_connect(s);
1652 rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
1653 if (!rt->real_setup_cache)
1654 return AVERROR(ENOMEM);
1655 rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
1657 if (ap->initial_pause) {
1658 /* do not start immediately */
1660 if (rtsp_read_play(s) < 0) {
1661 ff_rtsp_close_streams(s);
1662 ff_rtsp_close_connections(s);
1663 return AVERROR_INVALIDDATA;
1670 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1671 uint8_t *buf, int buf_size)
1673 RTSPState *rt = s->priv_data;
1674 RTSPStream *rtsp_st;
1676 int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1680 if (url_interrupt_cb())
1681 return AVERROR(EINTR);
1684 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1685 FD_SET(tcp_fd, &rfds);
1690 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1691 rtsp_st = rt->rtsp_streams[i];
1692 if (rtsp_st->rtp_handle) {
1693 fd = url_get_file_handle(rtsp_st->rtp_handle);
1694 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1695 if (FFMAX(fd, fd_rtcp) > fd_max)
1696 fd_max = FFMAX(fd, fd_rtcp);
1698 FD_SET(fd_rtcp, &rfds);
1702 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1703 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1706 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1707 rtsp_st = rt->rtsp_streams[i];
1708 if (rtsp_st->rtp_handle) {
1709 fd = url_get_file_handle(rtsp_st->rtp_handle);
1710 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1711 if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
1712 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1714 *prtsp_st = rtsp_st;
1720 #if CONFIG_RTSP_DEMUXER
1721 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1722 RTSPMessageHeader reply;
1724 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1727 /* XXX: parse message */
1728 if (rt->state != RTSP_STATE_STREAMING)
1732 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1733 return FF_NETERROR(ETIMEDOUT);
1734 } else if (n < 0 && errno != EINTR)
1735 return AVERROR(errno);
1739 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1740 uint8_t *buf, int buf_size)
1742 RTSPState *rt = s->priv_data;
1743 int id, len, i, ret;
1744 RTSPStream *rtsp_st;
1746 #ifdef DEBUG_RTP_TCP
1747 dprintf(s, "tcp_read_packet:\n");
1751 RTSPMessageHeader reply;
1753 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1756 if (ret == 1) /* received '$' */
1758 /* XXX: parse message */
1759 if (rt->state != RTSP_STATE_STREAMING)
1762 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1766 len = AV_RB16(buf + 1);
1767 #ifdef DEBUG_RTP_TCP
1768 dprintf(s, "id=%d len=%d\n", id, len);
1770 if (len > buf_size || len < 12)
1773 ret = url_read_complete(rt->rtsp_hd, buf, len);
1776 if (rt->transport == RTSP_TRANSPORT_RDT &&
1777 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1780 /* find the matching stream */
1781 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1782 rtsp_st = rt->rtsp_streams[i];
1783 if (id >= rtsp_st->interleaved_min &&
1784 id <= rtsp_st->interleaved_max)
1789 *prtsp_st = rtsp_st;
1793 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1795 RTSPState *rt = s->priv_data;
1797 uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1798 RTSPStream *rtsp_st;
1800 if (rt->nb_byes == rt->nb_rtsp_streams)
1803 /* get next frames from the same RTP packet */
1804 if (rt->cur_transport_priv) {
1805 if (rt->transport == RTSP_TRANSPORT_RDT) {
1806 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1808 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1810 rt->cur_transport_priv = NULL;
1812 } else if (ret == 1) {
1815 rt->cur_transport_priv = NULL;
1818 /* read next RTP packet */
1820 switch(rt->lower_transport) {
1822 #if CONFIG_RTSP_DEMUXER
1823 case RTSP_LOWER_TRANSPORT_TCP:
1824 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1827 case RTSP_LOWER_TRANSPORT_UDP:
1828 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1829 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1830 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1831 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1838 if (rt->transport == RTSP_TRANSPORT_RDT) {
1839 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1841 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1843 /* Either bad packet, or a RTCP packet. Check if the
1844 * first_rtcp_ntp_time field was initialized. */
1845 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1846 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1847 /* first_rtcp_ntp_time has been initialized for this stream,
1848 * copy the same value to all other uninitialized streams,
1849 * in order to map their timestamp origin to the same ntp time
1852 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1853 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1855 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1856 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1859 if (ret == -RTCP_BYE) {
1862 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1863 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1865 if (rt->nb_byes == rt->nb_rtsp_streams)
1873 /* more packets may follow, so we save the RTP context */
1874 rt->cur_transport_priv = rtsp_st->transport_priv;
1879 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1881 RTSPState *rt = s->priv_data;
1883 RTSPMessageHeader reply1, *reply = &reply1;
1886 if (rt->server_type == RTSP_SERVER_REAL) {
1889 for (i = 0; i < s->nb_streams; i++)
1890 rt->real_setup[i] = s->streams[i]->discard;
1892 if (!rt->need_subscription) {
1893 if (memcmp (rt->real_setup, rt->real_setup_cache,
1894 sizeof(enum AVDiscard) * s->nb_streams)) {
1895 snprintf(cmd, sizeof(cmd),
1896 "Unsubscribe: %s\r\n",
1897 rt->last_subscription);
1898 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1900 if (reply->status_code != RTSP_STATUS_OK)
1901 return AVERROR_INVALIDDATA;
1902 rt->need_subscription = 1;
1906 if (rt->need_subscription) {
1907 int r, rule_nr, first = 1;
1909 memcpy(rt->real_setup_cache, rt->real_setup,
1910 sizeof(enum AVDiscard) * s->nb_streams);
1911 rt->last_subscription[0] = 0;
1913 snprintf(cmd, sizeof(cmd),
1915 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1917 for (r = 0; r < s->nb_streams; r++) {
1918 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1919 if (s->streams[r]->discard != AVDISCARD_ALL) {
1921 av_strlcat(rt->last_subscription, ",",
1922 sizeof(rt->last_subscription));
1923 ff_rdt_subscribe_rule(
1924 rt->last_subscription,
1925 sizeof(rt->last_subscription), i, rule_nr);
1932 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1933 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1935 if (reply->status_code != RTSP_STATUS_OK)
1936 return AVERROR_INVALIDDATA;
1937 rt->need_subscription = 0;
1939 if (rt->state == RTSP_STATE_STREAMING)
1944 ret = rtsp_fetch_packet(s, pkt);
1948 /* send dummy request to keep TCP connection alive */
1949 if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1950 if (rt->server_type == RTSP_SERVER_WMS) {
1951 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1953 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1960 /* pause the stream */
1961 static int rtsp_read_pause(AVFormatContext *s)
1963 RTSPState *rt = s->priv_data;
1964 RTSPMessageHeader reply1, *reply = &reply1;
1966 if (rt->state != RTSP_STATE_STREAMING)
1968 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1969 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1970 if (reply->status_code != RTSP_STATUS_OK) {
1974 rt->state = RTSP_STATE_PAUSED;
1978 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1979 int64_t timestamp, int flags)
1981 RTSPState *rt = s->priv_data;
1983 rt->seek_timestamp = av_rescale_q(timestamp,
1984 s->streams[stream_index]->time_base,
1988 case RTSP_STATE_IDLE:
1990 case RTSP_STATE_STREAMING:
1991 if (rtsp_read_pause(s) != 0)
1993 rt->state = RTSP_STATE_SEEKING;
1994 if (rtsp_read_play(s) != 0)
1997 case RTSP_STATE_PAUSED:
1998 rt->state = RTSP_STATE_IDLE;
2004 static int rtsp_read_close(AVFormatContext *s)
2006 RTSPState *rt = s->priv_data;
2009 /* NOTE: it is valid to flush the buffer here */
2010 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
2011 url_fclose(&rt->rtsp_gb);
2014 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
2016 ff_rtsp_close_streams(s);
2017 ff_rtsp_close_connections(s);
2019 rt->real_setup = NULL;
2020 av_freep(&rt->real_setup_cache);
2024 AVInputFormat rtsp_demuxer = {
2026 NULL_IF_CONFIG_SMALL("RTSP input format"),
2033 .flags = AVFMT_NOFILE,
2034 .read_play = rtsp_read_play,
2035 .read_pause = rtsp_read_pause,
2039 static int sdp_probe(AVProbeData *p1)
2041 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2043 /* we look for a line beginning "c=IN IP" */
2044 while (p < p_end && *p != '\0') {
2045 if (p + sizeof("c=IN IP") - 1 < p_end &&
2046 av_strstart(p, "c=IN IP", NULL))
2047 return AVPROBE_SCORE_MAX / 2;
2049 while (p < p_end - 1 && *p != '\n') p++;
2058 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2060 RTSPState *rt = s->priv_data;
2061 RTSPStream *rtsp_st;
2066 if (!ff_network_init())
2067 return AVERROR(EIO);
2069 /* read the whole sdp file */
2070 /* XXX: better loading */
2071 content = av_malloc(SDP_MAX_SIZE);
2072 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2075 return AVERROR_INVALIDDATA;
2077 content[size] ='\0';
2079 sdp_parse(s, content);
2082 /* open each RTP stream */
2083 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2085 rtsp_st = rt->rtsp_streams[i];
2087 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2088 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2089 ff_url_join(url, sizeof(url), "rtp", NULL,
2090 namebuf, rtsp_st->sdp_port,
2091 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2093 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2094 err = AVERROR_INVALIDDATA;
2097 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2102 ff_rtsp_close_streams(s);
2107 static int sdp_read_close(AVFormatContext *s)
2109 ff_rtsp_close_streams(s);
2114 AVInputFormat sdp_demuxer = {
2116 NULL_IF_CONFIG_SMALL("SDP"),