3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/random_seed.h"
30 #include <sys/select.h>
35 #include "os_support.h"
41 #include "rtpdec_formats.h"
44 //#define DEBUG_RTP_TCP
46 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
47 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
50 /* Timeout values for socket select, in ms,
51 * and read_packet(), in seconds */
52 #define SELECT_TIMEOUT_MS 100
53 #define READ_PACKET_TIMEOUT_S 10
54 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
55 #define SDP_MAX_SIZE 16384
56 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
58 static void get_word_until_chars(char *buf, int buf_size,
59 const char *sep, const char **pp)
65 p += strspn(p, SPACE_CHARS);
67 while (!strchr(sep, *p) && *p != '\0') {
68 if ((q - buf) < buf_size - 1)
77 static void get_word_sep(char *buf, int buf_size, const char *sep,
80 if (**pp == '/') (*pp)++;
81 get_word_until_chars(buf, buf_size, sep, pp);
84 static void get_word(char *buf, int buf_size, const char **pp)
86 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
89 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
90 static int sdp_parse_rtpmap(AVFormatContext *s,
91 AVCodecContext *codec, RTSPStream *rtsp_st,
92 int payload_type, const char *p)
99 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
100 * see if we can handle this kind of payload.
101 * The space should normally not be there but some Real streams or
102 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
103 * have a trailing space. */
104 get_word_sep(buf, sizeof(buf), "/ ", &p);
105 if (payload_type >= RTP_PT_PRIVATE) {
106 RTPDynamicProtocolHandler *handler;
107 for (handler = RTPFirstDynamicPayloadHandler;
108 handler; handler = handler->next) {
109 if (!strcasecmp(buf, handler->enc_name) &&
110 codec->codec_type == handler->codec_type) {
111 codec->codec_id = handler->codec_id;
112 rtsp_st->dynamic_handler = handler;
114 rtsp_st->dynamic_protocol_context = handler->open();
118 /* If no dynamic handler was found, check with the list of standard
119 * allocated types, if such a stream for some reason happens to
120 * use a private payload type. This isn't handled in rtpdec.c, since
121 * the format name from the rtpmap line never is passed into rtpdec. */
122 if (!rtsp_st->dynamic_handler)
123 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
125 /* We are in a standard case
126 * (from http://www.iana.org/assignments/rtp-parameters). */
127 /* search into AVRtpPayloadTypes[] */
128 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
131 c = avcodec_find_decoder(codec->codec_id);
137 get_word_sep(buf, sizeof(buf), "/", &p);
139 switch (codec->codec_type) {
140 case AVMEDIA_TYPE_AUDIO:
141 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
142 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
143 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
145 codec->sample_rate = i;
146 get_word_sep(buf, sizeof(buf), "/", &p);
150 // TODO: there is a bug here; if it is a mono stream, and
151 // less than 22000Hz, faad upconverts to stereo and twice
152 // the frequency. No problem, but the sample rate is being
153 // set here by the sdp line. Patch on its way. (rdm)
155 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
157 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
160 case AVMEDIA_TYPE_VIDEO:
161 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
169 /* parse the attribute line from the fmtp a line of an sdp response. This
170 * is broken out as a function because it is used in rtp_h264.c, which is
172 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
173 char *value, int value_size)
175 *p += strspn(*p, SPACE_CHARS);
177 get_word_sep(attr, attr_size, "=", p);
180 get_word_sep(value, value_size, ";", p);
188 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
190 * Used for seeking in the rtp stream.
192 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
196 p += strspn(p, SPACE_CHARS);
197 if (!av_stristart(p, "npt=", &p))
200 *start = AV_NOPTS_VALUE;
201 *end = AV_NOPTS_VALUE;
203 get_word_sep(buf, sizeof(buf), "-", &p);
204 *start = parse_date(buf, 1);
207 get_word_sep(buf, sizeof(buf), "-", &p);
208 *end = parse_date(buf, 1);
210 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
211 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
214 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
216 struct addrinfo hints, *ai = NULL;
217 memset(&hints, 0, sizeof(hints));
218 hints.ai_flags = AI_NUMERICHOST;
219 if (getaddrinfo(buf, NULL, &hints, &ai))
221 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
226 typedef struct SDPParseState {
228 struct sockaddr_storage default_ip;
230 int skip_media; ///< set if an unknown m= line occurs
233 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
234 int letter, const char *buf)
236 RTSPState *rt = s->priv_data;
237 char buf1[64], st_type[64];
239 enum AVMediaType codec_type;
243 struct sockaddr_storage sdp_ip;
246 dprintf(s, "sdp: %c='%s'\n", letter, buf);
249 if (s1->skip_media && letter != 'm')
253 get_word(buf1, sizeof(buf1), &p);
254 if (strcmp(buf1, "IN") != 0)
256 get_word(buf1, sizeof(buf1), &p);
257 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
259 get_word_sep(buf1, sizeof(buf1), "/", &p);
260 if (get_sockaddr(buf1, &sdp_ip))
265 get_word_sep(buf1, sizeof(buf1), "/", &p);
268 if (s->nb_streams == 0) {
269 s1->default_ip = sdp_ip;
270 s1->default_ttl = ttl;
272 st = s->streams[s->nb_streams - 1];
273 rtsp_st = st->priv_data;
274 rtsp_st->sdp_ip = sdp_ip;
275 rtsp_st->sdp_ttl = ttl;
279 av_metadata_set2(&s->metadata, "title", p, 0);
282 if (s->nb_streams == 0) {
283 av_metadata_set2(&s->metadata, "comment", p, 0);
290 get_word(st_type, sizeof(st_type), &p);
291 if (!strcmp(st_type, "audio")) {
292 codec_type = AVMEDIA_TYPE_AUDIO;
293 } else if (!strcmp(st_type, "video")) {
294 codec_type = AVMEDIA_TYPE_VIDEO;
295 } else if (!strcmp(st_type, "application")) {
296 codec_type = AVMEDIA_TYPE_DATA;
301 rtsp_st = av_mallocz(sizeof(RTSPStream));
304 rtsp_st->stream_index = -1;
305 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
307 rtsp_st->sdp_ip = s1->default_ip;
308 rtsp_st->sdp_ttl = s1->default_ttl;
310 get_word(buf1, sizeof(buf1), &p); /* port */
311 rtsp_st->sdp_port = atoi(buf1);
313 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
315 /* XXX: handle list of formats */
316 get_word(buf1, sizeof(buf1), &p); /* format list */
317 rtsp_st->sdp_payload_type = atoi(buf1);
319 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
320 /* no corresponding stream */
322 st = av_new_stream(s, 0);
325 st->priv_data = rtsp_st;
326 rtsp_st->stream_index = st->index;
327 st->codec->codec_type = codec_type;
328 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
329 /* if standard payload type, we can find the codec right now */
330 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
333 /* put a default control url */
334 av_strlcpy(rtsp_st->control_url, rt->control_uri,
335 sizeof(rtsp_st->control_url));
338 if (av_strstart(p, "control:", &p)) {
339 if (s->nb_streams == 0) {
340 if (!strncmp(p, "rtsp://", 7))
341 av_strlcpy(rt->control_uri, p,
342 sizeof(rt->control_uri));
345 /* get the control url */
346 st = s->streams[s->nb_streams - 1];
347 rtsp_st = st->priv_data;
349 /* XXX: may need to add full url resolution */
350 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
352 if (proto[0] == '\0') {
353 /* relative control URL */
354 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
355 av_strlcat(rtsp_st->control_url, "/",
356 sizeof(rtsp_st->control_url));
357 av_strlcat(rtsp_st->control_url, p,
358 sizeof(rtsp_st->control_url));
360 av_strlcpy(rtsp_st->control_url, p,
361 sizeof(rtsp_st->control_url));
363 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
364 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
365 get_word(buf1, sizeof(buf1), &p);
366 payload_type = atoi(buf1);
367 st = s->streams[s->nb_streams - 1];
368 rtsp_st = st->priv_data;
369 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
370 } else if (av_strstart(p, "fmtp:", &p) ||
371 av_strstart(p, "framesize:", &p)) {
372 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
373 // let dynamic protocol handlers have a stab at the line.
374 get_word(buf1, sizeof(buf1), &p);
375 payload_type = atoi(buf1);
376 for (i = 0; i < s->nb_streams; i++) {
378 rtsp_st = st->priv_data;
379 if (rtsp_st->sdp_payload_type == payload_type &&
380 rtsp_st->dynamic_handler &&
381 rtsp_st->dynamic_handler->parse_sdp_a_line)
382 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
383 rtsp_st->dynamic_protocol_context, buf);
385 } else if (av_strstart(p, "range:", &p)) {
388 // this is so that seeking on a streamed file can work.
389 rtsp_parse_range_npt(p, &start, &end);
390 s->start_time = start;
391 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
392 s->duration = (end == AV_NOPTS_VALUE) ?
393 AV_NOPTS_VALUE : end - start;
394 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
396 rt->transport = RTSP_TRANSPORT_RDT;
398 if (rt->server_type == RTSP_SERVER_WMS)
399 ff_wms_parse_sdp_a_line(s, p);
400 if (s->nb_streams > 0) {
401 if (rt->server_type == RTSP_SERVER_REAL)
402 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
404 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
405 if (rtsp_st->dynamic_handler &&
406 rtsp_st->dynamic_handler->parse_sdp_a_line)
407 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
409 rtsp_st->dynamic_protocol_context, buf);
416 static int sdp_parse(AVFormatContext *s, const char *content)
420 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
421 * contain long SDP lines containing complete ASF Headers (several
422 * kB) or arrays of MDPR (RM stream descriptor) headers plus
423 * "rulebooks" describing their properties. Therefore, the SDP line
426 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
427 * in rtpdec_xiph.c. */
429 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
431 memset(s1, 0, sizeof(SDPParseState));
434 p += strspn(p, SPACE_CHARS);
442 /* get the content */
444 while (*p != '\n' && *p != '\r' && *p != '\0') {
445 if ((q - buf) < sizeof(buf) - 1)
450 sdp_parse_line(s, s1, letter, buf);
452 while (*p != '\n' && *p != '\0')
460 /* close and free RTSP streams */
461 void ff_rtsp_close_streams(AVFormatContext *s)
463 RTSPState *rt = s->priv_data;
467 for (i = 0; i < rt->nb_rtsp_streams; i++) {
468 rtsp_st = rt->rtsp_streams[i];
470 if (rtsp_st->transport_priv) {
472 AVFormatContext *rtpctx = rtsp_st->transport_priv;
473 av_write_trailer(rtpctx);
474 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
476 url_close_dyn_buf(rtpctx->pb, &ptr);
479 url_fclose(rtpctx->pb);
481 av_metadata_free(&rtpctx->streams[0]->metadata);
482 av_metadata_free(&rtpctx->metadata);
483 av_free(rtpctx->streams[0]);
485 } else if (rt->transport == RTSP_TRANSPORT_RDT)
486 ff_rdt_parse_close(rtsp_st->transport_priv);
488 rtp_parse_close(rtsp_st->transport_priv);
490 if (rtsp_st->rtp_handle)
491 url_close(rtsp_st->rtp_handle);
492 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
493 rtsp_st->dynamic_handler->close(
494 rtsp_st->dynamic_protocol_context);
497 av_free(rt->rtsp_streams);
499 av_close_input_stream (rt->asf_ctx);
502 av_free(rt->recvbuf);
505 static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
508 RTSPState *rt = s->priv_data;
509 AVFormatContext *rtpctx;
511 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
516 /* Allocate an AVFormatContext for each output stream */
517 rtpctx = avformat_alloc_context();
521 rtpctx->oformat = rtp_format;
522 if (!av_new_stream(rtpctx, 0)) {
526 /* Copy the max delay setting; the rtp muxer reads this. */
527 rtpctx->max_delay = s->max_delay;
528 /* Copy other stream parameters. */
529 rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
531 /* Set the synchronized start time. */
532 rtpctx->start_time_realtime = rt->start_time;
534 /* Remove the local codec, link to the original codec
535 * context instead, to give the rtp muxer access to
536 * codec parameters. */
537 av_free(rtpctx->streams[0]->codec);
538 rtpctx->streams[0]->codec = st->codec;
541 url_fdopen(&rtpctx->pb, handle);
543 url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
544 ret = av_write_header(rtpctx);
548 url_fclose(rtpctx->pb);
551 url_close_dyn_buf(rtpctx->pb, &ptr);
554 av_free(rtpctx->streams[0]);
559 /* Copy the RTP AVStream timebase back to the original AVStream */
560 st->time_base = rtpctx->streams[0]->time_base;
564 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
566 RTSPState *rt = s->priv_data;
569 /* open the RTP context */
570 if (rtsp_st->stream_index >= 0)
571 st = s->streams[rtsp_st->stream_index];
573 s->ctx_flags |= AVFMTCTX_NOHEADER;
576 rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
577 /* Ownership of rtp_handle is passed to the rtp mux context */
578 rtsp_st->rtp_handle = NULL;
579 } else if (rt->transport == RTSP_TRANSPORT_RDT)
580 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
581 rtsp_st->dynamic_protocol_context,
582 rtsp_st->dynamic_handler);
584 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
585 rtsp_st->sdp_payload_type);
587 if (!rtsp_st->transport_priv) {
588 return AVERROR(ENOMEM);
589 } else if (rt->transport != RTSP_TRANSPORT_RDT) {
590 if (rtsp_st->dynamic_handler) {
591 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
592 rtsp_st->dynamic_protocol_context,
593 rtsp_st->dynamic_handler);
600 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
601 static int rtsp_probe(AVProbeData *p)
603 if (av_strstart(p->filename, "rtsp:", NULL))
604 return AVPROBE_SCORE_MAX;
608 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
614 p += strspn(p, SPACE_CHARS);
615 v = strtol(p, (char **)&p, 10);
619 v = strtol(p, (char **)&p, 10);
628 /* XXX: only one transport specification is parsed */
629 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
631 char transport_protocol[16];
633 char lower_transport[16];
635 RTSPTransportField *th;
638 reply->nb_transports = 0;
641 p += strspn(p, SPACE_CHARS);
645 th = &reply->transports[reply->nb_transports];
647 get_word_sep(transport_protocol, sizeof(transport_protocol),
649 if (!strcasecmp (transport_protocol, "rtp")) {
650 get_word_sep(profile, sizeof(profile), "/;,", &p);
651 lower_transport[0] = '\0';
652 /* rtp/avp/<protocol> */
654 get_word_sep(lower_transport, sizeof(lower_transport),
657 th->transport = RTSP_TRANSPORT_RTP;
658 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
659 !strcasecmp (transport_protocol, "x-real-rdt")) {
660 /* x-pn-tng/<protocol> */
661 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
663 th->transport = RTSP_TRANSPORT_RDT;
665 if (!strcasecmp(lower_transport, "TCP"))
666 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
668 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
672 /* get each parameter */
673 while (*p != '\0' && *p != ',') {
674 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
675 if (!strcmp(parameter, "port")) {
678 rtsp_parse_range(&th->port_min, &th->port_max, &p);
680 } else if (!strcmp(parameter, "client_port")) {
683 rtsp_parse_range(&th->client_port_min,
684 &th->client_port_max, &p);
686 } else if (!strcmp(parameter, "server_port")) {
689 rtsp_parse_range(&th->server_port_min,
690 &th->server_port_max, &p);
692 } else if (!strcmp(parameter, "interleaved")) {
695 rtsp_parse_range(&th->interleaved_min,
696 &th->interleaved_max, &p);
698 } else if (!strcmp(parameter, "multicast")) {
699 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
700 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
701 } else if (!strcmp(parameter, "ttl")) {
704 th->ttl = strtol(p, (char **)&p, 10);
706 } else if (!strcmp(parameter, "destination")) {
709 get_word_sep(buf, sizeof(buf), ";,", &p);
710 get_sockaddr(buf, &th->destination);
712 } else if (!strcmp(parameter, "source")) {
715 get_word_sep(buf, sizeof(buf), ";,", &p);
716 av_strlcpy(th->source, buf, sizeof(th->source));
720 while (*p != ';' && *p != '\0' && *p != ',')
728 reply->nb_transports++;
732 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
733 HTTPAuthState *auth_state)
737 /* NOTE: we do case independent match for broken servers */
739 if (av_stristart(p, "Session:", &p)) {
741 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
742 if (av_stristart(p, ";timeout=", &p) &&
743 (t = strtol(p, NULL, 10)) > 0) {
746 } else if (av_stristart(p, "Content-Length:", &p)) {
747 reply->content_length = strtol(p, NULL, 10);
748 } else if (av_stristart(p, "Transport:", &p)) {
749 rtsp_parse_transport(reply, p);
750 } else if (av_stristart(p, "CSeq:", &p)) {
751 reply->seq = strtol(p, NULL, 10);
752 } else if (av_stristart(p, "Range:", &p)) {
753 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
754 } else if (av_stristart(p, "RealChallenge1:", &p)) {
755 p += strspn(p, SPACE_CHARS);
756 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
757 } else if (av_stristart(p, "Server:", &p)) {
758 p += strspn(p, SPACE_CHARS);
759 av_strlcpy(reply->server, p, sizeof(reply->server));
760 } else if (av_stristart(p, "Notice:", &p) ||
761 av_stristart(p, "X-Notice:", &p)) {
762 reply->notice = strtol(p, NULL, 10);
763 } else if (av_stristart(p, "Location:", &p)) {
764 p += strspn(p, SPACE_CHARS);
765 av_strlcpy(reply->location, p , sizeof(reply->location));
766 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
767 p += strspn(p, SPACE_CHARS);
768 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
769 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
770 p += strspn(p, SPACE_CHARS);
771 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
775 /* skip a RTP/TCP interleaved packet */
776 void ff_rtsp_skip_packet(AVFormatContext *s)
778 RTSPState *rt = s->priv_data;
782 ret = url_read_complete(rt->rtsp_hd, buf, 3);
785 len = AV_RB16(buf + 1);
787 dprintf(s, "skipping RTP packet len=%d\n", len);
792 if (len1 > sizeof(buf))
794 ret = url_read_complete(rt->rtsp_hd, buf, len1);
801 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
802 unsigned char **content_ptr,
803 int return_on_interleaved_data)
805 RTSPState *rt = s->priv_data;
806 char buf[4096], buf1[1024], *q;
809 int ret, content_length, line_count = 0;
810 unsigned char *content = NULL;
812 memset(reply, 0, sizeof(*reply));
814 /* parse reply (XXX: use buffers) */
815 rt->last_reply[0] = '\0';
819 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
821 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
828 /* XXX: only parse it if first char on line ? */
829 if (return_on_interleaved_data) {
832 ff_rtsp_skip_packet(s);
833 } else if (ch != '\r') {
834 if ((q - buf) < sizeof(buf) - 1)
840 dprintf(s, "line='%s'\n", buf);
842 /* test if last line */
846 if (line_count == 0) {
848 get_word(buf1, sizeof(buf1), &p);
849 get_word(buf1, sizeof(buf1), &p);
850 reply->status_code = atoi(buf1);
851 av_strlcpy(reply->reason, p, sizeof(reply->reason));
853 ff_rtsp_parse_line(reply, p, &rt->auth_state);
854 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
855 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
860 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
861 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
863 content_length = reply->content_length;
864 if (content_length > 0) {
865 /* leave some room for a trailing '\0' (useful for simple parsing) */
866 content = av_malloc(content_length + 1);
867 (void)url_read_complete(rt->rtsp_hd, content, content_length);
868 content[content_length] = '\0';
871 *content_ptr = content;
875 if (rt->seq != reply->seq) {
876 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
877 rt->seq, reply->seq);
881 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
882 reply->notice == 2104 /* Start-of-Stream Reached */ ||
883 reply->notice == 2306 /* Continuous Feed Terminated */) {
884 rt->state = RTSP_STATE_IDLE;
885 } else if (reply->notice >= 4400 && reply->notice < 5500) {
886 return AVERROR(EIO); /* data or server error */
887 } else if (reply->notice == 2401 /* Ticket Expired */ ||
888 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
889 return AVERROR(EPERM);
894 int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
895 const char *method, const char *url,
897 const unsigned char *send_content,
898 int send_content_length)
900 RTSPState *rt = s->priv_data;
901 char buf[4096], *out_buf;
902 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
904 /* Add in RTSP headers */
907 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
909 av_strlcat(buf, headers, sizeof(buf));
910 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
911 if (rt->session_id[0] != '\0' && (!headers ||
912 !strstr(headers, "\nIf-Match:"))) {
913 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
916 char *str = ff_http_auth_create_response(&rt->auth_state,
917 rt->auth, url, method);
919 av_strlcat(buf, str, sizeof(buf));
922 if (send_content_length > 0 && send_content)
923 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
924 av_strlcat(buf, "\r\n", sizeof(buf));
926 /* base64 encode rtsp if tunneling */
927 if (rt->control_transport == RTSP_MODE_TUNNEL) {
928 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
932 dprintf(s, "Sending:\n%s--\n", buf);
934 url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
935 if (send_content_length > 0 && send_content) {
936 if (rt->control_transport == RTSP_MODE_TUNNEL) {
937 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
938 "with content data not supported\n");
939 return AVERROR_PATCHWELCOME;
941 url_write(rt->rtsp_hd_out, send_content, send_content_length);
943 rt->last_cmd_time = av_gettime();
948 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
949 const char *url, const char *headers)
951 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
954 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
955 const char *headers, RTSPMessageHeader *reply,
956 unsigned char **content_ptr)
958 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
959 content_ptr, NULL, 0);
962 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
963 const char *method, const char *url,
965 RTSPMessageHeader *reply,
966 unsigned char **content_ptr,
967 const unsigned char *send_content,
968 int send_content_length)
970 RTSPState *rt = s->priv_data;
971 HTTPAuthType cur_auth_type;
975 cur_auth_type = rt->auth_state.auth_type;
976 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
978 send_content_length)))
981 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
984 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
985 rt->auth_state.auth_type != HTTP_AUTH_NONE)
988 if (reply->status_code > 400){
989 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
993 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1000 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
1002 static int make_setup_request(AVFormatContext *s, const char *host, int port,
1003 int lower_transport, const char *real_challenge)
1005 RTSPState *rt = s->priv_data;
1006 int rtx, j, i, err, interleave = 0;
1007 RTSPStream *rtsp_st;
1008 RTSPMessageHeader reply1, *reply = &reply1;
1010 const char *trans_pref;
1012 if (rt->transport == RTSP_TRANSPORT_RDT)
1013 trans_pref = "x-pn-tng";
1015 trans_pref = "RTP/AVP";
1017 /* default timeout: 1 minute */
1020 /* for each stream, make the setup request */
1021 /* XXX: we assume the same server is used for the control of each
1024 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1025 char transport[2048];
1028 * WMS serves all UDP data over a single connection, the RTX, which
1029 * isn't necessarily the first in the SDP but has to be the first
1030 * to be set up, else the second/third SETUP will fail with a 461.
1032 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1033 rt->server_type == RTSP_SERVER_WMS) {
1036 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1037 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1039 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1043 if (rtx == rt->nb_rtsp_streams)
1044 return -1; /* no RTX found */
1045 rtsp_st = rt->rtsp_streams[rtx];
1047 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1049 rtsp_st = rt->rtsp_streams[i];
1052 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1055 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1056 port = reply->transports[0].client_port_min;
1060 /* first try in specified port range */
1061 if (RTSP_RTP_PORT_MIN != 0) {
1062 while (j <= RTSP_RTP_PORT_MAX) {
1063 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1064 "?localport=%d", j);
1065 /* we will use two ports per rtp stream (rtp and rtcp) */
1067 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1073 /* then try on any port */
1074 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1075 err = AVERROR_INVALIDDATA;
1081 port = rtp_get_local_port(rtsp_st->rtp_handle);
1083 snprintf(transport, sizeof(transport) - 1,
1084 "%s/UDP;", trans_pref);
1085 if (rt->server_type != RTSP_SERVER_REAL)
1086 av_strlcat(transport, "unicast;", sizeof(transport));
1087 av_strlcatf(transport, sizeof(transport),
1088 "client_port=%d", port);
1089 if (rt->transport == RTSP_TRANSPORT_RTP &&
1090 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1091 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1095 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1096 /** For WMS streams, the application streams are only used for
1097 * UDP. When trying to set it up for TCP streams, the server
1098 * will return an error. Therefore, we skip those streams. */
1099 if (rt->server_type == RTSP_SERVER_WMS &&
1100 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1103 snprintf(transport, sizeof(transport) - 1,
1104 "%s/TCP;", trans_pref);
1105 if (rt->server_type == RTSP_SERVER_WMS)
1106 av_strlcat(transport, "unicast;", sizeof(transport));
1107 av_strlcatf(transport, sizeof(transport),
1108 "interleaved=%d-%d",
1109 interleave, interleave + 1);
1113 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1114 snprintf(transport, sizeof(transport) - 1,
1115 "%s/UDP;multicast", trans_pref);
1118 av_strlcat(transport, ";mode=receive", sizeof(transport));
1119 } else if (rt->server_type == RTSP_SERVER_REAL ||
1120 rt->server_type == RTSP_SERVER_WMS)
1121 av_strlcat(transport, ";mode=play", sizeof(transport));
1122 snprintf(cmd, sizeof(cmd),
1123 "Transport: %s\r\n",
1125 if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1126 char real_res[41], real_csum[9];
1127 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1129 av_strlcatf(cmd, sizeof(cmd),
1131 "RealChallenge2: %s, sd=%s\r\n",
1132 rt->session_id, real_res, real_csum);
1134 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1135 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1138 } else if (reply->status_code != RTSP_STATUS_OK ||
1139 reply->nb_transports != 1) {
1140 err = AVERROR_INVALIDDATA;
1144 /* XXX: same protocol for all streams is required */
1146 if (reply->transports[0].lower_transport != rt->lower_transport ||
1147 reply->transports[0].transport != rt->transport) {
1148 err = AVERROR_INVALIDDATA;
1152 rt->lower_transport = reply->transports[0].lower_transport;
1153 rt->transport = reply->transports[0].transport;
1156 /* close RTP connection if not chosen */
1157 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1158 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1159 url_close(rtsp_st->rtp_handle);
1160 rtsp_st->rtp_handle = NULL;
1163 switch(reply->transports[0].lower_transport) {
1164 case RTSP_LOWER_TRANSPORT_TCP:
1165 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1166 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1169 case RTSP_LOWER_TRANSPORT_UDP: {
1172 /* Use source address if specified */
1173 if (reply->transports[0].source[0]) {
1174 ff_url_join(url, sizeof(url), "rtp", NULL,
1175 reply->transports[0].source,
1176 reply->transports[0].server_port_min, NULL);
1178 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1179 reply->transports[0].server_port_min, NULL);
1181 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1182 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1183 err = AVERROR_INVALIDDATA;
1186 /* Try to initialize the connection state in a
1187 * potential NAT router by sending dummy packets.
1188 * RTP/RTCP dummy packets are used for RDT, too.
1190 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1191 rtp_send_punch_packets(rtsp_st->rtp_handle);
1194 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1195 char url[1024], namebuf[50];
1196 struct sockaddr_storage addr;
1199 if (reply->transports[0].destination.ss_family) {
1200 addr = reply->transports[0].destination;
1201 port = reply->transports[0].port_min;
1202 ttl = reply->transports[0].ttl;
1204 addr = rtsp_st->sdp_ip;
1205 port = rtsp_st->sdp_port;
1206 ttl = rtsp_st->sdp_ttl;
1208 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1209 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1210 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1211 port, "?ttl=%d", ttl);
1212 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1213 err = AVERROR_INVALIDDATA;
1220 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1224 if (reply->timeout > 0)
1225 rt->timeout = reply->timeout;
1227 if (rt->server_type == RTSP_SERVER_REAL)
1228 rt->need_subscription = 1;
1233 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1234 if (rt->rtsp_streams[i]->rtp_handle) {
1235 url_close(rt->rtsp_streams[i]->rtp_handle);
1236 rt->rtsp_streams[i]->rtp_handle = NULL;
1242 static int rtsp_read_play(AVFormatContext *s)
1244 RTSPState *rt = s->priv_data;
1245 RTSPMessageHeader reply1, *reply = &reply1;
1249 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1252 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1253 if (rt->state == RTSP_STATE_PAUSED) {
1256 snprintf(cmd, sizeof(cmd),
1257 "Range: npt=%0.3f-\r\n",
1258 (double)rt->seek_timestamp / AV_TIME_BASE);
1260 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1261 if (reply->status_code != RTSP_STATUS_OK) {
1264 if (reply->range_start != AV_NOPTS_VALUE &&
1265 rt->transport == RTSP_TRANSPORT_RTP) {
1266 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1267 RTSPStream *rtsp_st = rt->rtsp_streams[i];
1268 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1269 AVStream *st = NULL;
1272 if (rtsp_st->stream_index >= 0)
1273 st = s->streams[rtsp_st->stream_index];
1274 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
1275 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1277 rtpctx->range_start_offset = av_rescale_q(reply->range_start,
1283 rt->state = RTSP_STATE_STREAMING;
1287 static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1289 RTSPState *rt = s->priv_data;
1291 unsigned char *content = NULL;
1294 /* describe the stream */
1295 snprintf(cmd, sizeof(cmd),
1296 "Accept: application/sdp\r\n");
1297 if (rt->server_type == RTSP_SERVER_REAL) {
1299 * The Require: attribute is needed for proper streaming from
1300 * Realmedia servers.
1303 "Require: com.real.retain-entity-for-setup\r\n",
1306 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1308 return AVERROR_INVALIDDATA;
1309 if (reply->status_code != RTSP_STATUS_OK) {
1311 return AVERROR_INVALIDDATA;
1314 /* now we got the SDP description, we parse it */
1315 ret = sdp_parse(s, (const char *)content);
1318 return AVERROR_INVALIDDATA;
1323 static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1325 RTSPState *rt = s->priv_data;
1326 RTSPMessageHeader reply1, *reply = &reply1;
1329 AVFormatContext sdp_ctx, *ctx_array[1];
1331 rt->start_time = av_gettime();
1333 /* Announce the stream */
1334 sdp = av_mallocz(SDP_MAX_SIZE);
1336 return AVERROR(ENOMEM);
1337 /* We create the SDP based on the RTSP AVFormatContext where we
1338 * aren't allowed to change the filename field. (We create the SDP
1339 * based on the RTSP context since the contexts for the RTP streams
1340 * don't exist yet.) In order to specify a custom URL with the actual
1341 * peer IP instead of the originally specified hostname, we create
1342 * a temporary copy of the AVFormatContext, where the custom URL is set.
1344 * FIXME: Create the SDP without copying the AVFormatContext.
1345 * This either requires setting up the RTP stream AVFormatContexts
1346 * already here (complicating things immensely) or getting a more
1347 * flexible SDP creation interface.
1350 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1351 "rtsp", NULL, addr, -1, NULL);
1352 ctx_array[0] = &sdp_ctx;
1353 if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
1355 return AVERROR_INVALIDDATA;
1357 av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
1358 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1359 "Content-Type: application/sdp\r\n",
1360 reply, NULL, sdp, strlen(sdp));
1362 if (reply->status_code != RTSP_STATUS_OK)
1363 return AVERROR_INVALIDDATA;
1365 /* Set up the RTSPStreams for each AVStream */
1366 for (i = 0; i < s->nb_streams; i++) {
1367 RTSPStream *rtsp_st;
1368 AVStream *st = s->streams[i];
1370 rtsp_st = av_mallocz(sizeof(RTSPStream));
1372 return AVERROR(ENOMEM);
1373 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1375 st->priv_data = rtsp_st;
1376 rtsp_st->stream_index = i;
1378 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1379 /* Note, this must match the relative uri set in the sdp content */
1380 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1387 void ff_rtsp_close_connections(AVFormatContext *s)
1389 RTSPState *rt = s->priv_data;
1390 if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1391 url_close(rt->rtsp_hd);
1392 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1395 int ff_rtsp_connect(AVFormatContext *s)
1397 RTSPState *rt = s->priv_data;
1398 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1399 char *option_list, *option, *filename;
1400 int port, err, tcp_fd;
1401 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1402 int lower_transport_mask = 0;
1403 char real_challenge[64];
1404 struct sockaddr_storage peer;
1405 socklen_t peer_len = sizeof(peer);
1407 if (!ff_network_init())
1408 return AVERROR(EIO);
1410 rt->control_transport = RTSP_MODE_PLAIN;
1411 /* extract hostname and port */
1412 av_url_split(NULL, 0, auth, sizeof(auth),
1413 host, sizeof(host), &port, path, sizeof(path), s->filename);
1415 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1418 port = RTSP_DEFAULT_PORT;
1420 /* search for options */
1421 option_list = strrchr(path, '?');
1423 /* Strip out the RTSP specific options, write out the rest of
1424 * the options back into the same string. */
1425 filename = option_list;
1426 while (option_list) {
1427 /* move the option pointer */
1428 option = ++option_list;
1429 option_list = strchr(option_list, '&');
1433 /* handle the options */
1434 if (!strcmp(option, "udp")) {
1435 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1436 } else if (!strcmp(option, "multicast")) {
1437 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1438 } else if (!strcmp(option, "tcp")) {
1439 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1440 } else if(!strcmp(option, "http")) {
1441 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1442 rt->control_transport = RTSP_MODE_TUNNEL;
1444 /* Write options back into the buffer, using memmove instead
1445 * of strcpy since the strings may overlap. */
1446 int len = strlen(option);
1447 memmove(++filename, option, len);
1449 if (option_list) *filename = '&';
1455 if (!lower_transport_mask)
1456 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1459 /* Only UDP or TCP - UDP multicast isn't supported. */
1460 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1461 (1 << RTSP_LOWER_TRANSPORT_TCP);
1462 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1463 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1464 "only UDP and TCP are supported for output.\n");
1465 err = AVERROR(EINVAL);
1470 /* Construct the URI used in request; this is similar to s->filename,
1471 * but with authentication credentials removed and RTSP specific options
1473 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1474 host, port, "%s", path);
1476 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1477 /* set up initial handshake for tunneling */
1478 char httpname[1024];
1479 char sessioncookie[17];
1482 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1483 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1484 av_get_random_seed(), av_get_random_seed());
1487 if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
1492 /* generate GET headers */
1493 snprintf(headers, sizeof(headers),
1494 "x-sessioncookie: %s\r\n"
1495 "Accept: application/x-rtsp-tunnelled\r\n"
1496 "Pragma: no-cache\r\n"
1497 "Cache-Control: no-cache\r\n",
1499 ff_http_set_headers(rt->rtsp_hd, headers);
1501 /* complete the connection */
1502 if (url_connect(rt->rtsp_hd)) {
1508 if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1513 /* generate POST headers */
1514 snprintf(headers, sizeof(headers),
1515 "x-sessioncookie: %s\r\n"
1516 "Content-Type: application/x-rtsp-tunnelled\r\n"
1517 "Pragma: no-cache\r\n"
1518 "Cache-Control: no-cache\r\n"
1519 "Content-Length: 32767\r\n"
1520 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1522 ff_http_set_headers(rt->rtsp_hd_out, headers);
1523 ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1525 /* Initialize the authentication state for the POST session. The HTTP
1526 * protocol implementation doesn't properly handle multi-pass
1527 * authentication for POST requests, since it would require one of
1529 * - implementing Expect: 100-continue, which many HTTP servers
1530 * don't support anyway, even less the RTSP servers that do HTTP
1532 * - sending the whole POST data until getting a 401 reply specifying
1533 * what authentication method to use, then resending all that data
1534 * - waiting for potential 401 replies directly after sending the
1535 * POST header (waiting for some unspecified time)
1536 * Therefore, we copy the full auth state, which works for both basic
1537 * and digest. (For digest, we would have to synchronize the nonce
1538 * count variable between the two sessions, if we'd do more requests
1539 * with the original session, though.)
1541 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1543 /* complete the connection */
1544 if (url_connect(rt->rtsp_hd_out)) {
1549 /* open the tcp connection */
1550 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1551 if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
1555 rt->rtsp_hd_out = rt->rtsp_hd;
1559 tcp_fd = url_get_file_handle(rt->rtsp_hd);
1560 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1561 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1562 NULL, 0, NI_NUMERICHOST);
1565 /* request options supported by the server; this also detects server
1567 for (rt->server_type = RTSP_SERVER_RTP;;) {
1569 if (rt->server_type == RTSP_SERVER_REAL)
1572 * The following entries are required for proper
1573 * streaming from a Realmedia server. They are
1574 * interdependent in some way although we currently
1575 * don't quite understand how. Values were copied
1576 * from mplayer SVN r23589.
1577 * @param CompanyID is a 16-byte ID in base64
1578 * @param ClientChallenge is a 16-byte ID in hex
1580 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1581 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1582 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1583 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1585 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1586 if (reply->status_code != RTSP_STATUS_OK) {
1587 err = AVERROR_INVALIDDATA;
1591 /* detect server type if not standard-compliant RTP */
1592 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1593 rt->server_type = RTSP_SERVER_REAL;
1595 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1596 rt->server_type = RTSP_SERVER_WMS;
1597 } else if (rt->server_type == RTSP_SERVER_REAL)
1598 strcpy(real_challenge, reply->real_challenge);
1603 err = rtsp_setup_input_streams(s, reply);
1605 err = rtsp_setup_output_streams(s, host);
1610 int lower_transport = ff_log2_tab[lower_transport_mask &
1611 ~(lower_transport_mask - 1)];
1613 err = make_setup_request(s, host, port, lower_transport,
1614 rt->server_type == RTSP_SERVER_REAL ?
1615 real_challenge : NULL);
1618 lower_transport_mask &= ~(1 << lower_transport);
1619 if (lower_transport_mask == 0 && err == 1) {
1620 err = FF_NETERROR(EPROTONOSUPPORT);
1625 rt->state = RTSP_STATE_IDLE;
1626 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1629 ff_rtsp_close_streams(s);
1630 ff_rtsp_close_connections(s);
1631 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1632 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1633 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1643 #if CONFIG_RTSP_DEMUXER
1644 static int rtsp_read_header(AVFormatContext *s,
1645 AVFormatParameters *ap)
1647 RTSPState *rt = s->priv_data;
1650 ret = ff_rtsp_connect(s);
1654 rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
1655 if (!rt->real_setup_cache)
1656 return AVERROR(ENOMEM);
1657 rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
1659 if (ap->initial_pause) {
1660 /* do not start immediately */
1662 if (rtsp_read_play(s) < 0) {
1663 ff_rtsp_close_streams(s);
1664 ff_rtsp_close_connections(s);
1665 return AVERROR_INVALIDDATA;
1672 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1673 uint8_t *buf, int buf_size)
1675 RTSPState *rt = s->priv_data;
1676 RTSPStream *rtsp_st;
1678 int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1682 if (url_interrupt_cb())
1683 return AVERROR(EINTR);
1686 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1687 FD_SET(tcp_fd, &rfds);
1692 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1693 rtsp_st = rt->rtsp_streams[i];
1694 if (rtsp_st->rtp_handle) {
1695 fd = url_get_file_handle(rtsp_st->rtp_handle);
1696 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1697 if (FFMAX(fd, fd_rtcp) > fd_max)
1698 fd_max = FFMAX(fd, fd_rtcp);
1700 FD_SET(fd_rtcp, &rfds);
1704 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1705 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1708 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1709 rtsp_st = rt->rtsp_streams[i];
1710 if (rtsp_st->rtp_handle) {
1711 fd = url_get_file_handle(rtsp_st->rtp_handle);
1712 fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1713 if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
1714 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1716 *prtsp_st = rtsp_st;
1722 #if CONFIG_RTSP_DEMUXER
1723 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1724 RTSPMessageHeader reply;
1726 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1729 /* XXX: parse message */
1730 if (rt->state != RTSP_STATE_STREAMING)
1734 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1735 return FF_NETERROR(ETIMEDOUT);
1736 } else if (n < 0 && errno != EINTR)
1737 return AVERROR(errno);
1741 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1742 uint8_t *buf, int buf_size)
1744 RTSPState *rt = s->priv_data;
1745 int id, len, i, ret;
1746 RTSPStream *rtsp_st;
1748 #ifdef DEBUG_RTP_TCP
1749 dprintf(s, "tcp_read_packet:\n");
1753 RTSPMessageHeader reply;
1755 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1758 if (ret == 1) /* received '$' */
1760 /* XXX: parse message */
1761 if (rt->state != RTSP_STATE_STREAMING)
1764 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1768 len = AV_RB16(buf + 1);
1769 #ifdef DEBUG_RTP_TCP
1770 dprintf(s, "id=%d len=%d\n", id, len);
1772 if (len > buf_size || len < 12)
1775 ret = url_read_complete(rt->rtsp_hd, buf, len);
1778 if (rt->transport == RTSP_TRANSPORT_RDT &&
1779 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1782 /* find the matching stream */
1783 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1784 rtsp_st = rt->rtsp_streams[i];
1785 if (id >= rtsp_st->interleaved_min &&
1786 id <= rtsp_st->interleaved_max)
1791 *prtsp_st = rtsp_st;
1795 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1797 RTSPState *rt = s->priv_data;
1799 RTSPStream *rtsp_st;
1801 if (rt->nb_byes == rt->nb_rtsp_streams)
1804 /* get next frames from the same RTP packet */
1805 if (rt->cur_transport_priv) {
1806 if (rt->transport == RTSP_TRANSPORT_RDT) {
1807 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1809 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1811 rt->cur_transport_priv = NULL;
1813 } else if (ret == 1) {
1816 rt->cur_transport_priv = NULL;
1819 /* read next RTP packet */
1822 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1824 return AVERROR(ENOMEM);
1827 switch(rt->lower_transport) {
1829 #if CONFIG_RTSP_DEMUXER
1830 case RTSP_LOWER_TRANSPORT_TCP:
1831 len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1834 case RTSP_LOWER_TRANSPORT_UDP:
1835 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1836 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1837 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1838 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1845 if (rt->transport == RTSP_TRANSPORT_RDT) {
1846 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, rt->recvbuf, len);
1848 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, rt->recvbuf, len);
1850 /* Either bad packet, or a RTCP packet. Check if the
1851 * first_rtcp_ntp_time field was initialized. */
1852 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1853 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1854 /* first_rtcp_ntp_time has been initialized for this stream,
1855 * copy the same value to all other uninitialized streams,
1856 * in order to map their timestamp origin to the same ntp time
1859 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1860 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1862 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1863 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1866 if (ret == -RTCP_BYE) {
1869 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1870 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1872 if (rt->nb_byes == rt->nb_rtsp_streams)
1880 /* more packets may follow, so we save the RTP context */
1881 rt->cur_transport_priv = rtsp_st->transport_priv;
1886 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1888 RTSPState *rt = s->priv_data;
1890 RTSPMessageHeader reply1, *reply = &reply1;
1893 if (rt->server_type == RTSP_SERVER_REAL) {
1896 for (i = 0; i < s->nb_streams; i++)
1897 rt->real_setup[i] = s->streams[i]->discard;
1899 if (!rt->need_subscription) {
1900 if (memcmp (rt->real_setup, rt->real_setup_cache,
1901 sizeof(enum AVDiscard) * s->nb_streams)) {
1902 snprintf(cmd, sizeof(cmd),
1903 "Unsubscribe: %s\r\n",
1904 rt->last_subscription);
1905 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1907 if (reply->status_code != RTSP_STATUS_OK)
1908 return AVERROR_INVALIDDATA;
1909 rt->need_subscription = 1;
1913 if (rt->need_subscription) {
1914 int r, rule_nr, first = 1;
1916 memcpy(rt->real_setup_cache, rt->real_setup,
1917 sizeof(enum AVDiscard) * s->nb_streams);
1918 rt->last_subscription[0] = 0;
1920 snprintf(cmd, sizeof(cmd),
1922 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1924 for (r = 0; r < s->nb_streams; r++) {
1925 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1926 if (s->streams[r]->discard != AVDISCARD_ALL) {
1928 av_strlcat(rt->last_subscription, ",",
1929 sizeof(rt->last_subscription));
1930 ff_rdt_subscribe_rule(
1931 rt->last_subscription,
1932 sizeof(rt->last_subscription), i, rule_nr);
1939 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1940 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1942 if (reply->status_code != RTSP_STATUS_OK)
1943 return AVERROR_INVALIDDATA;
1944 rt->need_subscription = 0;
1946 if (rt->state == RTSP_STATE_STREAMING)
1951 ret = rtsp_fetch_packet(s, pkt);
1955 /* send dummy request to keep TCP connection alive */
1956 if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1957 if (rt->server_type == RTSP_SERVER_WMS) {
1958 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1960 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1967 /* pause the stream */
1968 static int rtsp_read_pause(AVFormatContext *s)
1970 RTSPState *rt = s->priv_data;
1971 RTSPMessageHeader reply1, *reply = &reply1;
1973 if (rt->state != RTSP_STATE_STREAMING)
1975 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1976 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1977 if (reply->status_code != RTSP_STATUS_OK) {
1981 rt->state = RTSP_STATE_PAUSED;
1985 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1986 int64_t timestamp, int flags)
1988 RTSPState *rt = s->priv_data;
1990 rt->seek_timestamp = av_rescale_q(timestamp,
1991 s->streams[stream_index]->time_base,
1995 case RTSP_STATE_IDLE:
1997 case RTSP_STATE_STREAMING:
1998 if (rtsp_read_pause(s) != 0)
2000 rt->state = RTSP_STATE_SEEKING;
2001 if (rtsp_read_play(s) != 0)
2004 case RTSP_STATE_PAUSED:
2005 rt->state = RTSP_STATE_IDLE;
2011 static int rtsp_read_close(AVFormatContext *s)
2013 RTSPState *rt = s->priv_data;
2016 /* NOTE: it is valid to flush the buffer here */
2017 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
2018 url_fclose(&rt->rtsp_gb);
2021 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
2023 ff_rtsp_close_streams(s);
2024 ff_rtsp_close_connections(s);
2026 rt->real_setup = NULL;
2027 av_freep(&rt->real_setup_cache);
2031 AVInputFormat rtsp_demuxer = {
2033 NULL_IF_CONFIG_SMALL("RTSP input format"),
2040 .flags = AVFMT_NOFILE,
2041 .read_play = rtsp_read_play,
2042 .read_pause = rtsp_read_pause,
2046 static int sdp_probe(AVProbeData *p1)
2048 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2050 /* we look for a line beginning "c=IN IP" */
2051 while (p < p_end && *p != '\0') {
2052 if (p + sizeof("c=IN IP") - 1 < p_end &&
2053 av_strstart(p, "c=IN IP", NULL))
2054 return AVPROBE_SCORE_MAX / 2;
2056 while (p < p_end - 1 && *p != '\n') p++;
2065 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2067 RTSPState *rt = s->priv_data;
2068 RTSPStream *rtsp_st;
2073 if (!ff_network_init())
2074 return AVERROR(EIO);
2076 /* read the whole sdp file */
2077 /* XXX: better loading */
2078 content = av_malloc(SDP_MAX_SIZE);
2079 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2082 return AVERROR_INVALIDDATA;
2084 content[size] ='\0';
2086 sdp_parse(s, content);
2089 /* open each RTP stream */
2090 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2092 rtsp_st = rt->rtsp_streams[i];
2094 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2095 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2096 ff_url_join(url, sizeof(url), "rtp", NULL,
2097 namebuf, rtsp_st->sdp_port,
2098 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2100 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2101 err = AVERROR_INVALIDDATA;
2104 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2109 ff_rtsp_close_streams(s);
2114 static int sdp_read_close(AVFormatContext *s)
2116 ff_rtsp_close_streams(s);
2121 AVInputFormat sdp_demuxer = {
2123 NULL_IF_CONFIG_SMALL("SDP"),