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