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 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
48 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
51 /* Timeout values for socket select, in ms,
52 * and read_packet(), in seconds */
53 #define SELECT_TIMEOUT_MS 100
54 #define READ_PACKET_TIMEOUT_S 10
55 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
56 #define SDP_MAX_SIZE 16384
57 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
59 static void get_word_until_chars(char *buf, int buf_size,
60 const char *sep, const char **pp)
66 p += strspn(p, SPACE_CHARS);
68 while (!strchr(sep, *p) && *p != '\0') {
69 if ((q - buf) < buf_size - 1)
78 static void get_word_sep(char *buf, int buf_size, const char *sep,
81 if (**pp == '/') (*pp)++;
82 get_word_until_chars(buf, buf_size, sep, pp);
85 static void get_word(char *buf, int buf_size, const char **pp)
87 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
90 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
92 * Used for seeking in the rtp stream.
94 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
98 p += strspn(p, SPACE_CHARS);
99 if (!av_stristart(p, "npt=", &p))
102 *start = AV_NOPTS_VALUE;
103 *end = AV_NOPTS_VALUE;
105 get_word_sep(buf, sizeof(buf), "-", &p);
106 *start = parse_date(buf, 1);
109 get_word_sep(buf, sizeof(buf), "-", &p);
110 *end = parse_date(buf, 1);
112 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
113 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
116 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
118 struct addrinfo hints, *ai = NULL;
119 memset(&hints, 0, sizeof(hints));
120 hints.ai_flags = AI_NUMERICHOST;
121 if (getaddrinfo(buf, NULL, &hints, &ai))
123 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
129 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
130 static int sdp_parse_rtpmap(AVFormatContext *s,
131 AVCodecContext *codec, RTSPStream *rtsp_st,
132 int payload_type, const char *p)
139 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
140 * see if we can handle this kind of payload.
141 * The space should normally not be there but some Real streams or
142 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
143 * have a trailing space. */
144 get_word_sep(buf, sizeof(buf), "/ ", &p);
145 if (payload_type >= RTP_PT_PRIVATE) {
146 RTPDynamicProtocolHandler *handler;
147 for (handler = RTPFirstDynamicPayloadHandler;
148 handler; handler = handler->next) {
149 if (!strcasecmp(buf, handler->enc_name) &&
150 codec->codec_type == handler->codec_type) {
151 codec->codec_id = handler->codec_id;
152 rtsp_st->dynamic_handler = handler;
154 rtsp_st->dynamic_protocol_context = handler->open();
158 /* If no dynamic handler was found, check with the list of standard
159 * allocated types, if such a stream for some reason happens to
160 * use a private payload type. This isn't handled in rtpdec.c, since
161 * the format name from the rtpmap line never is passed into rtpdec. */
162 if (!rtsp_st->dynamic_handler)
163 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
165 /* We are in a standard case
166 * (from http://www.iana.org/assignments/rtp-parameters). */
167 /* search into AVRtpPayloadTypes[] */
168 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
171 c = avcodec_find_decoder(codec->codec_id);
177 get_word_sep(buf, sizeof(buf), "/", &p);
179 switch (codec->codec_type) {
180 case AVMEDIA_TYPE_AUDIO:
181 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
182 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
183 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
185 codec->sample_rate = i;
186 get_word_sep(buf, sizeof(buf), "/", &p);
190 // TODO: there is a bug here; if it is a mono stream, and
191 // less than 22000Hz, faad upconverts to stereo and twice
192 // the frequency. No problem, but the sample rate is being
193 // set here by the sdp line. Patch on its way. (rdm)
195 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
197 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
200 case AVMEDIA_TYPE_VIDEO:
201 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
209 /* parse the attribute line from the fmtp a line of an sdp response. This
210 * is broken out as a function because it is used in rtp_h264.c, which is
212 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
213 char *value, int value_size)
215 *p += strspn(*p, SPACE_CHARS);
217 get_word_sep(attr, attr_size, "=", p);
220 get_word_sep(value, value_size, ";", p);
228 typedef struct SDPParseState {
230 struct sockaddr_storage default_ip;
232 int skip_media; ///< set if an unknown m= line occurs
235 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
236 int letter, const char *buf)
238 RTSPState *rt = s->priv_data;
239 char buf1[64], st_type[64];
241 enum AVMediaType codec_type;
245 struct sockaddr_storage sdp_ip;
248 dprintf(s, "sdp: %c='%s'\n", letter, buf);
251 if (s1->skip_media && letter != 'm')
255 get_word(buf1, sizeof(buf1), &p);
256 if (strcmp(buf1, "IN") != 0)
258 get_word(buf1, sizeof(buf1), &p);
259 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
261 get_word_sep(buf1, sizeof(buf1), "/", &p);
262 if (get_sockaddr(buf1, &sdp_ip))
267 get_word_sep(buf1, sizeof(buf1), "/", &p);
270 if (s->nb_streams == 0) {
271 s1->default_ip = sdp_ip;
272 s1->default_ttl = ttl;
274 st = s->streams[s->nb_streams - 1];
275 rtsp_st = st->priv_data;
276 rtsp_st->sdp_ip = sdp_ip;
277 rtsp_st->sdp_ttl = ttl;
281 av_metadata_set2(&s->metadata, "title", p, 0);
284 if (s->nb_streams == 0) {
285 av_metadata_set2(&s->metadata, "comment", p, 0);
292 get_word(st_type, sizeof(st_type), &p);
293 if (!strcmp(st_type, "audio")) {
294 codec_type = AVMEDIA_TYPE_AUDIO;
295 } else if (!strcmp(st_type, "video")) {
296 codec_type = AVMEDIA_TYPE_VIDEO;
297 } else if (!strcmp(st_type, "application")) {
298 codec_type = AVMEDIA_TYPE_DATA;
303 rtsp_st = av_mallocz(sizeof(RTSPStream));
306 rtsp_st->stream_index = -1;
307 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
309 rtsp_st->sdp_ip = s1->default_ip;
310 rtsp_st->sdp_ttl = s1->default_ttl;
312 get_word(buf1, sizeof(buf1), &p); /* port */
313 rtsp_st->sdp_port = atoi(buf1);
315 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
317 /* XXX: handle list of formats */
318 get_word(buf1, sizeof(buf1), &p); /* format list */
319 rtsp_st->sdp_payload_type = atoi(buf1);
321 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
322 /* no corresponding stream */
324 st = av_new_stream(s, 0);
327 st->priv_data = rtsp_st;
328 rtsp_st->stream_index = st->index;
329 st->codec->codec_type = codec_type;
330 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
331 /* if standard payload type, we can find the codec right now */
332 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
335 /* put a default control url */
336 av_strlcpy(rtsp_st->control_url, rt->control_uri,
337 sizeof(rtsp_st->control_url));
340 if (av_strstart(p, "control:", &p)) {
341 if (s->nb_streams == 0) {
342 if (!strncmp(p, "rtsp://", 7))
343 av_strlcpy(rt->control_uri, p,
344 sizeof(rt->control_uri));
347 /* get the control url */
348 st = s->streams[s->nb_streams - 1];
349 rtsp_st = st->priv_data;
351 /* XXX: may need to add full url resolution */
352 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
354 if (proto[0] == '\0') {
355 /* relative control URL */
356 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
357 av_strlcat(rtsp_st->control_url, "/",
358 sizeof(rtsp_st->control_url));
359 av_strlcat(rtsp_st->control_url, p,
360 sizeof(rtsp_st->control_url));
362 av_strlcpy(rtsp_st->control_url, p,
363 sizeof(rtsp_st->control_url));
365 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
366 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
367 get_word(buf1, sizeof(buf1), &p);
368 payload_type = atoi(buf1);
369 st = s->streams[s->nb_streams - 1];
370 rtsp_st = st->priv_data;
371 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
372 } else if (av_strstart(p, "fmtp:", &p) ||
373 av_strstart(p, "framesize:", &p)) {
374 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
375 // let dynamic protocol handlers have a stab at the line.
376 get_word(buf1, sizeof(buf1), &p);
377 payload_type = atoi(buf1);
378 for (i = 0; i < s->nb_streams; i++) {
380 rtsp_st = st->priv_data;
381 if (rtsp_st->sdp_payload_type == payload_type &&
382 rtsp_st->dynamic_handler &&
383 rtsp_st->dynamic_handler->parse_sdp_a_line)
384 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
385 rtsp_st->dynamic_protocol_context, buf);
387 } else if (av_strstart(p, "range:", &p)) {
390 // this is so that seeking on a streamed file can work.
391 rtsp_parse_range_npt(p, &start, &end);
392 s->start_time = start;
393 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
394 s->duration = (end == AV_NOPTS_VALUE) ?
395 AV_NOPTS_VALUE : end - start;
396 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
398 rt->transport = RTSP_TRANSPORT_RDT;
400 if (rt->server_type == RTSP_SERVER_WMS)
401 ff_wms_parse_sdp_a_line(s, p);
402 if (s->nb_streams > 0) {
403 if (rt->server_type == RTSP_SERVER_REAL)
404 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
406 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
407 if (rtsp_st->dynamic_handler &&
408 rtsp_st->dynamic_handler->parse_sdp_a_line)
409 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
411 rtsp_st->dynamic_protocol_context, buf);
418 static int sdp_parse(AVFormatContext *s, const char *content)
422 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
423 * contain long SDP lines containing complete ASF Headers (several
424 * kB) or arrays of MDPR (RM stream descriptor) headers plus
425 * "rulebooks" describing their properties. Therefore, the SDP line
428 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
429 * in rtpdec_xiph.c. */
431 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
433 memset(s1, 0, sizeof(SDPParseState));
436 p += strspn(p, SPACE_CHARS);
444 /* get the content */
446 while (*p != '\n' && *p != '\r' && *p != '\0') {
447 if ((q - buf) < sizeof(buf) - 1)
452 sdp_parse_line(s, s1, letter, buf);
454 while (*p != '\n' && *p != '\0')
461 #endif /* CONFIG_RTPDEC */
463 /* close and free RTSP streams */
464 void ff_rtsp_close_streams(AVFormatContext *s)
466 RTSPState *rt = s->priv_data;
470 for (i = 0; i < rt->nb_rtsp_streams; i++) {
471 rtsp_st = rt->rtsp_streams[i];
473 if (rtsp_st->transport_priv) {
475 AVFormatContext *rtpctx = rtsp_st->transport_priv;
476 av_write_trailer(rtpctx);
477 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
479 url_close_dyn_buf(rtpctx->pb, &ptr);
482 url_fclose(rtpctx->pb);
484 av_metadata_free(&rtpctx->streams[0]->metadata);
485 av_metadata_free(&rtpctx->metadata);
486 av_free(rtpctx->streams[0]);
488 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
489 ff_rdt_parse_close(rtsp_st->transport_priv);
490 else if (CONFIG_RTPDEC)
491 rtp_parse_close(rtsp_st->transport_priv);
493 if (rtsp_st->rtp_handle)
494 url_close(rtsp_st->rtp_handle);
495 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
496 rtsp_st->dynamic_handler->close(
497 rtsp_st->dynamic_protocol_context);
500 av_free(rt->rtsp_streams);
502 av_close_input_stream (rt->asf_ctx);
505 av_free(rt->recvbuf);
508 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
510 RTSPState *rt = s->priv_data;
513 /* open the RTP context */
514 if (rtsp_st->stream_index >= 0)
515 st = s->streams[rtsp_st->stream_index];
517 s->ctx_flags |= AVFMTCTX_NOHEADER;
519 if (s->oformat && CONFIG_RTSP_MUXER) {
520 rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
522 RTSP_TCP_MAX_PACKET_SIZE);
523 /* Ownership of rtp_handle is passed to the rtp mux context */
524 rtsp_st->rtp_handle = NULL;
525 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
526 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
527 rtsp_st->dynamic_protocol_context,
528 rtsp_st->dynamic_handler);
529 else if (CONFIG_RTPDEC)
530 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
531 rtsp_st->sdp_payload_type,
532 (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
533 ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
535 if (!rtsp_st->transport_priv) {
536 return AVERROR(ENOMEM);
537 } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
538 if (rtsp_st->dynamic_handler) {
539 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
540 rtsp_st->dynamic_protocol_context,
541 rtsp_st->dynamic_handler);
548 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
549 static int rtsp_probe(AVProbeData *p)
551 if (av_strstart(p->filename, "rtsp:", NULL))
552 return AVPROBE_SCORE_MAX;
556 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
562 p += strspn(p, SPACE_CHARS);
563 v = strtol(p, (char **)&p, 10);
567 v = strtol(p, (char **)&p, 10);
576 /* XXX: only one transport specification is parsed */
577 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
579 char transport_protocol[16];
581 char lower_transport[16];
583 RTSPTransportField *th;
586 reply->nb_transports = 0;
589 p += strspn(p, SPACE_CHARS);
593 th = &reply->transports[reply->nb_transports];
595 get_word_sep(transport_protocol, sizeof(transport_protocol),
597 if (!strcasecmp (transport_protocol, "rtp")) {
598 get_word_sep(profile, sizeof(profile), "/;,", &p);
599 lower_transport[0] = '\0';
600 /* rtp/avp/<protocol> */
602 get_word_sep(lower_transport, sizeof(lower_transport),
605 th->transport = RTSP_TRANSPORT_RTP;
606 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
607 !strcasecmp (transport_protocol, "x-real-rdt")) {
608 /* x-pn-tng/<protocol> */
609 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
611 th->transport = RTSP_TRANSPORT_RDT;
613 if (!strcasecmp(lower_transport, "TCP"))
614 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
616 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
620 /* get each parameter */
621 while (*p != '\0' && *p != ',') {
622 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
623 if (!strcmp(parameter, "port")) {
626 rtsp_parse_range(&th->port_min, &th->port_max, &p);
628 } else if (!strcmp(parameter, "client_port")) {
631 rtsp_parse_range(&th->client_port_min,
632 &th->client_port_max, &p);
634 } else if (!strcmp(parameter, "server_port")) {
637 rtsp_parse_range(&th->server_port_min,
638 &th->server_port_max, &p);
640 } else if (!strcmp(parameter, "interleaved")) {
643 rtsp_parse_range(&th->interleaved_min,
644 &th->interleaved_max, &p);
646 } else if (!strcmp(parameter, "multicast")) {
647 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
648 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
649 } else if (!strcmp(parameter, "ttl")) {
652 th->ttl = strtol(p, (char **)&p, 10);
654 } else if (!strcmp(parameter, "destination")) {
657 get_word_sep(buf, sizeof(buf), ";,", &p);
658 get_sockaddr(buf, &th->destination);
660 } else if (!strcmp(parameter, "source")) {
663 get_word_sep(buf, sizeof(buf), ";,", &p);
664 av_strlcpy(th->source, buf, sizeof(th->source));
668 while (*p != ';' && *p != '\0' && *p != ',')
676 reply->nb_transports++;
680 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
681 HTTPAuthState *auth_state)
685 /* NOTE: we do case independent match for broken servers */
687 if (av_stristart(p, "Session:", &p)) {
689 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
690 if (av_stristart(p, ";timeout=", &p) &&
691 (t = strtol(p, NULL, 10)) > 0) {
694 } else if (av_stristart(p, "Content-Length:", &p)) {
695 reply->content_length = strtol(p, NULL, 10);
696 } else if (av_stristart(p, "Transport:", &p)) {
697 rtsp_parse_transport(reply, p);
698 } else if (av_stristart(p, "CSeq:", &p)) {
699 reply->seq = strtol(p, NULL, 10);
700 } else if (av_stristart(p, "Range:", &p)) {
701 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
702 } else if (av_stristart(p, "RealChallenge1:", &p)) {
703 p += strspn(p, SPACE_CHARS);
704 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
705 } else if (av_stristart(p, "Server:", &p)) {
706 p += strspn(p, SPACE_CHARS);
707 av_strlcpy(reply->server, p, sizeof(reply->server));
708 } else if (av_stristart(p, "Notice:", &p) ||
709 av_stristart(p, "X-Notice:", &p)) {
710 reply->notice = strtol(p, NULL, 10);
711 } else if (av_stristart(p, "Location:", &p)) {
712 p += strspn(p, SPACE_CHARS);
713 av_strlcpy(reply->location, p , sizeof(reply->location));
714 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
715 p += strspn(p, SPACE_CHARS);
716 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
717 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
718 p += strspn(p, SPACE_CHARS);
719 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
723 /* skip a RTP/TCP interleaved packet */
724 void ff_rtsp_skip_packet(AVFormatContext *s)
726 RTSPState *rt = s->priv_data;
730 ret = url_read_complete(rt->rtsp_hd, buf, 3);
733 len = AV_RB16(buf + 1);
735 dprintf(s, "skipping RTP packet len=%d\n", len);
740 if (len1 > sizeof(buf))
742 ret = url_read_complete(rt->rtsp_hd, buf, len1);
749 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
750 unsigned char **content_ptr,
751 int return_on_interleaved_data)
753 RTSPState *rt = s->priv_data;
754 char buf[4096], buf1[1024], *q;
757 int ret, content_length, line_count = 0;
758 unsigned char *content = NULL;
760 memset(reply, 0, sizeof(*reply));
762 /* parse reply (XXX: use buffers) */
763 rt->last_reply[0] = '\0';
767 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
769 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
776 /* XXX: only parse it if first char on line ? */
777 if (return_on_interleaved_data) {
780 ff_rtsp_skip_packet(s);
781 } else if (ch != '\r') {
782 if ((q - buf) < sizeof(buf) - 1)
788 dprintf(s, "line='%s'\n", buf);
790 /* test if last line */
794 if (line_count == 0) {
796 get_word(buf1, sizeof(buf1), &p);
797 get_word(buf1, sizeof(buf1), &p);
798 reply->status_code = atoi(buf1);
799 av_strlcpy(reply->reason, p, sizeof(reply->reason));
801 ff_rtsp_parse_line(reply, p, &rt->auth_state);
802 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
803 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
808 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
809 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
811 content_length = reply->content_length;
812 if (content_length > 0) {
813 /* leave some room for a trailing '\0' (useful for simple parsing) */
814 content = av_malloc(content_length + 1);
815 (void)url_read_complete(rt->rtsp_hd, content, content_length);
816 content[content_length] = '\0';
819 *content_ptr = content;
823 if (rt->seq != reply->seq) {
824 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
825 rt->seq, reply->seq);
829 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
830 reply->notice == 2104 /* Start-of-Stream Reached */ ||
831 reply->notice == 2306 /* Continuous Feed Terminated */) {
832 rt->state = RTSP_STATE_IDLE;
833 } else if (reply->notice >= 4400 && reply->notice < 5500) {
834 return AVERROR(EIO); /* data or server error */
835 } else if (reply->notice == 2401 /* Ticket Expired */ ||
836 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
837 return AVERROR(EPERM);
842 int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
843 const char *method, const char *url,
845 const unsigned char *send_content,
846 int send_content_length)
848 RTSPState *rt = s->priv_data;
849 char buf[4096], *out_buf;
850 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
852 /* Add in RTSP headers */
855 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
857 av_strlcat(buf, headers, sizeof(buf));
858 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
859 if (rt->session_id[0] != '\0' && (!headers ||
860 !strstr(headers, "\nIf-Match:"))) {
861 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
864 char *str = ff_http_auth_create_response(&rt->auth_state,
865 rt->auth, url, method);
867 av_strlcat(buf, str, sizeof(buf));
870 if (send_content_length > 0 && send_content)
871 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
872 av_strlcat(buf, "\r\n", sizeof(buf));
874 /* base64 encode rtsp if tunneling */
875 if (rt->control_transport == RTSP_MODE_TUNNEL) {
876 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
880 dprintf(s, "Sending:\n%s--\n", buf);
882 url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
883 if (send_content_length > 0 && send_content) {
884 if (rt->control_transport == RTSP_MODE_TUNNEL) {
885 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
886 "with content data not supported\n");
887 return AVERROR_PATCHWELCOME;
889 url_write(rt->rtsp_hd_out, send_content, send_content_length);
891 rt->last_cmd_time = av_gettime();
896 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
897 const char *url, const char *headers)
899 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
902 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
903 const char *headers, RTSPMessageHeader *reply,
904 unsigned char **content_ptr)
906 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
907 content_ptr, NULL, 0);
910 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
911 const char *method, const char *url,
913 RTSPMessageHeader *reply,
914 unsigned char **content_ptr,
915 const unsigned char *send_content,
916 int send_content_length)
918 RTSPState *rt = s->priv_data;
919 HTTPAuthType cur_auth_type;
923 cur_auth_type = rt->auth_state.auth_type;
924 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
926 send_content_length)))
929 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
932 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
933 rt->auth_state.auth_type != HTTP_AUTH_NONE)
936 if (reply->status_code > 400){
937 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
941 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
948 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
950 static int make_setup_request(AVFormatContext *s, const char *host, int port,
951 int lower_transport, const char *real_challenge)
953 RTSPState *rt = s->priv_data;
954 int rtx, j, i, err, interleave = 0;
956 RTSPMessageHeader reply1, *reply = &reply1;
958 const char *trans_pref;
960 if (rt->transport == RTSP_TRANSPORT_RDT)
961 trans_pref = "x-pn-tng";
963 trans_pref = "RTP/AVP";
965 /* default timeout: 1 minute */
968 /* for each stream, make the setup request */
969 /* XXX: we assume the same server is used for the control of each
972 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
973 char transport[2048];
976 * WMS serves all UDP data over a single connection, the RTX, which
977 * isn't necessarily the first in the SDP but has to be the first
978 * to be set up, else the second/third SETUP will fail with a 461.
980 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
981 rt->server_type == RTSP_SERVER_WMS) {
984 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
985 int len = strlen(rt->rtsp_streams[rtx]->control_url);
987 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
991 if (rtx == rt->nb_rtsp_streams)
992 return -1; /* no RTX found */
993 rtsp_st = rt->rtsp_streams[rtx];
995 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
997 rtsp_st = rt->rtsp_streams[i];
1000 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1003 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1004 port = reply->transports[0].client_port_min;
1008 /* first try in specified port range */
1009 if (RTSP_RTP_PORT_MIN != 0) {
1010 while (j <= RTSP_RTP_PORT_MAX) {
1011 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1012 "?localport=%d", j);
1013 /* we will use two ports per rtp stream (rtp and rtcp) */
1015 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1021 /* then try on any port */
1022 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1023 err = AVERROR_INVALIDDATA;
1029 port = rtp_get_local_port(rtsp_st->rtp_handle);
1031 snprintf(transport, sizeof(transport) - 1,
1032 "%s/UDP;", trans_pref);
1033 if (rt->server_type != RTSP_SERVER_REAL)
1034 av_strlcat(transport, "unicast;", sizeof(transport));
1035 av_strlcatf(transport, sizeof(transport),
1036 "client_port=%d", port);
1037 if (rt->transport == RTSP_TRANSPORT_RTP &&
1038 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1039 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1043 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1044 /** For WMS streams, the application streams are only used for
1045 * UDP. When trying to set it up for TCP streams, the server
1046 * will return an error. Therefore, we skip those streams. */
1047 if (rt->server_type == RTSP_SERVER_WMS &&
1048 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1051 snprintf(transport, sizeof(transport) - 1,
1052 "%s/TCP;", trans_pref);
1053 if (rt->server_type == RTSP_SERVER_WMS)
1054 av_strlcat(transport, "unicast;", sizeof(transport));
1055 av_strlcatf(transport, sizeof(transport),
1056 "interleaved=%d-%d",
1057 interleave, interleave + 1);
1061 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1062 snprintf(transport, sizeof(transport) - 1,
1063 "%s/UDP;multicast", trans_pref);
1066 av_strlcat(transport, ";mode=receive", sizeof(transport));
1067 } else if (rt->server_type == RTSP_SERVER_REAL ||
1068 rt->server_type == RTSP_SERVER_WMS)
1069 av_strlcat(transport, ";mode=play", sizeof(transport));
1070 snprintf(cmd, sizeof(cmd),
1071 "Transport: %s\r\n",
1073 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
1074 char real_res[41], real_csum[9];
1075 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1077 av_strlcatf(cmd, sizeof(cmd),
1079 "RealChallenge2: %s, sd=%s\r\n",
1080 rt->session_id, real_res, real_csum);
1082 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1083 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1086 } else if (reply->status_code != RTSP_STATUS_OK ||
1087 reply->nb_transports != 1) {
1088 err = AVERROR_INVALIDDATA;
1092 /* XXX: same protocol for all streams is required */
1094 if (reply->transports[0].lower_transport != rt->lower_transport ||
1095 reply->transports[0].transport != rt->transport) {
1096 err = AVERROR_INVALIDDATA;
1100 rt->lower_transport = reply->transports[0].lower_transport;
1101 rt->transport = reply->transports[0].transport;
1104 /* close RTP connection if not chosen */
1105 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1106 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1107 url_close(rtsp_st->rtp_handle);
1108 rtsp_st->rtp_handle = NULL;
1111 switch(reply->transports[0].lower_transport) {
1112 case RTSP_LOWER_TRANSPORT_TCP:
1113 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1114 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1117 case RTSP_LOWER_TRANSPORT_UDP: {
1120 /* Use source address if specified */
1121 if (reply->transports[0].source[0]) {
1122 ff_url_join(url, sizeof(url), "rtp", NULL,
1123 reply->transports[0].source,
1124 reply->transports[0].server_port_min, NULL);
1126 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1127 reply->transports[0].server_port_min, NULL);
1129 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1130 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1131 err = AVERROR_INVALIDDATA;
1134 /* Try to initialize the connection state in a
1135 * potential NAT router by sending dummy packets.
1136 * RTP/RTCP dummy packets are used for RDT, too.
1138 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1140 rtp_send_punch_packets(rtsp_st->rtp_handle);
1143 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1144 char url[1024], namebuf[50];
1145 struct sockaddr_storage addr;
1148 if (reply->transports[0].destination.ss_family) {
1149 addr = reply->transports[0].destination;
1150 port = reply->transports[0].port_min;
1151 ttl = reply->transports[0].ttl;
1153 addr = rtsp_st->sdp_ip;
1154 port = rtsp_st->sdp_port;
1155 ttl = rtsp_st->sdp_ttl;
1157 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1158 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1159 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1160 port, "?ttl=%d", ttl);
1161 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1162 err = AVERROR_INVALIDDATA;
1169 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1173 if (reply->timeout > 0)
1174 rt->timeout = reply->timeout;
1176 if (rt->server_type == RTSP_SERVER_REAL)
1177 rt->need_subscription = 1;
1182 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1183 if (rt->rtsp_streams[i]->rtp_handle) {
1184 url_close(rt->rtsp_streams[i]->rtp_handle);
1185 rt->rtsp_streams[i]->rtp_handle = NULL;
1191 static int rtsp_read_play(AVFormatContext *s)
1193 RTSPState *rt = s->priv_data;
1194 RTSPMessageHeader reply1, *reply = &reply1;
1198 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1201 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1202 if (rt->state == RTSP_STATE_PAUSED) {
1205 snprintf(cmd, sizeof(cmd),
1206 "Range: npt=%0.3f-\r\n",
1207 (double)rt->seek_timestamp / AV_TIME_BASE);
1209 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1210 if (reply->status_code != RTSP_STATUS_OK) {
1213 if (rt->transport == RTSP_TRANSPORT_RTP) {
1214 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1215 RTSPStream *rtsp_st = rt->rtsp_streams[i];
1216 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1217 AVStream *st = NULL;
1220 if (rtsp_st->stream_index >= 0)
1221 st = s->streams[rtsp_st->stream_index];
1222 ff_rtp_reset_packet_queue(rtpctx);
1223 if (reply->range_start != AV_NOPTS_VALUE) {
1224 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
1225 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1227 rtpctx->range_start_offset =
1228 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
1234 rt->state = RTSP_STATE_STREAMING;
1238 #if CONFIG_RTSP_DEMUXER
1239 static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1241 RTSPState *rt = s->priv_data;
1243 unsigned char *content = NULL;
1246 /* describe the stream */
1247 snprintf(cmd, sizeof(cmd),
1248 "Accept: application/sdp\r\n");
1249 if (rt->server_type == RTSP_SERVER_REAL) {
1251 * The Require: attribute is needed for proper streaming from
1252 * Realmedia servers.
1255 "Require: com.real.retain-entity-for-setup\r\n",
1258 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1260 return AVERROR_INVALIDDATA;
1261 if (reply->status_code != RTSP_STATUS_OK) {
1263 return AVERROR_INVALIDDATA;
1266 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
1267 /* now we got the SDP description, we parse it */
1268 ret = sdp_parse(s, (const char *)content);
1271 return AVERROR_INVALIDDATA;
1275 #endif /* CONFIG_RTSP_DEMUXER */
1277 #if CONFIG_RTSP_MUXER
1278 static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1280 RTSPState *rt = s->priv_data;
1281 RTSPMessageHeader reply1, *reply = &reply1;
1284 AVFormatContext sdp_ctx, *ctx_array[1];
1286 s->start_time_realtime = av_gettime();
1288 /* Announce the stream */
1289 sdp = av_mallocz(SDP_MAX_SIZE);
1291 return AVERROR(ENOMEM);
1292 /* We create the SDP based on the RTSP AVFormatContext where we
1293 * aren't allowed to change the filename field. (We create the SDP
1294 * based on the RTSP context since the contexts for the RTP streams
1295 * don't exist yet.) In order to specify a custom URL with the actual
1296 * peer IP instead of the originally specified hostname, we create
1297 * a temporary copy of the AVFormatContext, where the custom URL is set.
1299 * FIXME: Create the SDP without copying the AVFormatContext.
1300 * This either requires setting up the RTP stream AVFormatContexts
1301 * already here (complicating things immensely) or getting a more
1302 * flexible SDP creation interface.
1305 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1306 "rtsp", NULL, addr, -1, NULL);
1307 ctx_array[0] = &sdp_ctx;
1308 if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
1310 return AVERROR_INVALIDDATA;
1312 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
1313 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1314 "Content-Type: application/sdp\r\n",
1315 reply, NULL, sdp, strlen(sdp));
1317 if (reply->status_code != RTSP_STATUS_OK)
1318 return AVERROR_INVALIDDATA;
1320 /* Set up the RTSPStreams for each AVStream */
1321 for (i = 0; i < s->nb_streams; i++) {
1322 RTSPStream *rtsp_st;
1323 AVStream *st = s->streams[i];
1325 rtsp_st = av_mallocz(sizeof(RTSPStream));
1327 return AVERROR(ENOMEM);
1328 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1330 st->priv_data = rtsp_st;
1331 rtsp_st->stream_index = i;
1333 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1334 /* Note, this must match the relative uri set in the sdp content */
1335 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1341 #endif /* CONFIG_RTSP_MUXER */
1343 void ff_rtsp_close_connections(AVFormatContext *s)
1345 RTSPState *rt = s->priv_data;
1346 if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1347 url_close(rt->rtsp_hd);
1348 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1351 int ff_rtsp_connect(AVFormatContext *s)
1353 RTSPState *rt = s->priv_data;
1354 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1355 char *option_list, *option, *filename;
1356 int port, err, tcp_fd;
1357 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1358 int lower_transport_mask = 0;
1359 char real_challenge[64];
1360 struct sockaddr_storage peer;
1361 socklen_t peer_len = sizeof(peer);
1363 if (!ff_network_init())
1364 return AVERROR(EIO);
1366 rt->control_transport = RTSP_MODE_PLAIN;
1367 /* extract hostname and port */
1368 av_url_split(NULL, 0, auth, sizeof(auth),
1369 host, sizeof(host), &port, path, sizeof(path), s->filename);
1371 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1374 port = RTSP_DEFAULT_PORT;
1376 /* search for options */
1377 option_list = strrchr(path, '?');
1379 /* Strip out the RTSP specific options, write out the rest of
1380 * the options back into the same string. */
1381 filename = option_list;
1382 while (option_list) {
1383 /* move the option pointer */
1384 option = ++option_list;
1385 option_list = strchr(option_list, '&');
1389 /* handle the options */
1390 if (!strcmp(option, "udp")) {
1391 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1392 } else if (!strcmp(option, "multicast")) {
1393 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1394 } else if (!strcmp(option, "tcp")) {
1395 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1396 } else if(!strcmp(option, "http")) {
1397 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1398 rt->control_transport = RTSP_MODE_TUNNEL;
1400 /* Write options back into the buffer, using memmove instead
1401 * of strcpy since the strings may overlap. */
1402 int len = strlen(option);
1403 memmove(++filename, option, len);
1405 if (option_list) *filename = '&';
1411 if (!lower_transport_mask)
1412 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1415 /* Only UDP or TCP - UDP multicast isn't supported. */
1416 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1417 (1 << RTSP_LOWER_TRANSPORT_TCP);
1418 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1419 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1420 "only UDP and TCP are supported for output.\n");
1421 err = AVERROR(EINVAL);
1426 /* Construct the URI used in request; this is similar to s->filename,
1427 * but with authentication credentials removed and RTSP specific options
1429 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1430 host, port, "%s", path);
1432 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1433 /* set up initial handshake for tunneling */
1434 char httpname[1024];
1435 char sessioncookie[17];
1438 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1439 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1440 av_get_random_seed(), av_get_random_seed());
1443 if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
1448 /* generate GET headers */
1449 snprintf(headers, sizeof(headers),
1450 "x-sessioncookie: %s\r\n"
1451 "Accept: application/x-rtsp-tunnelled\r\n"
1452 "Pragma: no-cache\r\n"
1453 "Cache-Control: no-cache\r\n",
1455 ff_http_set_headers(rt->rtsp_hd, headers);
1457 /* complete the connection */
1458 if (url_connect(rt->rtsp_hd)) {
1464 if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1469 /* generate POST headers */
1470 snprintf(headers, sizeof(headers),
1471 "x-sessioncookie: %s\r\n"
1472 "Content-Type: application/x-rtsp-tunnelled\r\n"
1473 "Pragma: no-cache\r\n"
1474 "Cache-Control: no-cache\r\n"
1475 "Content-Length: 32767\r\n"
1476 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1478 ff_http_set_headers(rt->rtsp_hd_out, headers);
1479 ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1481 /* Initialize the authentication state for the POST session. The HTTP
1482 * protocol implementation doesn't properly handle multi-pass
1483 * authentication for POST requests, since it would require one of
1485 * - implementing Expect: 100-continue, which many HTTP servers
1486 * don't support anyway, even less the RTSP servers that do HTTP
1488 * - sending the whole POST data until getting a 401 reply specifying
1489 * what authentication method to use, then resending all that data
1490 * - waiting for potential 401 replies directly after sending the
1491 * POST header (waiting for some unspecified time)
1492 * Therefore, we copy the full auth state, which works for both basic
1493 * and digest. (For digest, we would have to synchronize the nonce
1494 * count variable between the two sessions, if we'd do more requests
1495 * with the original session, though.)
1497 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1499 /* complete the connection */
1500 if (url_connect(rt->rtsp_hd_out)) {
1505 /* open the tcp connection */
1506 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1507 if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
1511 rt->rtsp_hd_out = rt->rtsp_hd;
1515 tcp_fd = url_get_file_handle(rt->rtsp_hd);
1516 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1517 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1518 NULL, 0, NI_NUMERICHOST);
1521 /* request options supported by the server; this also detects server
1523 for (rt->server_type = RTSP_SERVER_RTP;;) {
1525 if (rt->server_type == RTSP_SERVER_REAL)
1528 * The following entries are required for proper
1529 * streaming from a Realmedia server. They are
1530 * interdependent in some way although we currently
1531 * don't quite understand how. Values were copied
1532 * from mplayer SVN r23589.
1533 * @param CompanyID is a 16-byte ID in base64
1534 * @param ClientChallenge is a 16-byte ID in hex
1536 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1537 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1538 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1539 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1541 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1542 if (reply->status_code != RTSP_STATUS_OK) {
1543 err = AVERROR_INVALIDDATA;
1547 /* detect server type if not standard-compliant RTP */
1548 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1549 rt->server_type = RTSP_SERVER_REAL;
1551 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1552 rt->server_type = RTSP_SERVER_WMS;
1553 } else if (rt->server_type == RTSP_SERVER_REAL)
1554 strcpy(real_challenge, reply->real_challenge);
1558 if (s->iformat && CONFIG_RTSP_DEMUXER)
1559 err = rtsp_setup_input_streams(s, reply);
1560 else if (CONFIG_RTSP_MUXER)
1561 err = rtsp_setup_output_streams(s, host);
1566 int lower_transport = ff_log2_tab[lower_transport_mask &
1567 ~(lower_transport_mask - 1)];
1569 err = make_setup_request(s, host, port, lower_transport,
1570 rt->server_type == RTSP_SERVER_REAL ?
1571 real_challenge : NULL);
1574 lower_transport_mask &= ~(1 << lower_transport);
1575 if (lower_transport_mask == 0 && err == 1) {
1576 err = FF_NETERROR(EPROTONOSUPPORT);
1581 rt->state = RTSP_STATE_IDLE;
1582 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1585 ff_rtsp_close_streams(s);
1586 ff_rtsp_close_connections(s);
1587 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1588 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1589 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1597 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1600 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1601 uint8_t *buf, int buf_size, int64_t wait_end)
1603 RTSPState *rt = s->priv_data;
1604 RTSPStream *rtsp_st;
1606 int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1610 if (url_interrupt_cb())
1611 return AVERROR(EINTR);
1612 if (wait_end && wait_end - av_gettime() < 0)
1613 return AVERROR(EAGAIN);
1616 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1617 FD_SET(tcp_fd, &rfds);
1622 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1623 rtsp_st = rt->rtsp_streams[i];
1624 if (rtsp_st->rtp_handle) {
1625 fd = url_get_file_handle(rtsp_st->rtp_handle);
1626 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1627 if (FFMAX(fd, fd_rtcp) > fd_max)
1628 fd_max = FFMAX(fd, fd_rtcp);
1630 FD_SET(fd_rtcp, &rfds);
1634 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1635 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1638 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1639 rtsp_st = rt->rtsp_streams[i];
1640 if (rtsp_st->rtp_handle) {
1641 fd = url_get_file_handle(rtsp_st->rtp_handle);
1642 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1643 if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
1644 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1646 *prtsp_st = rtsp_st;
1652 #if CONFIG_RTSP_DEMUXER
1653 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1654 RTSPMessageHeader reply;
1656 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1659 /* XXX: parse message */
1660 if (rt->state != RTSP_STATE_STREAMING)
1664 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1665 return FF_NETERROR(ETIMEDOUT);
1666 } else if (n < 0 && errno != EINTR)
1667 return AVERROR(errno);
1671 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1672 uint8_t *buf, int buf_size);
1674 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1676 RTSPState *rt = s->priv_data;
1678 RTSPStream *rtsp_st, *first_queue_st = NULL;
1679 int64_t wait_end = 0;
1681 if (rt->nb_byes == rt->nb_rtsp_streams)
1684 /* get next frames from the same RTP packet */
1685 if (rt->cur_transport_priv) {
1686 if (rt->transport == RTSP_TRANSPORT_RDT) {
1687 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1689 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1691 rt->cur_transport_priv = NULL;
1693 } else if (ret == 1) {
1696 rt->cur_transport_priv = NULL;
1699 if (rt->transport == RTSP_TRANSPORT_RTP) {
1701 int64_t first_queue_time = 0;
1702 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1703 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1704 int64_t queue_time = ff_rtp_queued_packet_time(rtpctx);
1705 if (queue_time && (queue_time - first_queue_time < 0 ||
1706 !first_queue_time)) {
1707 first_queue_time = queue_time;
1708 first_queue_st = rt->rtsp_streams[i];
1711 if (first_queue_time)
1712 wait_end = first_queue_time + s->max_delay;
1715 /* read next RTP packet */
1718 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1720 return AVERROR(ENOMEM);
1723 switch(rt->lower_transport) {
1725 #if CONFIG_RTSP_DEMUXER
1726 case RTSP_LOWER_TRANSPORT_TCP:
1727 len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1730 case RTSP_LOWER_TRANSPORT_UDP:
1731 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1732 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
1733 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1734 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1737 if (len == AVERROR(EAGAIN) && first_queue_st &&
1738 rt->transport == RTSP_TRANSPORT_RTP) {
1739 rtsp_st = first_queue_st;
1740 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
1747 if (rt->transport == RTSP_TRANSPORT_RDT) {
1748 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1750 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1752 /* Either bad packet, or a RTCP packet. Check if the
1753 * first_rtcp_ntp_time field was initialized. */
1754 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1755 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1756 /* first_rtcp_ntp_time has been initialized for this stream,
1757 * copy the same value to all other uninitialized streams,
1758 * in order to map their timestamp origin to the same ntp time
1761 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1762 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1764 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1765 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1768 if (ret == -RTCP_BYE) {
1771 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1772 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1774 if (rt->nb_byes == rt->nb_rtsp_streams)
1783 /* more packets may follow, so we save the RTP context */
1784 rt->cur_transport_priv = rtsp_st->transport_priv;
1788 #endif /* CONFIG_RTPDEC */
1790 #if CONFIG_RTSP_DEMUXER
1791 static int rtsp_read_header(AVFormatContext *s,
1792 AVFormatParameters *ap)
1794 RTSPState *rt = s->priv_data;
1797 ret = ff_rtsp_connect(s);
1801 rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
1802 if (!rt->real_setup_cache)
1803 return AVERROR(ENOMEM);
1804 rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
1806 if (ap->initial_pause) {
1807 /* do not start immediately */
1809 if (rtsp_read_play(s) < 0) {
1810 ff_rtsp_close_streams(s);
1811 ff_rtsp_close_connections(s);
1812 return AVERROR_INVALIDDATA;
1819 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1820 uint8_t *buf, int buf_size)
1822 RTSPState *rt = s->priv_data;
1823 int id, len, i, ret;
1824 RTSPStream *rtsp_st;
1826 #ifdef DEBUG_RTP_TCP
1827 dprintf(s, "tcp_read_packet:\n");
1831 RTSPMessageHeader reply;
1833 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1836 if (ret == 1) /* received '$' */
1838 /* XXX: parse message */
1839 if (rt->state != RTSP_STATE_STREAMING)
1842 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1846 len = AV_RB16(buf + 1);
1847 #ifdef DEBUG_RTP_TCP
1848 dprintf(s, "id=%d len=%d\n", id, len);
1850 if (len > buf_size || len < 12)
1853 ret = url_read_complete(rt->rtsp_hd, buf, len);
1856 if (rt->transport == RTSP_TRANSPORT_RDT &&
1857 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1860 /* find the matching stream */
1861 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1862 rtsp_st = rt->rtsp_streams[i];
1863 if (id >= rtsp_st->interleaved_min &&
1864 id <= rtsp_st->interleaved_max)
1869 *prtsp_st = rtsp_st;
1872 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1874 RTSPState *rt = s->priv_data;
1876 RTSPMessageHeader reply1, *reply = &reply1;
1879 if (rt->server_type == RTSP_SERVER_REAL) {
1882 for (i = 0; i < s->nb_streams; i++)
1883 rt->real_setup[i] = s->streams[i]->discard;
1885 if (!rt->need_subscription) {
1886 if (memcmp (rt->real_setup, rt->real_setup_cache,
1887 sizeof(enum AVDiscard) * s->nb_streams)) {
1888 snprintf(cmd, sizeof(cmd),
1889 "Unsubscribe: %s\r\n",
1890 rt->last_subscription);
1891 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1893 if (reply->status_code != RTSP_STATUS_OK)
1894 return AVERROR_INVALIDDATA;
1895 rt->need_subscription = 1;
1899 if (rt->need_subscription) {
1900 int r, rule_nr, first = 1;
1902 memcpy(rt->real_setup_cache, rt->real_setup,
1903 sizeof(enum AVDiscard) * s->nb_streams);
1904 rt->last_subscription[0] = 0;
1906 snprintf(cmd, sizeof(cmd),
1908 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1910 for (r = 0; r < s->nb_streams; r++) {
1911 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1912 if (s->streams[r]->discard != AVDISCARD_ALL) {
1914 av_strlcat(rt->last_subscription, ",",
1915 sizeof(rt->last_subscription));
1916 ff_rdt_subscribe_rule(
1917 rt->last_subscription,
1918 sizeof(rt->last_subscription), i, rule_nr);
1925 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1926 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1928 if (reply->status_code != RTSP_STATUS_OK)
1929 return AVERROR_INVALIDDATA;
1930 rt->need_subscription = 0;
1932 if (rt->state == RTSP_STATE_STREAMING)
1937 ret = rtsp_fetch_packet(s, pkt);
1941 /* send dummy request to keep TCP connection alive */
1942 if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1943 if (rt->server_type == RTSP_SERVER_WMS) {
1944 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1946 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1953 /* pause the stream */
1954 static int rtsp_read_pause(AVFormatContext *s)
1956 RTSPState *rt = s->priv_data;
1957 RTSPMessageHeader reply1, *reply = &reply1;
1959 if (rt->state != RTSP_STATE_STREAMING)
1961 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1962 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1963 if (reply->status_code != RTSP_STATUS_OK) {
1967 rt->state = RTSP_STATE_PAUSED;
1971 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1972 int64_t timestamp, int flags)
1974 RTSPState *rt = s->priv_data;
1976 rt->seek_timestamp = av_rescale_q(timestamp,
1977 s->streams[stream_index]->time_base,
1981 case RTSP_STATE_IDLE:
1983 case RTSP_STATE_STREAMING:
1984 if (rtsp_read_pause(s) != 0)
1986 rt->state = RTSP_STATE_SEEKING;
1987 if (rtsp_read_play(s) != 0)
1990 case RTSP_STATE_PAUSED:
1991 rt->state = RTSP_STATE_IDLE;
1997 static int rtsp_read_close(AVFormatContext *s)
1999 RTSPState *rt = s->priv_data;
2002 /* NOTE: it is valid to flush the buffer here */
2003 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
2004 url_fclose(&rt->rtsp_gb);
2007 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
2009 ff_rtsp_close_streams(s);
2010 ff_rtsp_close_connections(s);
2012 rt->real_setup = NULL;
2013 av_freep(&rt->real_setup_cache);
2017 AVInputFormat rtsp_demuxer = {
2019 NULL_IF_CONFIG_SMALL("RTSP input format"),
2026 .flags = AVFMT_NOFILE,
2027 .read_play = rtsp_read_play,
2028 .read_pause = rtsp_read_pause,
2030 #endif /* CONFIG_RTSP_DEMUXER */
2032 #if CONFIG_SDP_DEMUXER
2033 static int sdp_probe(AVProbeData *p1)
2035 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2037 /* we look for a line beginning "c=IN IP" */
2038 while (p < p_end && *p != '\0') {
2039 if (p + sizeof("c=IN IP") - 1 < p_end &&
2040 av_strstart(p, "c=IN IP", NULL))
2041 return AVPROBE_SCORE_MAX / 2;
2043 while (p < p_end - 1 && *p != '\n') p++;
2052 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2054 RTSPState *rt = s->priv_data;
2055 RTSPStream *rtsp_st;
2060 if (!ff_network_init())
2061 return AVERROR(EIO);
2063 /* read the whole sdp file */
2064 /* XXX: better loading */
2065 content = av_malloc(SDP_MAX_SIZE);
2066 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2069 return AVERROR_INVALIDDATA;
2071 content[size] ='\0';
2073 sdp_parse(s, content);
2076 /* open each RTP stream */
2077 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2079 rtsp_st = rt->rtsp_streams[i];
2081 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2082 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2083 ff_url_join(url, sizeof(url), "rtp", NULL,
2084 namebuf, rtsp_st->sdp_port,
2085 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2087 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2088 err = AVERROR_INVALIDDATA;
2091 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2096 ff_rtsp_close_streams(s);
2101 static int sdp_read_close(AVFormatContext *s)
2103 ff_rtsp_close_streams(s);
2108 AVInputFormat sdp_demuxer = {
2110 NULL_IF_CONFIG_SMALL("SDP"),
2117 #endif /* CONFIG_SDP_DEMUXER */
2119 #if CONFIG_RTP_DEMUXER
2120 static int rtp_probe(AVProbeData *p)
2122 if (av_strstart(p->filename, "rtp:", NULL))
2123 return AVPROBE_SCORE_MAX;
2127 static int rtp_read_header(AVFormatContext *s,
2128 AVFormatParameters *ap)
2130 uint8_t recvbuf[1500];
2131 char host[500], sdp[500];
2133 URLContext* in = NULL;
2135 AVCodecContext codec;
2136 struct sockaddr_storage addr;
2138 socklen_t addrlen = sizeof(addr);
2140 if (!ff_network_init())
2141 return AVERROR(EIO);
2143 ret = url_open(&in, s->filename, URL_RDONLY);
2148 ret = url_read(in, recvbuf, sizeof(recvbuf));
2149 if (ret == AVERROR(EAGAIN))
2154 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2158 if ((recvbuf[0] & 0xc0) != 0x80) {
2159 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2164 payload_type = recvbuf[1] & 0x7f;
2167 getsockname(url_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2171 memset(&codec, 0, sizeof(codec));
2172 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2173 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2174 "without an SDP file describing it\n",
2178 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2179 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2180 "properly you need an SDP file "
2184 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2185 NULL, 0, s->filename);
2187 snprintf(sdp, sizeof(sdp),
2188 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2189 addr.ss_family == AF_INET ? 4 : 6, host,
2190 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2191 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2192 port, payload_type);
2193 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2195 init_put_byte(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2198 /* sdp_read_header initializes this again */
2201 ret = sdp_read_header(s, ap);
2212 AVInputFormat rtp_demuxer = {
2214 NULL_IF_CONFIG_SMALL("RTP input format"),
2220 .flags = AVFMT_NOFILE,
2222 #endif /* CONFIG_RTP_DEMUXER */