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"
42 #include "rtpenc_chain.h"
45 //#define DEBUG_RTP_TCP
47 /* Timeout values for socket select, in ms,
48 * and read_packet(), in seconds */
49 #define SELECT_TIMEOUT_MS 100
50 #define READ_PACKET_TIMEOUT_S 10
51 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
52 #define SDP_MAX_SIZE 16384
53 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
55 static void get_word_until_chars(char *buf, int buf_size,
56 const char *sep, const char **pp)
62 p += strspn(p, SPACE_CHARS);
64 while (!strchr(sep, *p) && *p != '\0') {
65 if ((q - buf) < buf_size - 1)
74 static void get_word_sep(char *buf, int buf_size, const char *sep,
77 if (**pp == '/') (*pp)++;
78 get_word_until_chars(buf, buf_size, sep, pp);
81 static void get_word(char *buf, int buf_size, const char **pp)
83 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
86 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
88 * Used for seeking in the rtp stream.
90 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
94 p += strspn(p, SPACE_CHARS);
95 if (!av_stristart(p, "npt=", &p))
98 *start = AV_NOPTS_VALUE;
99 *end = AV_NOPTS_VALUE;
101 get_word_sep(buf, sizeof(buf), "-", &p);
102 *start = parse_date(buf, 1);
105 get_word_sep(buf, sizeof(buf), "-", &p);
106 *end = parse_date(buf, 1);
108 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
109 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
112 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
114 struct addrinfo hints, *ai = NULL;
115 memset(&hints, 0, sizeof(hints));
116 hints.ai_flags = AI_NUMERICHOST;
117 if (getaddrinfo(buf, NULL, &hints, &ai))
119 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
125 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
126 static int sdp_parse_rtpmap(AVFormatContext *s,
127 AVCodecContext *codec, RTSPStream *rtsp_st,
128 int payload_type, const char *p)
135 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
136 * see if we can handle this kind of payload.
137 * The space should normally not be there but some Real streams or
138 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
139 * have a trailing space. */
140 get_word_sep(buf, sizeof(buf), "/ ", &p);
141 if (payload_type >= RTP_PT_PRIVATE) {
142 RTPDynamicProtocolHandler *handler;
143 for (handler = RTPFirstDynamicPayloadHandler;
144 handler; handler = handler->next) {
145 if (!strcasecmp(buf, handler->enc_name) &&
146 codec->codec_type == handler->codec_type) {
147 codec->codec_id = handler->codec_id;
148 rtsp_st->dynamic_handler = handler;
150 rtsp_st->dynamic_protocol_context = handler->open();
154 /* If no dynamic handler was found, check with the list of standard
155 * allocated types, if such a stream for some reason happens to
156 * use a private payload type. This isn't handled in rtpdec.c, since
157 * the format name from the rtpmap line never is passed into rtpdec. */
158 if (!rtsp_st->dynamic_handler)
159 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
161 /* We are in a standard case
162 * (from http://www.iana.org/assignments/rtp-parameters). */
163 /* search into AVRtpPayloadTypes[] */
164 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
167 c = avcodec_find_decoder(codec->codec_id);
173 get_word_sep(buf, sizeof(buf), "/", &p);
175 switch (codec->codec_type) {
176 case AVMEDIA_TYPE_AUDIO:
177 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
178 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
179 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
181 codec->sample_rate = i;
182 get_word_sep(buf, sizeof(buf), "/", &p);
186 // TODO: there is a bug here; if it is a mono stream, and
187 // less than 22000Hz, faad upconverts to stereo and twice
188 // the frequency. No problem, but the sample rate is being
189 // set here by the sdp line. Patch on its way. (rdm)
191 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
193 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
196 case AVMEDIA_TYPE_VIDEO:
197 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
205 /* parse the attribute line from the fmtp a line of an sdp response. This
206 * is broken out as a function because it is used in rtp_h264.c, which is
208 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
209 char *value, int value_size)
211 *p += strspn(*p, SPACE_CHARS);
213 get_word_sep(attr, attr_size, "=", p);
216 get_word_sep(value, value_size, ";", p);
224 typedef struct SDPParseState {
226 struct sockaddr_storage default_ip;
228 int skip_media; ///< set if an unknown m= line occurs
231 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
232 int letter, const char *buf)
234 RTSPState *rt = s->priv_data;
235 char buf1[64], st_type[64];
237 enum AVMediaType codec_type;
241 struct sockaddr_storage sdp_ip;
244 dprintf(s, "sdp: %c='%s'\n", letter, buf);
247 if (s1->skip_media && letter != 'm')
251 get_word(buf1, sizeof(buf1), &p);
252 if (strcmp(buf1, "IN") != 0)
254 get_word(buf1, sizeof(buf1), &p);
255 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
257 get_word_sep(buf1, sizeof(buf1), "/", &p);
258 if (get_sockaddr(buf1, &sdp_ip))
263 get_word_sep(buf1, sizeof(buf1), "/", &p);
266 if (s->nb_streams == 0) {
267 s1->default_ip = sdp_ip;
268 s1->default_ttl = ttl;
270 st = s->streams[s->nb_streams - 1];
271 rtsp_st = st->priv_data;
272 rtsp_st->sdp_ip = sdp_ip;
273 rtsp_st->sdp_ttl = ttl;
277 av_metadata_set2(&s->metadata, "title", p, 0);
280 if (s->nb_streams == 0) {
281 av_metadata_set2(&s->metadata, "comment", p, 0);
288 get_word(st_type, sizeof(st_type), &p);
289 if (!strcmp(st_type, "audio")) {
290 codec_type = AVMEDIA_TYPE_AUDIO;
291 } else if (!strcmp(st_type, "video")) {
292 codec_type = AVMEDIA_TYPE_VIDEO;
293 } else if (!strcmp(st_type, "application")) {
294 codec_type = AVMEDIA_TYPE_DATA;
299 rtsp_st = av_mallocz(sizeof(RTSPStream));
302 rtsp_st->stream_index = -1;
303 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
305 rtsp_st->sdp_ip = s1->default_ip;
306 rtsp_st->sdp_ttl = s1->default_ttl;
308 get_word(buf1, sizeof(buf1), &p); /* port */
309 rtsp_st->sdp_port = atoi(buf1);
311 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
313 /* XXX: handle list of formats */
314 get_word(buf1, sizeof(buf1), &p); /* format list */
315 rtsp_st->sdp_payload_type = atoi(buf1);
317 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
318 /* no corresponding stream */
320 st = av_new_stream(s, 0);
323 st->priv_data = rtsp_st;
324 rtsp_st->stream_index = st->index;
325 st->codec->codec_type = codec_type;
326 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
327 /* if standard payload type, we can find the codec right now */
328 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
331 /* put a default control url */
332 av_strlcpy(rtsp_st->control_url, rt->control_uri,
333 sizeof(rtsp_st->control_url));
336 if (av_strstart(p, "control:", &p)) {
337 if (s->nb_streams == 0) {
338 if (!strncmp(p, "rtsp://", 7))
339 av_strlcpy(rt->control_uri, p,
340 sizeof(rt->control_uri));
343 /* get the control url */
344 st = s->streams[s->nb_streams - 1];
345 rtsp_st = st->priv_data;
347 /* XXX: may need to add full url resolution */
348 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
350 if (proto[0] == '\0') {
351 /* relative control URL */
352 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
353 av_strlcat(rtsp_st->control_url, "/",
354 sizeof(rtsp_st->control_url));
355 av_strlcat(rtsp_st->control_url, p,
356 sizeof(rtsp_st->control_url));
358 av_strlcpy(rtsp_st->control_url, p,
359 sizeof(rtsp_st->control_url));
361 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
362 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
363 get_word(buf1, sizeof(buf1), &p);
364 payload_type = atoi(buf1);
365 st = s->streams[s->nb_streams - 1];
366 rtsp_st = st->priv_data;
367 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
368 } else if (av_strstart(p, "fmtp:", &p) ||
369 av_strstart(p, "framesize:", &p)) {
370 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
371 // let dynamic protocol handlers have a stab at the line.
372 get_word(buf1, sizeof(buf1), &p);
373 payload_type = atoi(buf1);
374 for (i = 0; i < s->nb_streams; i++) {
376 rtsp_st = st->priv_data;
377 if (rtsp_st->sdp_payload_type == payload_type &&
378 rtsp_st->dynamic_handler &&
379 rtsp_st->dynamic_handler->parse_sdp_a_line)
380 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
381 rtsp_st->dynamic_protocol_context, buf);
383 } else if (av_strstart(p, "range:", &p)) {
386 // this is so that seeking on a streamed file can work.
387 rtsp_parse_range_npt(p, &start, &end);
388 s->start_time = start;
389 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
390 s->duration = (end == AV_NOPTS_VALUE) ?
391 AV_NOPTS_VALUE : end - start;
392 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
394 rt->transport = RTSP_TRANSPORT_RDT;
396 if (rt->server_type == RTSP_SERVER_WMS)
397 ff_wms_parse_sdp_a_line(s, p);
398 if (s->nb_streams > 0) {
399 if (rt->server_type == RTSP_SERVER_REAL)
400 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
402 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
403 if (rtsp_st->dynamic_handler &&
404 rtsp_st->dynamic_handler->parse_sdp_a_line)
405 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
407 rtsp_st->dynamic_protocol_context, buf);
414 static int sdp_parse(AVFormatContext *s, const char *content)
418 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
419 * contain long SDP lines containing complete ASF Headers (several
420 * kB) or arrays of MDPR (RM stream descriptor) headers plus
421 * "rulebooks" describing their properties. Therefore, the SDP line
424 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
425 * in rtpdec_xiph.c. */
427 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
429 memset(s1, 0, sizeof(SDPParseState));
432 p += strspn(p, SPACE_CHARS);
440 /* get the content */
442 while (*p != '\n' && *p != '\r' && *p != '\0') {
443 if ((q - buf) < sizeof(buf) - 1)
448 sdp_parse_line(s, s1, letter, buf);
450 while (*p != '\n' && *p != '\0')
457 #endif /* CONFIG_RTPDEC */
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 && CONFIG_RTPDEC)
485 ff_rdt_parse_close(rtsp_st->transport_priv);
486 else if (CONFIG_RTPDEC)
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);
501 av_free(rt->recvbuf);
504 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
506 RTSPState *rt = s->priv_data;
509 /* open the RTP context */
510 if (rtsp_st->stream_index >= 0)
511 st = s->streams[rtsp_st->stream_index];
513 s->ctx_flags |= AVFMTCTX_NOHEADER;
515 if (s->oformat && CONFIG_RTSP_MUXER) {
516 rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
518 RTSP_TCP_MAX_PACKET_SIZE);
519 /* Ownership of rtp_handle is passed to the rtp mux context */
520 rtsp_st->rtp_handle = NULL;
521 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
522 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
523 rtsp_st->dynamic_protocol_context,
524 rtsp_st->dynamic_handler);
525 else if (CONFIG_RTPDEC)
526 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
527 rtsp_st->sdp_payload_type,
528 (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
529 ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
531 if (!rtsp_st->transport_priv) {
532 return AVERROR(ENOMEM);
533 } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
534 if (rtsp_st->dynamic_handler) {
535 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
536 rtsp_st->dynamic_protocol_context,
537 rtsp_st->dynamic_handler);
544 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
545 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
551 p += strspn(p, SPACE_CHARS);
552 v = strtol(p, (char **)&p, 10);
556 v = strtol(p, (char **)&p, 10);
565 /* XXX: only one transport specification is parsed */
566 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
568 char transport_protocol[16];
570 char lower_transport[16];
572 RTSPTransportField *th;
575 reply->nb_transports = 0;
578 p += strspn(p, SPACE_CHARS);
582 th = &reply->transports[reply->nb_transports];
584 get_word_sep(transport_protocol, sizeof(transport_protocol),
586 if (!strcasecmp (transport_protocol, "rtp")) {
587 get_word_sep(profile, sizeof(profile), "/;,", &p);
588 lower_transport[0] = '\0';
589 /* rtp/avp/<protocol> */
591 get_word_sep(lower_transport, sizeof(lower_transport),
594 th->transport = RTSP_TRANSPORT_RTP;
595 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
596 !strcasecmp (transport_protocol, "x-real-rdt")) {
597 /* x-pn-tng/<protocol> */
598 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
600 th->transport = RTSP_TRANSPORT_RDT;
602 if (!strcasecmp(lower_transport, "TCP"))
603 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
605 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
609 /* get each parameter */
610 while (*p != '\0' && *p != ',') {
611 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
612 if (!strcmp(parameter, "port")) {
615 rtsp_parse_range(&th->port_min, &th->port_max, &p);
617 } else if (!strcmp(parameter, "client_port")) {
620 rtsp_parse_range(&th->client_port_min,
621 &th->client_port_max, &p);
623 } else if (!strcmp(parameter, "server_port")) {
626 rtsp_parse_range(&th->server_port_min,
627 &th->server_port_max, &p);
629 } else if (!strcmp(parameter, "interleaved")) {
632 rtsp_parse_range(&th->interleaved_min,
633 &th->interleaved_max, &p);
635 } else if (!strcmp(parameter, "multicast")) {
636 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
637 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
638 } else if (!strcmp(parameter, "ttl")) {
641 th->ttl = strtol(p, (char **)&p, 10);
643 } else if (!strcmp(parameter, "destination")) {
646 get_word_sep(buf, sizeof(buf), ";,", &p);
647 get_sockaddr(buf, &th->destination);
649 } else if (!strcmp(parameter, "source")) {
652 get_word_sep(buf, sizeof(buf), ";,", &p);
653 av_strlcpy(th->source, buf, sizeof(th->source));
657 while (*p != ';' && *p != '\0' && *p != ',')
665 reply->nb_transports++;
669 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
670 HTTPAuthState *auth_state)
674 /* NOTE: we do case independent match for broken servers */
676 if (av_stristart(p, "Session:", &p)) {
678 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
679 if (av_stristart(p, ";timeout=", &p) &&
680 (t = strtol(p, NULL, 10)) > 0) {
683 } else if (av_stristart(p, "Content-Length:", &p)) {
684 reply->content_length = strtol(p, NULL, 10);
685 } else if (av_stristart(p, "Transport:", &p)) {
686 rtsp_parse_transport(reply, p);
687 } else if (av_stristart(p, "CSeq:", &p)) {
688 reply->seq = strtol(p, NULL, 10);
689 } else if (av_stristart(p, "Range:", &p)) {
690 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
691 } else if (av_stristart(p, "RealChallenge1:", &p)) {
692 p += strspn(p, SPACE_CHARS);
693 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
694 } else if (av_stristart(p, "Server:", &p)) {
695 p += strspn(p, SPACE_CHARS);
696 av_strlcpy(reply->server, p, sizeof(reply->server));
697 } else if (av_stristart(p, "Notice:", &p) ||
698 av_stristart(p, "X-Notice:", &p)) {
699 reply->notice = strtol(p, NULL, 10);
700 } else if (av_stristart(p, "Location:", &p)) {
701 p += strspn(p, SPACE_CHARS);
702 av_strlcpy(reply->location, p , sizeof(reply->location));
703 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
704 p += strspn(p, SPACE_CHARS);
705 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
706 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
707 p += strspn(p, SPACE_CHARS);
708 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
712 /* skip a RTP/TCP interleaved packet */
713 void ff_rtsp_skip_packet(AVFormatContext *s)
715 RTSPState *rt = s->priv_data;
719 ret = url_read_complete(rt->rtsp_hd, buf, 3);
722 len = AV_RB16(buf + 1);
724 dprintf(s, "skipping RTP packet len=%d\n", len);
729 if (len1 > sizeof(buf))
731 ret = url_read_complete(rt->rtsp_hd, buf, len1);
738 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
739 unsigned char **content_ptr,
740 int return_on_interleaved_data)
742 RTSPState *rt = s->priv_data;
743 char buf[4096], buf1[1024], *q;
746 int ret, content_length, line_count = 0;
747 unsigned char *content = NULL;
749 memset(reply, 0, sizeof(*reply));
751 /* parse reply (XXX: use buffers) */
752 rt->last_reply[0] = '\0';
756 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
758 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
765 /* XXX: only parse it if first char on line ? */
766 if (return_on_interleaved_data) {
769 ff_rtsp_skip_packet(s);
770 } else if (ch != '\r') {
771 if ((q - buf) < sizeof(buf) - 1)
777 dprintf(s, "line='%s'\n", buf);
779 /* test if last line */
783 if (line_count == 0) {
785 get_word(buf1, sizeof(buf1), &p);
786 get_word(buf1, sizeof(buf1), &p);
787 reply->status_code = atoi(buf1);
788 av_strlcpy(reply->reason, p, sizeof(reply->reason));
790 ff_rtsp_parse_line(reply, p, &rt->auth_state);
791 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
792 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
797 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
798 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
800 content_length = reply->content_length;
801 if (content_length > 0) {
802 /* leave some room for a trailing '\0' (useful for simple parsing) */
803 content = av_malloc(content_length + 1);
804 (void)url_read_complete(rt->rtsp_hd, content, content_length);
805 content[content_length] = '\0';
808 *content_ptr = content;
812 if (rt->seq != reply->seq) {
813 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
814 rt->seq, reply->seq);
818 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
819 reply->notice == 2104 /* Start-of-Stream Reached */ ||
820 reply->notice == 2306 /* Continuous Feed Terminated */) {
821 rt->state = RTSP_STATE_IDLE;
822 } else if (reply->notice >= 4400 && reply->notice < 5500) {
823 return AVERROR(EIO); /* data or server error */
824 } else if (reply->notice == 2401 /* Ticket Expired */ ||
825 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
826 return AVERROR(EPERM);
831 int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
832 const char *method, const char *url,
834 const unsigned char *send_content,
835 int send_content_length)
837 RTSPState *rt = s->priv_data;
838 char buf[4096], *out_buf;
839 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
841 /* Add in RTSP headers */
844 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
846 av_strlcat(buf, headers, sizeof(buf));
847 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
848 if (rt->session_id[0] != '\0' && (!headers ||
849 !strstr(headers, "\nIf-Match:"))) {
850 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
853 char *str = ff_http_auth_create_response(&rt->auth_state,
854 rt->auth, url, method);
856 av_strlcat(buf, str, sizeof(buf));
859 if (send_content_length > 0 && send_content)
860 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
861 av_strlcat(buf, "\r\n", sizeof(buf));
863 /* base64 encode rtsp if tunneling */
864 if (rt->control_transport == RTSP_MODE_TUNNEL) {
865 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
869 dprintf(s, "Sending:\n%s--\n", buf);
871 url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
872 if (send_content_length > 0 && send_content) {
873 if (rt->control_transport == RTSP_MODE_TUNNEL) {
874 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
875 "with content data not supported\n");
876 return AVERROR_PATCHWELCOME;
878 url_write(rt->rtsp_hd_out, send_content, send_content_length);
880 rt->last_cmd_time = av_gettime();
885 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
886 const char *url, const char *headers)
888 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
891 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
892 const char *headers, RTSPMessageHeader *reply,
893 unsigned char **content_ptr)
895 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
896 content_ptr, NULL, 0);
899 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
900 const char *method, const char *url,
902 RTSPMessageHeader *reply,
903 unsigned char **content_ptr,
904 const unsigned char *send_content,
905 int send_content_length)
907 RTSPState *rt = s->priv_data;
908 HTTPAuthType cur_auth_type;
912 cur_auth_type = rt->auth_state.auth_type;
913 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
915 send_content_length)))
918 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
921 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
922 rt->auth_state.auth_type != HTTP_AUTH_NONE)
925 if (reply->status_code > 400){
926 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
930 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
937 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
939 static int make_setup_request(AVFormatContext *s, const char *host, int port,
940 int lower_transport, const char *real_challenge)
942 RTSPState *rt = s->priv_data;
943 int rtx, j, i, err, interleave = 0;
945 RTSPMessageHeader reply1, *reply = &reply1;
947 const char *trans_pref;
949 if (rt->transport == RTSP_TRANSPORT_RDT)
950 trans_pref = "x-pn-tng";
952 trans_pref = "RTP/AVP";
954 /* default timeout: 1 minute */
957 /* for each stream, make the setup request */
958 /* XXX: we assume the same server is used for the control of each
961 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
962 char transport[2048];
965 * WMS serves all UDP data over a single connection, the RTX, which
966 * isn't necessarily the first in the SDP but has to be the first
967 * to be set up, else the second/third SETUP will fail with a 461.
969 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
970 rt->server_type == RTSP_SERVER_WMS) {
973 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
974 int len = strlen(rt->rtsp_streams[rtx]->control_url);
976 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
980 if (rtx == rt->nb_rtsp_streams)
981 return -1; /* no RTX found */
982 rtsp_st = rt->rtsp_streams[rtx];
984 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
986 rtsp_st = rt->rtsp_streams[i];
989 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
992 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
993 port = reply->transports[0].client_port_min;
997 /* first try in specified port range */
998 if (RTSP_RTP_PORT_MIN != 0) {
999 while (j <= RTSP_RTP_PORT_MAX) {
1000 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1001 "?localport=%d", j);
1002 /* we will use two ports per rtp stream (rtp and rtcp) */
1004 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1010 /* then try on any port */
1011 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1012 err = AVERROR_INVALIDDATA;
1018 port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1020 snprintf(transport, sizeof(transport) - 1,
1021 "%s/UDP;", trans_pref);
1022 if (rt->server_type != RTSP_SERVER_REAL)
1023 av_strlcat(transport, "unicast;", sizeof(transport));
1024 av_strlcatf(transport, sizeof(transport),
1025 "client_port=%d", port);
1026 if (rt->transport == RTSP_TRANSPORT_RTP &&
1027 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1028 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1032 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1033 /** For WMS streams, the application streams are only used for
1034 * UDP. When trying to set it up for TCP streams, the server
1035 * will return an error. Therefore, we skip those streams. */
1036 if (rt->server_type == RTSP_SERVER_WMS &&
1037 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1040 snprintf(transport, sizeof(transport) - 1,
1041 "%s/TCP;", trans_pref);
1042 if (rt->server_type == RTSP_SERVER_WMS)
1043 av_strlcat(transport, "unicast;", sizeof(transport));
1044 av_strlcatf(transport, sizeof(transport),
1045 "interleaved=%d-%d",
1046 interleave, interleave + 1);
1050 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1051 snprintf(transport, sizeof(transport) - 1,
1052 "%s/UDP;multicast", trans_pref);
1055 av_strlcat(transport, ";mode=receive", sizeof(transport));
1056 } else if (rt->server_type == RTSP_SERVER_REAL ||
1057 rt->server_type == RTSP_SERVER_WMS)
1058 av_strlcat(transport, ";mode=play", sizeof(transport));
1059 snprintf(cmd, sizeof(cmd),
1060 "Transport: %s\r\n",
1062 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
1063 char real_res[41], real_csum[9];
1064 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1066 av_strlcatf(cmd, sizeof(cmd),
1068 "RealChallenge2: %s, sd=%s\r\n",
1069 rt->session_id, real_res, real_csum);
1071 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1072 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1075 } else if (reply->status_code != RTSP_STATUS_OK ||
1076 reply->nb_transports != 1) {
1077 err = AVERROR_INVALIDDATA;
1081 /* XXX: same protocol for all streams is required */
1083 if (reply->transports[0].lower_transport != rt->lower_transport ||
1084 reply->transports[0].transport != rt->transport) {
1085 err = AVERROR_INVALIDDATA;
1089 rt->lower_transport = reply->transports[0].lower_transport;
1090 rt->transport = reply->transports[0].transport;
1093 /* close RTP connection if not chosen */
1094 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1095 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1096 url_close(rtsp_st->rtp_handle);
1097 rtsp_st->rtp_handle = NULL;
1100 switch(reply->transports[0].lower_transport) {
1101 case RTSP_LOWER_TRANSPORT_TCP:
1102 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1103 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1106 case RTSP_LOWER_TRANSPORT_UDP: {
1109 /* Use source address if specified */
1110 if (reply->transports[0].source[0]) {
1111 ff_url_join(url, sizeof(url), "rtp", NULL,
1112 reply->transports[0].source,
1113 reply->transports[0].server_port_min, NULL);
1115 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1116 reply->transports[0].server_port_min, NULL);
1118 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1119 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1120 err = AVERROR_INVALIDDATA;
1123 /* Try to initialize the connection state in a
1124 * potential NAT router by sending dummy packets.
1125 * RTP/RTCP dummy packets are used for RDT, too.
1127 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1129 rtp_send_punch_packets(rtsp_st->rtp_handle);
1132 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1133 char url[1024], namebuf[50];
1134 struct sockaddr_storage addr;
1137 if (reply->transports[0].destination.ss_family) {
1138 addr = reply->transports[0].destination;
1139 port = reply->transports[0].port_min;
1140 ttl = reply->transports[0].ttl;
1142 addr = rtsp_st->sdp_ip;
1143 port = rtsp_st->sdp_port;
1144 ttl = rtsp_st->sdp_ttl;
1146 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1147 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1148 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1149 port, "?ttl=%d", ttl);
1150 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1151 err = AVERROR_INVALIDDATA;
1158 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1162 if (reply->timeout > 0)
1163 rt->timeout = reply->timeout;
1165 if (rt->server_type == RTSP_SERVER_REAL)
1166 rt->need_subscription = 1;
1171 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1172 if (rt->rtsp_streams[i]->rtp_handle) {
1173 url_close(rt->rtsp_streams[i]->rtp_handle);
1174 rt->rtsp_streams[i]->rtp_handle = NULL;
1180 static int rtsp_read_play(AVFormatContext *s)
1182 RTSPState *rt = s->priv_data;
1183 RTSPMessageHeader reply1, *reply = &reply1;
1187 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1190 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1191 if (rt->state == RTSP_STATE_PAUSED) {
1194 snprintf(cmd, sizeof(cmd),
1195 "Range: npt=%0.3f-\r\n",
1196 (double)rt->seek_timestamp / AV_TIME_BASE);
1198 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1199 if (reply->status_code != RTSP_STATUS_OK) {
1202 if (rt->transport == RTSP_TRANSPORT_RTP) {
1203 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1204 RTSPStream *rtsp_st = rt->rtsp_streams[i];
1205 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1206 AVStream *st = NULL;
1209 if (rtsp_st->stream_index >= 0)
1210 st = s->streams[rtsp_st->stream_index];
1211 ff_rtp_reset_packet_queue(rtpctx);
1212 if (reply->range_start != AV_NOPTS_VALUE) {
1213 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
1214 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1216 rtpctx->range_start_offset =
1217 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
1223 rt->state = RTSP_STATE_STREAMING;
1227 #if CONFIG_RTSP_DEMUXER
1228 static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1230 RTSPState *rt = s->priv_data;
1232 unsigned char *content = NULL;
1235 /* describe the stream */
1236 snprintf(cmd, sizeof(cmd),
1237 "Accept: application/sdp\r\n");
1238 if (rt->server_type == RTSP_SERVER_REAL) {
1240 * The Require: attribute is needed for proper streaming from
1241 * Realmedia servers.
1244 "Require: com.real.retain-entity-for-setup\r\n",
1247 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1249 return AVERROR_INVALIDDATA;
1250 if (reply->status_code != RTSP_STATUS_OK) {
1252 return AVERROR_INVALIDDATA;
1255 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
1256 /* now we got the SDP description, we parse it */
1257 ret = sdp_parse(s, (const char *)content);
1260 return AVERROR_INVALIDDATA;
1264 #endif /* CONFIG_RTSP_DEMUXER */
1266 #if CONFIG_RTSP_MUXER
1267 static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1269 RTSPState *rt = s->priv_data;
1270 RTSPMessageHeader reply1, *reply = &reply1;
1273 AVFormatContext sdp_ctx, *ctx_array[1];
1275 s->start_time_realtime = av_gettime();
1277 /* Announce the stream */
1278 sdp = av_mallocz(SDP_MAX_SIZE);
1280 return AVERROR(ENOMEM);
1281 /* We create the SDP based on the RTSP AVFormatContext where we
1282 * aren't allowed to change the filename field. (We create the SDP
1283 * based on the RTSP context since the contexts for the RTP streams
1284 * don't exist yet.) In order to specify a custom URL with the actual
1285 * peer IP instead of the originally specified hostname, we create
1286 * a temporary copy of the AVFormatContext, where the custom URL is set.
1288 * FIXME: Create the SDP without copying the AVFormatContext.
1289 * This either requires setting up the RTP stream AVFormatContexts
1290 * already here (complicating things immensely) or getting a more
1291 * flexible SDP creation interface.
1294 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1295 "rtsp", NULL, addr, -1, NULL);
1296 ctx_array[0] = &sdp_ctx;
1297 if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
1299 return AVERROR_INVALIDDATA;
1301 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
1302 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1303 "Content-Type: application/sdp\r\n",
1304 reply, NULL, sdp, strlen(sdp));
1306 if (reply->status_code != RTSP_STATUS_OK)
1307 return AVERROR_INVALIDDATA;
1309 /* Set up the RTSPStreams for each AVStream */
1310 for (i = 0; i < s->nb_streams; i++) {
1311 RTSPStream *rtsp_st;
1312 AVStream *st = s->streams[i];
1314 rtsp_st = av_mallocz(sizeof(RTSPStream));
1316 return AVERROR(ENOMEM);
1317 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1319 st->priv_data = rtsp_st;
1320 rtsp_st->stream_index = i;
1322 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1323 /* Note, this must match the relative uri set in the sdp content */
1324 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1330 #endif /* CONFIG_RTSP_MUXER */
1332 void ff_rtsp_close_connections(AVFormatContext *s)
1334 RTSPState *rt = s->priv_data;
1335 if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1336 url_close(rt->rtsp_hd);
1337 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1340 int ff_rtsp_connect(AVFormatContext *s)
1342 RTSPState *rt = s->priv_data;
1343 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1344 char *option_list, *option, *filename;
1345 int port, err, tcp_fd;
1346 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1347 int lower_transport_mask = 0;
1348 char real_challenge[64];
1349 struct sockaddr_storage peer;
1350 socklen_t peer_len = sizeof(peer);
1352 if (!ff_network_init())
1353 return AVERROR(EIO);
1355 rt->control_transport = RTSP_MODE_PLAIN;
1356 /* extract hostname and port */
1357 av_url_split(NULL, 0, auth, sizeof(auth),
1358 host, sizeof(host), &port, path, sizeof(path), s->filename);
1360 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1363 port = RTSP_DEFAULT_PORT;
1365 /* search for options */
1366 option_list = strrchr(path, '?');
1368 /* Strip out the RTSP specific options, write out the rest of
1369 * the options back into the same string. */
1370 filename = option_list;
1371 while (option_list) {
1372 /* move the option pointer */
1373 option = ++option_list;
1374 option_list = strchr(option_list, '&');
1378 /* handle the options */
1379 if (!strcmp(option, "udp")) {
1380 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1381 } else if (!strcmp(option, "multicast")) {
1382 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1383 } else if (!strcmp(option, "tcp")) {
1384 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1385 } else if(!strcmp(option, "http")) {
1386 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1387 rt->control_transport = RTSP_MODE_TUNNEL;
1389 /* Write options back into the buffer, using memmove instead
1390 * of strcpy since the strings may overlap. */
1391 int len = strlen(option);
1392 memmove(++filename, option, len);
1394 if (option_list) *filename = '&';
1400 if (!lower_transport_mask)
1401 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1404 /* Only UDP or TCP - UDP multicast isn't supported. */
1405 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1406 (1 << RTSP_LOWER_TRANSPORT_TCP);
1407 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1408 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1409 "only UDP and TCP are supported for output.\n");
1410 err = AVERROR(EINVAL);
1415 /* Construct the URI used in request; this is similar to s->filename,
1416 * but with authentication credentials removed and RTSP specific options
1418 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1419 host, port, "%s", path);
1421 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1422 /* set up initial handshake for tunneling */
1423 char httpname[1024];
1424 char sessioncookie[17];
1427 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1428 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1429 av_get_random_seed(), av_get_random_seed());
1432 if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
1437 /* generate GET headers */
1438 snprintf(headers, sizeof(headers),
1439 "x-sessioncookie: %s\r\n"
1440 "Accept: application/x-rtsp-tunnelled\r\n"
1441 "Pragma: no-cache\r\n"
1442 "Cache-Control: no-cache\r\n",
1444 ff_http_set_headers(rt->rtsp_hd, headers);
1446 /* complete the connection */
1447 if (url_connect(rt->rtsp_hd)) {
1453 if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1458 /* generate POST headers */
1459 snprintf(headers, sizeof(headers),
1460 "x-sessioncookie: %s\r\n"
1461 "Content-Type: application/x-rtsp-tunnelled\r\n"
1462 "Pragma: no-cache\r\n"
1463 "Cache-Control: no-cache\r\n"
1464 "Content-Length: 32767\r\n"
1465 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1467 ff_http_set_headers(rt->rtsp_hd_out, headers);
1468 ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1470 /* Initialize the authentication state for the POST session. The HTTP
1471 * protocol implementation doesn't properly handle multi-pass
1472 * authentication for POST requests, since it would require one of
1474 * - implementing Expect: 100-continue, which many HTTP servers
1475 * don't support anyway, even less the RTSP servers that do HTTP
1477 * - sending the whole POST data until getting a 401 reply specifying
1478 * what authentication method to use, then resending all that data
1479 * - waiting for potential 401 replies directly after sending the
1480 * POST header (waiting for some unspecified time)
1481 * Therefore, we copy the full auth state, which works for both basic
1482 * and digest. (For digest, we would have to synchronize the nonce
1483 * count variable between the two sessions, if we'd do more requests
1484 * with the original session, though.)
1486 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1488 /* complete the connection */
1489 if (url_connect(rt->rtsp_hd_out)) {
1494 /* open the tcp connection */
1495 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1496 if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
1500 rt->rtsp_hd_out = rt->rtsp_hd;
1504 tcp_fd = url_get_file_handle(rt->rtsp_hd);
1505 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1506 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1507 NULL, 0, NI_NUMERICHOST);
1510 /* request options supported by the server; this also detects server
1512 for (rt->server_type = RTSP_SERVER_RTP;;) {
1514 if (rt->server_type == RTSP_SERVER_REAL)
1517 * The following entries are required for proper
1518 * streaming from a Realmedia server. They are
1519 * interdependent in some way although we currently
1520 * don't quite understand how. Values were copied
1521 * from mplayer SVN r23589.
1522 * @param CompanyID is a 16-byte ID in base64
1523 * @param ClientChallenge is a 16-byte ID in hex
1525 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1526 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1527 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1528 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1530 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1531 if (reply->status_code != RTSP_STATUS_OK) {
1532 err = AVERROR_INVALIDDATA;
1536 /* detect server type if not standard-compliant RTP */
1537 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1538 rt->server_type = RTSP_SERVER_REAL;
1540 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1541 rt->server_type = RTSP_SERVER_WMS;
1542 } else if (rt->server_type == RTSP_SERVER_REAL)
1543 strcpy(real_challenge, reply->real_challenge);
1547 if (s->iformat && CONFIG_RTSP_DEMUXER)
1548 err = rtsp_setup_input_streams(s, reply);
1549 else if (CONFIG_RTSP_MUXER)
1550 err = rtsp_setup_output_streams(s, host);
1555 int lower_transport = ff_log2_tab[lower_transport_mask &
1556 ~(lower_transport_mask - 1)];
1558 err = make_setup_request(s, host, port, lower_transport,
1559 rt->server_type == RTSP_SERVER_REAL ?
1560 real_challenge : NULL);
1563 lower_transport_mask &= ~(1 << lower_transport);
1564 if (lower_transport_mask == 0 && err == 1) {
1565 err = FF_NETERROR(EPROTONOSUPPORT);
1570 rt->state = RTSP_STATE_IDLE;
1571 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1574 ff_rtsp_close_streams(s);
1575 ff_rtsp_close_connections(s);
1576 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1577 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1578 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1586 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1589 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1590 uint8_t *buf, int buf_size, int64_t wait_end)
1592 RTSPState *rt = s->priv_data;
1593 RTSPStream *rtsp_st;
1595 int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1599 if (url_interrupt_cb())
1600 return AVERROR(EINTR);
1601 if (wait_end && wait_end - av_gettime() < 0)
1602 return AVERROR(EAGAIN);
1605 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1606 FD_SET(tcp_fd, &rfds);
1611 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1612 rtsp_st = rt->rtsp_streams[i];
1613 if (rtsp_st->rtp_handle) {
1614 fd = url_get_file_handle(rtsp_st->rtp_handle);
1615 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1616 if (FFMAX(fd, fd_rtcp) > fd_max)
1617 fd_max = FFMAX(fd, fd_rtcp);
1619 FD_SET(fd_rtcp, &rfds);
1623 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1624 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1627 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1628 rtsp_st = rt->rtsp_streams[i];
1629 if (rtsp_st->rtp_handle) {
1630 fd = url_get_file_handle(rtsp_st->rtp_handle);
1631 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1632 if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
1633 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1635 *prtsp_st = rtsp_st;
1641 #if CONFIG_RTSP_DEMUXER
1642 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1643 RTSPMessageHeader reply;
1645 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1648 /* XXX: parse message */
1649 if (rt->state != RTSP_STATE_STREAMING)
1653 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1654 return FF_NETERROR(ETIMEDOUT);
1655 } else if (n < 0 && errno != EINTR)
1656 return AVERROR(errno);
1660 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1661 uint8_t *buf, int buf_size);
1663 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1665 RTSPState *rt = s->priv_data;
1667 RTSPStream *rtsp_st, *first_queue_st = NULL;
1668 int64_t wait_end = 0;
1670 if (rt->nb_byes == rt->nb_rtsp_streams)
1673 /* get next frames from the same RTP packet */
1674 if (rt->cur_transport_priv) {
1675 if (rt->transport == RTSP_TRANSPORT_RDT) {
1676 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1678 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1680 rt->cur_transport_priv = NULL;
1682 } else if (ret == 1) {
1685 rt->cur_transport_priv = NULL;
1688 if (rt->transport == RTSP_TRANSPORT_RTP) {
1690 int64_t first_queue_time = 0;
1691 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1692 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1693 int64_t queue_time = ff_rtp_queued_packet_time(rtpctx);
1694 if (queue_time && (queue_time - first_queue_time < 0 ||
1695 !first_queue_time)) {
1696 first_queue_time = queue_time;
1697 first_queue_st = rt->rtsp_streams[i];
1700 if (first_queue_time)
1701 wait_end = first_queue_time + s->max_delay;
1704 /* read next RTP packet */
1707 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1709 return AVERROR(ENOMEM);
1712 switch(rt->lower_transport) {
1714 #if CONFIG_RTSP_DEMUXER
1715 case RTSP_LOWER_TRANSPORT_TCP:
1716 len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1719 case RTSP_LOWER_TRANSPORT_UDP:
1720 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1721 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
1722 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1723 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1726 if (len == AVERROR(EAGAIN) && first_queue_st &&
1727 rt->transport == RTSP_TRANSPORT_RTP) {
1728 rtsp_st = first_queue_st;
1729 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
1736 if (rt->transport == RTSP_TRANSPORT_RDT) {
1737 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1739 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1741 /* Either bad packet, or a RTCP packet. Check if the
1742 * first_rtcp_ntp_time field was initialized. */
1743 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1744 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1745 /* first_rtcp_ntp_time has been initialized for this stream,
1746 * copy the same value to all other uninitialized streams,
1747 * in order to map their timestamp origin to the same ntp time
1750 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1751 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1753 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1754 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1757 if (ret == -RTCP_BYE) {
1760 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1761 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1763 if (rt->nb_byes == rt->nb_rtsp_streams)
1772 /* more packets may follow, so we save the RTP context */
1773 rt->cur_transport_priv = rtsp_st->transport_priv;
1777 #endif /* CONFIG_RTPDEC */
1779 #if CONFIG_RTSP_DEMUXER
1780 static int rtsp_probe(AVProbeData *p)
1782 if (av_strstart(p->filename, "rtsp:", NULL))
1783 return AVPROBE_SCORE_MAX;
1787 static int rtsp_read_header(AVFormatContext *s,
1788 AVFormatParameters *ap)
1790 RTSPState *rt = s->priv_data;
1793 ret = ff_rtsp_connect(s);
1797 rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
1798 if (!rt->real_setup_cache)
1799 return AVERROR(ENOMEM);
1800 rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
1802 if (ap->initial_pause) {
1803 /* do not start immediately */
1805 if (rtsp_read_play(s) < 0) {
1806 ff_rtsp_close_streams(s);
1807 ff_rtsp_close_connections(s);
1808 return AVERROR_INVALIDDATA;
1815 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1816 uint8_t *buf, int buf_size)
1818 RTSPState *rt = s->priv_data;
1819 int id, len, i, ret;
1820 RTSPStream *rtsp_st;
1822 #ifdef DEBUG_RTP_TCP
1823 dprintf(s, "tcp_read_packet:\n");
1827 RTSPMessageHeader reply;
1829 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1832 if (ret == 1) /* received '$' */
1834 /* XXX: parse message */
1835 if (rt->state != RTSP_STATE_STREAMING)
1838 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1842 len = AV_RB16(buf + 1);
1843 #ifdef DEBUG_RTP_TCP
1844 dprintf(s, "id=%d len=%d\n", id, len);
1846 if (len > buf_size || len < 12)
1849 ret = url_read_complete(rt->rtsp_hd, buf, len);
1852 if (rt->transport == RTSP_TRANSPORT_RDT &&
1853 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1856 /* find the matching stream */
1857 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1858 rtsp_st = rt->rtsp_streams[i];
1859 if (id >= rtsp_st->interleaved_min &&
1860 id <= rtsp_st->interleaved_max)
1865 *prtsp_st = rtsp_st;
1868 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1870 RTSPState *rt = s->priv_data;
1872 RTSPMessageHeader reply1, *reply = &reply1;
1875 if (rt->server_type == RTSP_SERVER_REAL) {
1878 for (i = 0; i < s->nb_streams; i++)
1879 rt->real_setup[i] = s->streams[i]->discard;
1881 if (!rt->need_subscription) {
1882 if (memcmp (rt->real_setup, rt->real_setup_cache,
1883 sizeof(enum AVDiscard) * s->nb_streams)) {
1884 snprintf(cmd, sizeof(cmd),
1885 "Unsubscribe: %s\r\n",
1886 rt->last_subscription);
1887 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1889 if (reply->status_code != RTSP_STATUS_OK)
1890 return AVERROR_INVALIDDATA;
1891 rt->need_subscription = 1;
1895 if (rt->need_subscription) {
1896 int r, rule_nr, first = 1;
1898 memcpy(rt->real_setup_cache, rt->real_setup,
1899 sizeof(enum AVDiscard) * s->nb_streams);
1900 rt->last_subscription[0] = 0;
1902 snprintf(cmd, sizeof(cmd),
1904 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1906 for (r = 0; r < s->nb_streams; r++) {
1907 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1908 if (s->streams[r]->discard != AVDISCARD_ALL) {
1910 av_strlcat(rt->last_subscription, ",",
1911 sizeof(rt->last_subscription));
1912 ff_rdt_subscribe_rule(
1913 rt->last_subscription,
1914 sizeof(rt->last_subscription), i, rule_nr);
1921 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1922 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1924 if (reply->status_code != RTSP_STATUS_OK)
1925 return AVERROR_INVALIDDATA;
1926 rt->need_subscription = 0;
1928 if (rt->state == RTSP_STATE_STREAMING)
1933 ret = rtsp_fetch_packet(s, pkt);
1937 /* send dummy request to keep TCP connection alive */
1938 if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1939 if (rt->server_type == RTSP_SERVER_WMS) {
1940 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1942 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1949 /* pause the stream */
1950 static int rtsp_read_pause(AVFormatContext *s)
1952 RTSPState *rt = s->priv_data;
1953 RTSPMessageHeader reply1, *reply = &reply1;
1955 if (rt->state != RTSP_STATE_STREAMING)
1957 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1958 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1959 if (reply->status_code != RTSP_STATUS_OK) {
1963 rt->state = RTSP_STATE_PAUSED;
1967 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1968 int64_t timestamp, int flags)
1970 RTSPState *rt = s->priv_data;
1972 rt->seek_timestamp = av_rescale_q(timestamp,
1973 s->streams[stream_index]->time_base,
1977 case RTSP_STATE_IDLE:
1979 case RTSP_STATE_STREAMING:
1980 if (rtsp_read_pause(s) != 0)
1982 rt->state = RTSP_STATE_SEEKING;
1983 if (rtsp_read_play(s) != 0)
1986 case RTSP_STATE_PAUSED:
1987 rt->state = RTSP_STATE_IDLE;
1993 static int rtsp_read_close(AVFormatContext *s)
1995 RTSPState *rt = s->priv_data;
1998 /* NOTE: it is valid to flush the buffer here */
1999 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
2000 url_fclose(&rt->rtsp_gb);
2003 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
2005 ff_rtsp_close_streams(s);
2006 ff_rtsp_close_connections(s);
2008 rt->real_setup = NULL;
2009 av_freep(&rt->real_setup_cache);
2013 AVInputFormat rtsp_demuxer = {
2015 NULL_IF_CONFIG_SMALL("RTSP input format"),
2022 .flags = AVFMT_NOFILE,
2023 .read_play = rtsp_read_play,
2024 .read_pause = rtsp_read_pause,
2026 #endif /* CONFIG_RTSP_DEMUXER */
2028 #if CONFIG_SDP_DEMUXER
2029 static int sdp_probe(AVProbeData *p1)
2031 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2033 /* we look for a line beginning "c=IN IP" */
2034 while (p < p_end && *p != '\0') {
2035 if (p + sizeof("c=IN IP") - 1 < p_end &&
2036 av_strstart(p, "c=IN IP", NULL))
2037 return AVPROBE_SCORE_MAX / 2;
2039 while (p < p_end - 1 && *p != '\n') p++;
2048 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2050 RTSPState *rt = s->priv_data;
2051 RTSPStream *rtsp_st;
2056 if (!ff_network_init())
2057 return AVERROR(EIO);
2059 /* read the whole sdp file */
2060 /* XXX: better loading */
2061 content = av_malloc(SDP_MAX_SIZE);
2062 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2065 return AVERROR_INVALIDDATA;
2067 content[size] ='\0';
2069 sdp_parse(s, content);
2072 /* open each RTP stream */
2073 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2075 rtsp_st = rt->rtsp_streams[i];
2077 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2078 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2079 ff_url_join(url, sizeof(url), "rtp", NULL,
2080 namebuf, rtsp_st->sdp_port,
2081 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2083 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2084 err = AVERROR_INVALIDDATA;
2087 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2092 ff_rtsp_close_streams(s);
2097 static int sdp_read_close(AVFormatContext *s)
2099 ff_rtsp_close_streams(s);
2104 AVInputFormat sdp_demuxer = {
2106 NULL_IF_CONFIG_SMALL("SDP"),
2113 #endif /* CONFIG_SDP_DEMUXER */
2115 #if CONFIG_RTP_DEMUXER
2116 static int rtp_probe(AVProbeData *p)
2118 if (av_strstart(p->filename, "rtp:", NULL))
2119 return AVPROBE_SCORE_MAX;
2123 static int rtp_read_header(AVFormatContext *s,
2124 AVFormatParameters *ap)
2126 uint8_t recvbuf[1500];
2127 char host[500], sdp[500];
2129 URLContext* in = NULL;
2131 AVCodecContext codec;
2132 struct sockaddr_storage addr;
2134 socklen_t addrlen = sizeof(addr);
2136 if (!ff_network_init())
2137 return AVERROR(EIO);
2139 ret = url_open(&in, s->filename, URL_RDONLY);
2144 ret = url_read(in, recvbuf, sizeof(recvbuf));
2145 if (ret == AVERROR(EAGAIN))
2150 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2154 if ((recvbuf[0] & 0xc0) != 0x80) {
2155 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2160 payload_type = recvbuf[1] & 0x7f;
2163 getsockname(url_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2167 memset(&codec, 0, sizeof(codec));
2168 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2169 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2170 "without an SDP file describing it\n",
2174 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2175 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2176 "properly you need an SDP file "
2180 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2181 NULL, 0, s->filename);
2183 snprintf(sdp, sizeof(sdp),
2184 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2185 addr.ss_family == AF_INET ? 4 : 6, host,
2186 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2187 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2188 port, payload_type);
2189 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2191 init_put_byte(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2194 /* sdp_read_header initializes this again */
2197 ret = sdp_read_header(s, ap);
2208 AVInputFormat rtp_demuxer = {
2210 NULL_IF_CONFIG_SMALL("RTP input format"),
2216 .flags = AVFMT_NOFILE,
2218 #endif /* CONFIG_RTP_DEMUXER */