Add dynamic payload handlers to rdt.c. These follow the same API as the ones
[libav.git] / libavformat / rtsp.c
CommitLineData
1617ad97 1/*
93ced3e8 2 * RTSP/SDP client
1617ad97
FB
3 * Copyright (c) 2002 Fabrice Bellard.
4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
1617ad97
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
1617ad97 11 *
b78e7197 12 * FFmpeg is distributed in the hope that it will be useful,
1617ad97
FB
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
b78e7197 18 * License along with FFmpeg; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1617ad97 20 */
245976da 21
7246177d
AJ
22/* needed by inet_aton() */
23#define _SVID_SOURCE
24
245976da 25#include "libavutil/avstring.h"
1617ad97
FB
26#include "avformat.h"
27
db0ed93e 28#include <sys/time.h>
438fcb75 29#include <unistd.h> /* for select() prototype */
ea452b54 30#include <strings.h>
42572ef5 31#include "network.h"
c971ff19 32#include "rtsp.h"
1617ad97 33
4934884a 34#include "rtp_internal.h"
e9dea59f 35#include "rdt.h"
4934884a 36
1617ad97 37//#define DEBUG
b6892136 38//#define DEBUG_RTP_TCP
1617ad97 39
ff762d6e
FB
40enum RTSPClientState {
41 RTSP_STATE_IDLE,
42 RTSP_STATE_PLAYING,
43 RTSP_STATE_PAUSED,
44};
45
e0776043
RB
46enum RTSPServerType {
47 RTSP_SERVER_RTP, /*< Standard-compliant RTP-server */
48 RTSP_SERVER_RDT, /*< Realmedia-style server */
49 RTSP_SERVER_LAST
50};
51
1617ad97
FB
52typedef struct RTSPState {
53 URLContext *rtsp_hd; /* RTSP TCP connexion handle */
8b1ab7bf
FB
54 int nb_rtsp_streams;
55 struct RTSPStream **rtsp_streams;
115329f1 56
ff762d6e
FB
57 enum RTSPClientState state;
58 int64_t seek_timestamp;
115329f1 59
b6892136
FB
60 /* XXX: currently we use unbuffered input */
61 // ByteIOContext rtsp_gb;
1617ad97
FB
62 int seq; /* RTSP command sequence number */
63 char session_id[512];
64 enum RTSPProtocol protocol;
e0776043 65 enum RTSPServerType server_type;
1617ad97 66 char last_reply[2048]; /* XXX: allocate ? */
8b1ab7bf 67 RTPDemuxContext *cur_rtp;
1617ad97
FB
68} RTSPState;
69
70typedef struct RTSPStream {
8b1ab7bf
FB
71 URLContext *rtp_handle; /* RTP stream handle */
72 RTPDemuxContext *rtp_ctx; /* RTP parse context */
115329f1 73
8b1ab7bf 74 int stream_index; /* corresponding stream index, if any. -1 if none (MPEG2TS case) */
1617ad97 75 int interleaved_min, interleaved_max; /* interleave ids, if TCP transport */
93ced3e8
FB
76 char control_url[1024]; /* url for this stream (from SDP) */
77
78 int sdp_port; /* port (from SDP content - not used in RTSP) */
79 struct in_addr sdp_ip; /* IP address (from SDP content - not used in RTSP) */
80 int sdp_ttl; /* IP TTL (from SDP content - not used in RTSP) */
81 int sdp_payload_type; /* payload type - only used in SDP */
d1ccf0e0 82 rtp_payload_data_t rtp_payload_data; /* rtp payload parsing infos from SDP */
4934884a
RM
83
84 RTPDynamicProtocolHandler *dynamic_handler; ///< Only valid if it's a dynamic protocol. (This is the handler structure)
85 void *dynamic_protocol_context; ///< Only valid if it's a dynamic protocol. (This is any private data associated with the dynamic protocol)
1617ad97
FB
86} RTSPStream;
87
ff762d6e
FB
88static int rtsp_read_play(AVFormatContext *s);
89
1617ad97
FB
90/* XXX: currently, the only way to change the protocols consists in
91 changing this variable */
1617ad97 92
c482500f 93#if LIBAVFORMAT_VERSION_INT < (53 << 16)
d1ccf0e0 94int rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_UDP);
c482500f 95#endif
85fb7b34 96
1617ad97
FB
97static int rtsp_probe(AVProbeData *p)
98{
f7d78f36 99 if (av_strstart(p->filename, "rtsp:", NULL))
1617ad97
FB
100 return AVPROBE_SCORE_MAX;
101 return 0;
102}
103
104static int redir_isspace(int c)
105{
ccd425e7 106 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
1617ad97
FB
107}
108
109static void skip_spaces(const char **pp)
110{
111 const char *p;
112 p = *pp;
113 while (redir_isspace(*p))
114 p++;
115 *pp = p;
116}
117
115329f1 118static void get_word_sep(char *buf, int buf_size, const char *sep,
1617ad97
FB
119 const char **pp)
120{
121 const char *p;
122 char *q;
123
124 p = *pp;
d1ccf0e0
RD
125 if (*p == '/')
126 p++;
1617ad97
FB
127 skip_spaces(&p);
128 q = buf;
129 while (!strchr(sep, *p) && *p != '\0') {
130 if ((q - buf) < buf_size - 1)
131 *q++ = *p;
132 p++;
133 }
134 if (buf_size > 0)
135 *q = '\0';
136 *pp = p;
137}
138
139static void get_word(char *buf, int buf_size, const char **pp)
140{
141 const char *p;
142 char *q;
143
144 p = *pp;
145 skip_spaces(&p);
146 q = buf;
147 while (!redir_isspace(*p) && *p != '\0') {
148 if ((q - buf) < buf_size - 1)
149 *q++ = *p;
150 p++;
151 }
152 if (buf_size > 0)
153 *q = '\0';
154 *pp = p;
155}
156
93ced3e8
FB
157/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
158 params>] */
4934884a 159static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)
93ced3e8
FB
160{
161 char buf[256];
d1ccf0e0
RD
162 int i;
163 AVCodec *c;
7b49ce2e 164 const char *c_name;
93ced3e8 165
d1ccf0e0
RD
166 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
167 see if we can handle this kind of payload */
93ced3e8 168 get_word_sep(buf, sizeof(buf), "/", &p);
d1ccf0e0 169 if (payload_type >= RTP_PT_PRIVATE) {
4934884a
RM
170 RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
171 while(handler) {
172 if (!strcmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
173 codec->codec_id = handler->codec_id;
174 rtsp_st->dynamic_handler= handler;
175 if(handler->open) {
176 rtsp_st->dynamic_protocol_context= handler->open();
177 }
d1ccf0e0
RD
178 break;
179 }
4934884a
RM
180 handler= handler->next;
181 }
93ced3e8 182 } else {
d1ccf0e0
RD
183 /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */
184 /* search into AVRtpPayloadTypes[] */
7ed19d7f 185 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
d1ccf0e0
RD
186 }
187
188 c = avcodec_find_decoder(codec->codec_id);
189 if (c && c->name)
7b49ce2e 190 c_name = c->name;
d1ccf0e0
RD
191 else
192 c_name = (char *)NULL;
193
194 if (c_name) {
195 get_word_sep(buf, sizeof(buf), "/", &p);
196 i = atoi(buf);
197 switch (codec->codec_type) {
198 case CODEC_TYPE_AUDIO:
199 av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name);
200 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
201 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
202 if (i > 0) {
203 codec->sample_rate = i;
204 get_word_sep(buf, sizeof(buf), "/", &p);
205 i = atoi(buf);
206 if (i > 0)
207 codec->channels = i;
d0deedcb
RM
208 // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the
209 // frequency. No problem, but the sample rate is being set here by the sdp line. Upcoming patch forthcoming. (rdm)
d1ccf0e0
RD
210 }
211 av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);
212 av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);
213 break;
214 case CODEC_TYPE_VIDEO:
215 av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);
216 break;
217 default:
218 break;
219 }
220 return 0;
93ced3e8 221 }
d1ccf0e0
RD
222
223 return -1;
93ced3e8
FB
224}
225
226/* return the length and optionnaly the data */
227static int hex_to_data(uint8_t *data, const char *p)
228{
229 int c, len, v;
230
231 len = 0;
232 v = 1;
233 for(;;) {
234 skip_spaces(&p);
235 if (p == '\0')
236 break;
237 c = toupper((unsigned char)*p++);
238 if (c >= '0' && c <= '9')
239 c = c - '0';
240 else if (c >= 'A' && c <= 'F')
241 c = c - 'A' + 10;
242 else
243 break;
244 v = (v << 4) | c;
245 if (v & 0x100) {
246 if (data)
247 data[len] = v;
248 len++;
249 v = 1;
250 }
251 }
252 return len;
253}
254
d1ccf0e0
RD
255static void sdp_parse_fmtp_config(AVCodecContext *codec, char *attr, char *value)
256{
257 switch (codec->codec_id) {
258 case CODEC_ID_MPEG4:
cbee7a69 259 case CODEC_ID_AAC:
d1ccf0e0
RD
260 if (!strcmp(attr, "config")) {
261 /* decode the hexa encoded parameter */
262 int len = hex_to_data(NULL, value);
263 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
264 if (!codec->extradata)
265 return;
266 codec->extradata_size = len;
267 hex_to_data(codec->extradata, value);
268 }
269 break;
270 default:
271 break;
272 }
273 return;
274}
275
276typedef struct attrname_map
277{
7b49ce2e 278 const char *str;
d1ccf0e0
RD
279 uint16_t type;
280 uint32_t offset;
281} attrname_map_t;
282
283/* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
284#define ATTR_NAME_TYPE_INT 0
285#define ATTR_NAME_TYPE_STR 1
286static attrname_map_t attr_names[]=
287{
288 {"SizeLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, sizelength)},
289 {"IndexLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexlength)},
290 {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexdeltalength)},
291 {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, profile_level_id)},
292 {"StreamType", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, streamtype)},
293 {"mode", ATTR_NAME_TYPE_STR, offsetof(rtp_payload_data_t, mode)},
294 {NULL, -1, -1},
295};
296
d0deedcb
RM
297/** parse the attribute line from the fmtp a line of an sdp resonse. This is broken out as a function
298* because it is used in rtp_h264.c, which is forthcoming.
299*/
300int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
301{
302 skip_spaces(p);
303 if(**p)
304 {
305 get_word_sep(attr, attr_size, "=", p);
306 if (**p == '=')
307 (*p)++;
308 get_word_sep(value, value_size, ";", p);
309 if (**p == ';')
310 (*p)++;
311 return 1;
312 }
313 return 0;
314}
315
d1ccf0e0
RD
316/* parse a SDP line and save stream attributes */
317static void sdp_parse_fmtp(AVStream *st, const char *p)
93ced3e8
FB
318{
319 char attr[256];
320 char value[4096];
d1ccf0e0
RD
321 int i;
322
323 RTSPStream *rtsp_st = st->priv_data;
01f4895c 324 AVCodecContext *codec = st->codec;
d1ccf0e0 325 rtp_payload_data_t *rtp_payload_data = &rtsp_st->rtp_payload_data;
93ced3e8
FB
326
327 /* loop on each attribute */
1ad20f96
RM
328 while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
329 {
bb270c08 330 /* grab the codec extra_data from the config parameter of the fmtp line */
d1ccf0e0
RD
331 sdp_parse_fmtp_config(codec, attr, value);
332 /* Looking for a known attribute */
333 for (i = 0; attr_names[i].str; ++i) {
334 if (!strcasecmp(attr, attr_names[i].str)) {
335 if (attr_names[i].type == ATTR_NAME_TYPE_INT)
336 *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
337 else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
338 *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
bb270c08 339 }
93ced3e8 340 }
93ced3e8
FB
341 }
342}
343
31693e00
RM
344/** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
345 * and end time.
346 * Used for seeking in the rtp stream.
347 */
348static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
349{
350 char buf[256];
351
352 skip_spaces(&p);
f7d78f36 353 if (!av_stristart(p, "npt=", &p))
31693e00
RM
354 return;
355
356 *start = AV_NOPTS_VALUE;
357 *end = AV_NOPTS_VALUE;
358
359 get_word_sep(buf, sizeof(buf), "-", &p);
360 *start = parse_date(buf, 1);
361 if (*p == '-') {
362 p++;
363 get_word_sep(buf, sizeof(buf), "-", &p);
364 *end = parse_date(buf, 1);
365 }
366// av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
367// av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
368}
369
93ced3e8
FB
370typedef struct SDPParseState {
371 /* SDP only */
372 struct in_addr default_ip;
373 int default_ttl;
374} SDPParseState;
375
376static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
1617ad97
FB
377 int letter, const char *buf)
378{
8b1ab7bf 379 RTSPState *rt = s->priv_data;
1617ad97
FB
380 char buf1[64], st_type[64];
381 const char *p;
93ced3e8 382 int codec_type, payload_type, i;
1617ad97
FB
383 AVStream *st;
384 RTSPStream *rtsp_st;
93ced3e8
FB
385 struct in_addr sdp_ip;
386 int ttl;
387
1617ad97
FB
388#ifdef DEBUG
389 printf("sdp: %c='%s'\n", letter, buf);
390#endif
391
392 p = buf;
393 switch(letter) {
93ced3e8
FB
394 case 'c':
395 get_word(buf1, sizeof(buf1), &p);
396 if (strcmp(buf1, "IN") != 0)
397 return;
398 get_word(buf1, sizeof(buf1), &p);
399 if (strcmp(buf1, "IP4") != 0)
400 return;
401 get_word_sep(buf1, sizeof(buf1), "/", &p);
402 if (inet_aton(buf1, &sdp_ip) == 0)
403 return;
404 ttl = 16;
405 if (*p == '/') {
406 p++;
407 get_word_sep(buf1, sizeof(buf1), "/", &p);
408 ttl = atoi(buf1);
409 }
410 if (s->nb_streams == 0) {
411 s1->default_ip = sdp_ip;
412 s1->default_ttl = ttl;
413 } else {
414 st = s->streams[s->nb_streams - 1];
415 rtsp_st = st->priv_data;
416 rtsp_st->sdp_ip = sdp_ip;
417 rtsp_st->sdp_ttl = ttl;
418 }
419 break;
1617ad97 420 case 's':
75e61b0e 421 av_strlcpy(s->title, p, sizeof(s->title));
1617ad97
FB
422 break;
423 case 'i':
424 if (s->nb_streams == 0) {
75e61b0e 425 av_strlcpy(s->comment, p, sizeof(s->comment));
1617ad97
FB
426 break;
427 }
428 break;
429 case 'm':
430 /* new stream */
431 get_word(st_type, sizeof(st_type), &p);
432 if (!strcmp(st_type, "audio")) {
433 codec_type = CODEC_TYPE_AUDIO;
434 } else if (!strcmp(st_type, "video")) {
435 codec_type = CODEC_TYPE_VIDEO;
436 } else {
437 return;
438 }
1617ad97
FB
439 rtsp_st = av_mallocz(sizeof(RTSPStream));
440 if (!rtsp_st)
441 return;
8b1ab7bf
FB
442 rtsp_st->stream_index = -1;
443 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
93ced3e8
FB
444
445 rtsp_st->sdp_ip = s1->default_ip;
446 rtsp_st->sdp_ttl = s1->default_ttl;
447
93ced3e8
FB
448 get_word(buf1, sizeof(buf1), &p); /* port */
449 rtsp_st->sdp_port = atoi(buf1);
450
451 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
115329f1 452
93ced3e8
FB
453 /* XXX: handle list of formats */
454 get_word(buf1, sizeof(buf1), &p); /* format list */
455 rtsp_st->sdp_payload_type = atoi(buf1);
93ced3e8 456
7ed19d7f 457 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
8b1ab7bf
FB
458 /* no corresponding stream */
459 } else {
460 st = av_new_stream(s, 0);
461 if (!st)
462 return;
463 st->priv_data = rtsp_st;
464 rtsp_st->stream_index = st->index;
01f4895c 465 st->codec->codec_type = codec_type;
d1ccf0e0 466 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
8b1ab7bf 467 /* if standard payload type, we can find the codec right now */
01f4895c 468 rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
8b1ab7bf
FB
469 }
470 }
1617ad97 471 /* put a default control url */
75e61b0e 472 av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
1617ad97
FB
473 break;
474 case 'a':
f7d78f36 475 if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
1617ad97
FB
476 char proto[32];
477 /* get the control url */
478 st = s->streams[s->nb_streams - 1];
479 rtsp_st = st->priv_data;
115329f1 480
1617ad97 481 /* XXX: may need to add full url resolution */
6ba5cbc6 482 url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
1617ad97
FB
483 if (proto[0] == '\0') {
484 /* relative control URL */
75e61b0e
MR
485 av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
486 av_strlcat(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
1617ad97 487 } else {
75e61b0e 488 av_strlcpy(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
1617ad97 489 }
f7d78f36 490 } else if (av_strstart(p, "rtpmap:", &p)) {
93ced3e8 491 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
115329f1 492 get_word(buf1, sizeof(buf1), &p);
93ced3e8
FB
493 payload_type = atoi(buf1);
494 for(i = 0; i < s->nb_streams;i++) {
495 st = s->streams[i];
496 rtsp_st = st->priv_data;
497 if (rtsp_st->sdp_payload_type == payload_type) {
4934884a 498 sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
93ced3e8
FB
499 }
500 }
f7d78f36 501 } else if (av_strstart(p, "fmtp:", &p)) {
93ced3e8 502 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
115329f1 503 get_word(buf1, sizeof(buf1), &p);
93ced3e8
FB
504 payload_type = atoi(buf1);
505 for(i = 0; i < s->nb_streams;i++) {
506 st = s->streams[i];
507 rtsp_st = st->priv_data;
508 if (rtsp_st->sdp_payload_type == payload_type) {
4934884a
RM
509 if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
510 if(!rtsp_st->dynamic_handler->parse_sdp_a_line(st, rtsp_st->dynamic_protocol_context, buf)) {
511 sdp_parse_fmtp(st, p);
512 }
513 } else {
ed787542 514 sdp_parse_fmtp(st, p);
4934884a 515 }
93ced3e8
FB
516 }
517 }
f7d78f36 518 } else if(av_strstart(p, "framesize:", &p)) {
d0deedcb
RM
519 // let dynamic protocol handlers have a stab at the line.
520 get_word(buf1, sizeof(buf1), &p);
521 payload_type = atoi(buf1);
522 for(i = 0; i < s->nb_streams;i++) {
523 st = s->streams[i];
524 rtsp_st = st->priv_data;
525 if (rtsp_st->sdp_payload_type == payload_type) {
526 if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
527 rtsp_st->dynamic_handler->parse_sdp_a_line(st, rtsp_st->dynamic_protocol_context, buf);
528 }
529 }
530 }
f7d78f36 531 } else if(av_strstart(p, "range:", &p)) {
31693e00
RM
532 int64_t start, end;
533
534 // this is so that seeking on a streamed file can work.
535 rtsp_parse_range_npt(p, &start, &end);
536 s->start_time= start;
537 s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
8646b907
RB
538 } else if (s->nb_streams > 0) {
539 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
540 if (rtsp_st->dynamic_handler &&
541 rtsp_st->dynamic_handler->parse_sdp_a_line)
542 rtsp_st->dynamic_handler->parse_sdp_a_line(s->streams[s->nb_streams - 1],
543 rtsp_st->dynamic_protocol_context, buf);
1617ad97
FB
544 }
545 break;
546 }
547}
548
5c91a675 549static int sdp_parse(AVFormatContext *s, const char *content)
1617ad97
FB
550{
551 const char *p;
552 int letter;
d6bb9ebd 553 char buf[2048], *q;
93ced3e8 554 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
115329f1 555
93ced3e8 556 memset(s1, 0, sizeof(SDPParseState));
1617ad97
FB
557 p = content;
558 for(;;) {
559 skip_spaces(&p);
560 letter = *p;
561 if (letter == '\0')
562 break;
563 p++;
564 if (*p != '=')
565 goto next_line;
566 p++;
567 /* get the content */
568 q = buf;
b6892136 569 while (*p != '\n' && *p != '\r' && *p != '\0') {
1617ad97
FB
570 if ((q - buf) < sizeof(buf) - 1)
571 *q++ = *p;
572 p++;
573 }
574 *q = '\0';
93ced3e8 575 sdp_parse_line(s, s1, letter, buf);
1617ad97
FB
576 next_line:
577 while (*p != '\n' && *p != '\0')
578 p++;
579 if (*p == '\n')
580 p++;
581 }
582 return 0;
583}
584
585static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
586{
587 const char *p;
588 int v;
589
590 p = *pp;
591 skip_spaces(&p);
592 v = strtol(p, (char **)&p, 10);
593 if (*p == '-') {
594 p++;
595 *min_ptr = v;
596 v = strtol(p, (char **)&p, 10);
597 *max_ptr = v;
598 } else {
599 *min_ptr = v;
600 *max_ptr = v;
601 }
602 *pp = p;
603}
604
605/* XXX: only one transport specification is parsed */
606static void rtsp_parse_transport(RTSPHeader *reply, const char *p)
607{
608 char transport_protocol[16];
609 char profile[16];
610 char lower_transport[16];
611 char parameter[16];
612 RTSPTransportField *th;
613 char buf[256];
115329f1 614
1617ad97 615 reply->nb_transports = 0;
115329f1 616
1617ad97
FB
617 for(;;) {
618 skip_spaces(&p);
619 if (*p == '\0')
620 break;
621
622 th = &reply->transports[reply->nb_transports];
623
115329f1 624 get_word_sep(transport_protocol, sizeof(transport_protocol),
1617ad97
FB
625 "/", &p);
626 if (*p == '/')
627 p++;
e1502118 628 if (!strcasecmp (transport_protocol, "rtp")) {
7ecc634e
LB
629 get_word_sep(profile, sizeof(profile), "/;,", &p);
630 lower_transport[0] = '\0';
631 /* rtp/avp/<protocol> */
632 if (*p == '/') {
633 p++;
634 get_word_sep(lower_transport, sizeof(lower_transport),
635 ";,", &p);
636 }
637 } else if (!strcasecmp (transport_protocol, "x-pn-tng")) {
638 /* x-pn-tng/<protocol> */
e1502118
LB
639 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
640 profile[0] = '\0';
1617ad97 641 }
b6892136 642 if (!strcasecmp(lower_transport, "TCP"))
1617ad97
FB
643 th->protocol = RTSP_PROTOCOL_RTP_TCP;
644 else
645 th->protocol = RTSP_PROTOCOL_RTP_UDP;
115329f1 646
1617ad97
FB
647 if (*p == ';')
648 p++;
649 /* get each parameter */
650 while (*p != '\0' && *p != ',') {
651 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
652 if (!strcmp(parameter, "port")) {
653 if (*p == '=') {
654 p++;
655 rtsp_parse_range(&th->port_min, &th->port_max, &p);
656 }
657 } else if (!strcmp(parameter, "client_port")) {
658 if (*p == '=') {
659 p++;
115329f1 660 rtsp_parse_range(&th->client_port_min,
1617ad97
FB
661 &th->client_port_max, &p);
662 }
663 } else if (!strcmp(parameter, "server_port")) {
664 if (*p == '=') {
665 p++;
115329f1 666 rtsp_parse_range(&th->server_port_min,
1617ad97
FB
667 &th->server_port_max, &p);
668 }
669 } else if (!strcmp(parameter, "interleaved")) {
670 if (*p == '=') {
671 p++;
115329f1 672 rtsp_parse_range(&th->interleaved_min,
1617ad97
FB
673 &th->interleaved_max, &p);
674 }
675 } else if (!strcmp(parameter, "multicast")) {
676 if (th->protocol == RTSP_PROTOCOL_RTP_UDP)
677 th->protocol = RTSP_PROTOCOL_RTP_UDP_MULTICAST;
678 } else if (!strcmp(parameter, "ttl")) {
679 if (*p == '=') {
680 p++;
681 th->ttl = strtol(p, (char **)&p, 10);
682 }
683 } else if (!strcmp(parameter, "destination")) {
684 struct in_addr ipaddr;
685
686 if (*p == '=') {
687 p++;
688 get_word_sep(buf, sizeof(buf), ";,", &p);
115329f1 689 if (inet_aton(buf, &ipaddr))
1617ad97
FB
690 th->destination = ntohl(ipaddr.s_addr);
691 }
692 }
693 while (*p != ';' && *p != '\0' && *p != ',')
694 p++;
695 if (*p == ';')
696 p++;
697 }
698 if (*p == ',')
699 p++;
700
701 reply->nb_transports++;
702 }
703}
704
705void rtsp_parse_line(RTSPHeader *reply, const char *buf)
706{
707 const char *p;
708
709 /* NOTE: we do case independent match for broken servers */
710 p = buf;
f7d78f36 711 if (av_stristart(p, "Session:", &p)) {
1617ad97 712 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
f7d78f36 713 } else if (av_stristart(p, "Content-Length:", &p)) {
1617ad97 714 reply->content_length = strtol(p, NULL, 10);
f7d78f36 715 } else if (av_stristart(p, "Transport:", &p)) {
1617ad97 716 rtsp_parse_transport(reply, p);
f7d78f36 717 } else if (av_stristart(p, "CSeq:", &p)) {
1617ad97 718 reply->seq = strtol(p, NULL, 10);
f7d78f36 719 } else if (av_stristart(p, "Range:", &p)) {
31693e00 720 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
30aa6aed
RB
721 } else if (av_stristart(p, "RealChallenge1:", &p)) {
722 skip_spaces(&p);
723 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
1617ad97
FB
724 }
725}
726
2a42b5c3
LS
727static int url_readbuf(URLContext *h, unsigned char *buf, int size)
728{
729 int ret, len;
730
731 len = 0;
732 while (len < size) {
733 ret = url_read(h, buf+len, size-len);
734 if (ret < 1)
735 return ret;
736 len += ret;
737 }
738 return len;
739}
740
b7b8fc34
FB
741/* skip a RTP/TCP interleaved packet */
742static void rtsp_skip_packet(AVFormatContext *s)
743{
744 RTSPState *rt = s->priv_data;
745 int ret, len, len1;
746 uint8_t buf[1024];
747
2a42b5c3 748 ret = url_readbuf(rt->rtsp_hd, buf, 3);
b7b8fc34
FB
749 if (ret != 3)
750 return;
80fb8234 751 len = AV_RB16(buf + 1);
b7b8fc34
FB
752#ifdef DEBUG
753 printf("skipping RTP packet len=%d\n", len);
754#endif
755 /* skip payload */
756 while (len > 0) {
757 len1 = len;
758 if (len1 > sizeof(buf))
759 len1 = sizeof(buf);
2a42b5c3 760 ret = url_readbuf(rt->rtsp_hd, buf, len1);
b7b8fc34
FB
761 if (ret != len1)
762 return;
763 len -= len1;
764 }
765}
1617ad97 766
115329f1
DB
767static void rtsp_send_cmd(AVFormatContext *s,
768 const char *cmd, RTSPHeader *reply,
1617ad97
FB
769 unsigned char **content_ptr)
770{
771 RTSPState *rt = s->priv_data;
772 char buf[4096], buf1[1024], *q;
773 unsigned char ch;
774 const char *p;
775 int content_length, line_count;
776 unsigned char *content = NULL;
777
778 memset(reply, 0, sizeof(RTSPHeader));
779
780 rt->seq++;
75e61b0e 781 av_strlcpy(buf, cmd, sizeof(buf));
b6892136 782 snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
75e61b0e 783 av_strlcat(buf, buf1, sizeof(buf));
1617ad97 784 if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
b6892136 785 snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
75e61b0e 786 av_strlcat(buf, buf1, sizeof(buf));
1617ad97 787 }
75e61b0e 788 av_strlcat(buf, "\r\n", sizeof(buf));
1617ad97
FB
789#ifdef DEBUG
790 printf("Sending:\n%s--\n", buf);
791#endif
792 url_write(rt->rtsp_hd, buf, strlen(buf));
793
794 /* parse reply (XXX: use buffers) */
795 line_count = 0;
796 rt->last_reply[0] = '\0';
797 for(;;) {
798 q = buf;
799 for(;;) {
2a42b5c3 800 if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
1617ad97
FB
801 break;
802 if (ch == '\n')
803 break;
b7b8fc34
FB
804 if (ch == '$') {
805 /* XXX: only parse it if first char on line ? */
806 rtsp_skip_packet(s);
807 } else if (ch != '\r') {
1617ad97
FB
808 if ((q - buf) < sizeof(buf) - 1)
809 *q++ = ch;
810 }
811 }
812 *q = '\0';
813#ifdef DEBUG
814 printf("line='%s'\n", buf);
815#endif
816 /* test if last line */
817 if (buf[0] == '\0')
818 break;
819 p = buf;
820 if (line_count == 0) {
821 /* get reply code */
822 get_word(buf1, sizeof(buf1), &p);
823 get_word(buf1, sizeof(buf1), &p);
824 reply->status_code = atoi(buf1);
825 } else {
826 rtsp_parse_line(reply, p);
75e61b0e
MR
827 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
828 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1617ad97
FB
829 }
830 line_count++;
831 }
115329f1 832
1617ad97 833 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
75e61b0e 834 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
115329f1 835
1617ad97
FB
836 content_length = reply->content_length;
837 if (content_length > 0) {
838 /* leave some room for a trailing '\0' (useful for simple parsing) */
839 content = av_malloc(content_length + 1);
2a42b5c3 840 (void)url_readbuf(rt->rtsp_hd, content, content_length);
1617ad97
FB
841 content[content_length] = '\0';
842 }
843 if (content_ptr)
844 *content_ptr = content;
e2e2e7dd
AB
845 else
846 av_free(content);
1617ad97
FB
847}
848
1617ad97 849
8b1ab7bf
FB
850/* close and free RTSP streams */
851static void rtsp_close_streams(RTSPState *rt)
852{
853 int i;
854 RTSPStream *rtsp_st;
855
856 for(i=0;i<rt->nb_rtsp_streams;i++) {
857 rtsp_st = rt->rtsp_streams[i];
858 if (rtsp_st) {
859 if (rtsp_st->rtp_ctx)
860 rtp_parse_close(rtsp_st->rtp_ctx);
861 if (rtsp_st->rtp_handle)
862 url_close(rtsp_st->rtp_handle);
4934884a
RM
863 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
864 rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
8b1ab7bf 865 }
8b1ab7bf
FB
866 }
867 av_free(rt->rtsp_streams);
868}
869
53620bba
RB
870/**
871 * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
872 */
873static int
e9dea59f
RB
874make_setup_request (AVFormatContext *s, const char *host, int port,
875 int protocol, const char *real_challenge)
1617ad97
FB
876{
877 RTSPState *rt = s->priv_data;
53620bba 878 int j, i, err;
1617ad97 879 RTSPStream *rtsp_st;
8b1ab7bf 880 AVStream *st;
53620bba
RB
881 RTSPHeader reply1, *reply = &reply1;
882 char cmd[2048];
e9dea59f
RB
883 const char *trans_pref;
884
885 if (rt->server_type == RTSP_SERVER_RDT)
886 trans_pref = "x-pn-tng";
887 else
888 trans_pref = "RTP/AVP";
115329f1 889
1617ad97
FB
890 /* for each stream, make the setup request */
891 /* XXX: we assume the same server is used for the control of each
892 RTSP stream */
d1ccf0e0
RD
893
894 for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1617ad97
FB
895 char transport[2048];
896
8b1ab7bf 897 rtsp_st = rt->rtsp_streams[i];
1617ad97 898
1617ad97 899 /* RTP/UDP */
8792f52a 900 if (protocol == RTSP_PROTOCOL_RTP_UDP) {
85fb7b34 901 char buf[256];
85fb7b34
FB
902
903 /* first try in specified port range */
d1ccf0e0
RD
904 if (RTSP_RTP_PORT_MIN != 0) {
905 while(j <= RTSP_RTP_PORT_MAX) {
b316aa1a 906 snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
ecdcbbf6 907 j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
dbf30963 908 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
85fb7b34 909 goto rtp_opened;
d1ccf0e0 910 }
85fb7b34 911 }
1617ad97 912 }
85fb7b34 913
d1ccf0e0
RD
914/* then try on any port
915** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
916** err = AVERROR_INVALIDDATA;
917** goto fail;
918** }
919*/
85fb7b34
FB
920
921 rtp_opened:
8b1ab7bf 922 port = rtp_get_local_port(rtsp_st->rtp_handle);
0ad306bc 923 snprintf(transport, sizeof(transport) - 1,
e9dea59f
RB
924 "%s/UDP;unicast;client_port=%d",
925 trans_pref, port);
926 if (rt->server_type == RTSP_SERVER_RTP)
927 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1617ad97
FB
928 }
929
930 /* RTP/TCP */
8792f52a 931 else if (protocol == RTSP_PROTOCOL_RTP_TCP) {
0ad306bc 932 snprintf(transport, sizeof(transport) - 1,
e9dea59f 933 "%s/TCP", trans_pref);
1617ad97
FB
934 }
935
8792f52a 936 else if (protocol == RTSP_PROTOCOL_RTP_UDP_MULTICAST) {
0ad306bc 937 snprintf(transport, sizeof(transport) - 1,
e9dea59f 938 "%s/UDP;multicast", trans_pref);
1617ad97 939 }
e9dea59f
RB
940 if (rt->server_type == RTSP_SERVER_RDT)
941 av_strlcat(transport, ";mode=play", sizeof(transport));
115329f1 942 snprintf(cmd, sizeof(cmd),
b6892136
FB
943 "SETUP %s RTSP/1.0\r\n"
944 "Transport: %s\r\n",
1617ad97 945 rtsp_st->control_url, transport);
e9dea59f
RB
946 if (i == 0 && rt->server_type == RTSP_SERVER_RDT) {
947 char real_res[41], real_csum[9];
948 ff_rdt_calc_response_and_checksum(real_res, real_csum,
949 real_challenge);
950 av_strlcatf(cmd, sizeof(cmd),
951 "If-Match: %s\r\n"
952 "RealChallenge2: %s, sd=%s\r\n",
953 rt->session_id, real_res, real_csum);
954 }
1617ad97 955 rtsp_send_cmd(s, cmd, reply, NULL);
8a8754d8
RB
956 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
957 err = 1;
958 goto fail;
7e6ca34f
RB
959 } else if (reply->status_code != RTSP_STATUS_OK ||
960 reply->nb_transports != 1) {
1617ad97
FB
961 err = AVERROR_INVALIDDATA;
962 goto fail;
963 }
964
965 /* XXX: same protocol for all streams is required */
966 if (i > 0) {
967 if (reply->transports[0].protocol != rt->protocol) {
968 err = AVERROR_INVALIDDATA;
969 goto fail;
970 }
971 } else {
972 rt->protocol = reply->transports[0].protocol;
973 }
974
975 /* close RTP connection if not choosen */
976 if (reply->transports[0].protocol != RTSP_PROTOCOL_RTP_UDP &&
8792f52a 977 (protocol == RTSP_PROTOCOL_RTP_UDP)) {
8b1ab7bf
FB
978 url_close(rtsp_st->rtp_handle);
979 rtsp_st->rtp_handle = NULL;
1617ad97
FB
980 }
981
982 switch(reply->transports[0].protocol) {
983 case RTSP_PROTOCOL_RTP_TCP:
1617ad97
FB
984 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
985 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
986 break;
115329f1 987
1617ad97
FB
988 case RTSP_PROTOCOL_RTP_UDP:
989 {
990 char url[1024];
115329f1 991
1617ad97 992 /* XXX: also use address if specified */
115329f1 993 snprintf(url, sizeof(url), "rtp://%s:%d",
1617ad97 994 host, reply->transports[0].server_port_min);
8b1ab7bf 995 if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1617ad97
FB
996 err = AVERROR_INVALIDDATA;
997 goto fail;
998 }
999 }
1000 break;
1001 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
1002 {
1003 char url[1024];
d02678ec 1004 struct in_addr in;
1617ad97 1005
d02678ec 1006 in.s_addr = htonl(reply->transports[0].destination);
35b74c3d 1007 snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
d02678ec
LB
1008 inet_ntoa(in),
1009 reply->transports[0].port_min,
1010 reply->transports[0].ttl);
dbf30963 1011 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1617ad97
FB
1012 err = AVERROR_INVALIDDATA;
1013 goto fail;
1014 }
1015 }
1016 break;
1017 }
8b1ab7bf
FB
1018 /* open the RTP context */
1019 st = NULL;
1020 if (rtsp_st->stream_index >= 0)
1021 st = s->streams[rtsp_st->stream_index];
1022 if (!st)
1023 s->ctx_flags |= AVFMTCTX_NOHEADER;
dbf30963 1024 rtsp_st->rtp_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data);
d1ccf0e0 1025
8b1ab7bf 1026 if (!rtsp_st->rtp_ctx) {
769e10f0 1027 err = AVERROR(ENOMEM);
8b1ab7bf 1028 goto fail;
4934884a
RM
1029 } else {
1030 if(rtsp_st->dynamic_handler) {
1031 rtsp_st->rtp_ctx->dynamic_protocol_context= rtsp_st->dynamic_protocol_context;
1032 rtsp_st->rtp_ctx->parse_packet= rtsp_st->dynamic_handler->parse_packet;
1033 }
8b1ab7bf 1034 }
1617ad97
FB
1035 }
1036
53620bba
RB
1037 return 0;
1038
1039fail:
8a8754d8
RB
1040 for (i=0; i<rt->nb_rtsp_streams; i++) {
1041 if (rt->rtsp_streams[i]->rtp_handle) {
1042 url_close(rt->rtsp_streams[i]->rtp_handle);
1043 rt->rtsp_streams[i]->rtp_handle = NULL;
1044 }
1045 }
53620bba
RB
1046 return err;
1047}
1048
1049static int rtsp_read_header(AVFormatContext *s,
1050 AVFormatParameters *ap)
1051{
1052 RTSPState *rt = s->priv_data;
1053 char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
1054 URLContext *rtsp_hd;
1055 int port, ret, err;
1056 RTSPHeader reply1, *reply = &reply1;
1057 unsigned char *content = NULL;
1058 int protocol_mask = 0;
1cf151e9 1059 char real_challenge[64];
53620bba
RB
1060
1061 /* extract hostname and port */
1062 url_split(NULL, 0, NULL, 0,
1063 host, sizeof(host), &port, path, sizeof(path), s->filename);
1064 if (port < 0)
1065 port = RTSP_DEFAULT_PORT;
1066
1067 /* search for options */
1068 option_list = strchr(path, '?');
1069 if (option_list) {
1070 /* remove the options from the path */
1071 *option_list++ = 0;
1072 while(option_list) {
1073 /* move the option pointer */
1074 option = option_list;
1075 option_list = strchr(option_list, '&');
1076 if (option_list)
1077 *(option_list++) = 0;
1078 /* handle the options */
1079 if (strcmp(option, "udp") == 0)
1080 protocol_mask = (1<< RTSP_PROTOCOL_RTP_UDP);
1081 else if (strcmp(option, "multicast") == 0)
1082 protocol_mask = (1<< RTSP_PROTOCOL_RTP_UDP_MULTICAST);
1083 else if (strcmp(option, "tcp") == 0)
1084 protocol_mask = (1<< RTSP_PROTOCOL_RTP_TCP);
1085 }
1086 }
1087
1088 if (!protocol_mask)
8a8754d8 1089 protocol_mask = (1 << RTSP_PROTOCOL_RTP_LAST) - 1;
53620bba
RB
1090
1091 /* open the tcp connexion */
1092 snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
1093 if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
1094 return AVERROR(EIO);
1095 rt->rtsp_hd = rtsp_hd;
1096 rt->seq = 0;
1097
1cf151e9
RB
1098 /* request options supported by the server; this also detects server type */
1099 for (rt->server_type = RTSP_SERVER_RTP;;) {
1100 snprintf(cmd, sizeof(cmd),
1101 "OPTIONS %s RTSP/1.0\r\n", s->filename);
1102 if (rt->server_type == RTSP_SERVER_RDT)
1103 av_strlcat(cmd,
1104 /**
1105 * The following entries are required for proper
1106 * streaming from a Realmedia server. They are
1107 * interdependent in some way although we currently
1108 * don't quite understand how. Values were copied
1109 * from mplayer SVN r23589.
1110 * @param CompanyID is a 16-byte ID in base64
1111 * @param ClientChallenge is a 16-byte ID in hex
1112 */
1113 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1114 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1115 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1116 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1117 sizeof(cmd));
1118 rtsp_send_cmd(s, cmd, reply, NULL);
1119 if (reply->status_code != RTSP_STATUS_OK) {
1120 err = AVERROR_INVALIDDATA;
1121 goto fail;
1122 }
1123
1124 /* detect server type if not standard-compliant RTP */
1125 if (rt->server_type != RTSP_SERVER_RDT && reply->real_challenge[0]) {
1126 rt->server_type = RTSP_SERVER_RDT;
1127 continue;
1128 } else if (rt->server_type == RTSP_SERVER_RDT) {
1129 strcpy(real_challenge, reply->real_challenge);
1130 }
1131 break;
1132 }
1133
53620bba
RB
1134 /* describe the stream */
1135 snprintf(cmd, sizeof(cmd),
1136 "DESCRIBE %s RTSP/1.0\r\n"
1137 "Accept: application/sdp\r\n",
1138 s->filename);
897ade1b
RB
1139 if (rt->server_type == RTSP_SERVER_RDT) {
1140 /**
1141 * The Require: attribute is needed for proper streaming from
1142 * Realmedia servers.
1143 */
1144 av_strlcat(cmd,
1145 "Require: com.real.retain-entity-for-setup\r\n",
1146 sizeof(cmd));
1147 }
53620bba
RB
1148 rtsp_send_cmd(s, cmd, reply, &content);
1149 if (!content) {
1150 err = AVERROR_INVALIDDATA;
1151 goto fail;
1152 }
1153 if (reply->status_code != RTSP_STATUS_OK) {
1154 err = AVERROR_INVALIDDATA;
1155 goto fail;
1156 }
1157
1158 /* now we got the SDP description, we parse it */
1159 ret = sdp_parse(s, (const char *)content);
1160 av_freep(&content);
1161 if (ret < 0) {
1162 err = AVERROR_INVALIDDATA;
1163 goto fail;
1164 }
1165
8a8754d8 1166 do {
8792f52a 1167 int protocol = ff_log2_tab[protocol_mask & ~(protocol_mask - 1)];
8a8754d8 1168
e9dea59f
RB
1169 err = make_setup_request(s, host, port, protocol,
1170 rt->server_type == RTSP_SERVER_RDT ?
1171 real_challenge : NULL);
8a8754d8 1172 if (err < 0)
7e6ca34f 1173 goto fail;
8792f52a 1174 protocol_mask &= ~(1 << protocol);
8a8754d8 1175 if (protocol_mask == 0 && err == 1) {
5ee0e139 1176 err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
8a8754d8
RB
1177 goto fail;
1178 }
1179 } while (err);
53620bba 1180
ff762d6e
FB
1181 rt->state = RTSP_STATE_IDLE;
1182 rt->seek_timestamp = 0; /* default is to start stream at position
1183 zero */
c04c3282 1184 if (ap->initial_pause) {
ff762d6e
FB
1185 /* do not start immediately */
1186 } else {
1187 if (rtsp_read_play(s) < 0) {
1188 err = AVERROR_INVALIDDATA;
1617ad97
FB
1189 goto fail;
1190 }
1191 }
1617ad97
FB
1192 return 0;
1193 fail:
8b1ab7bf 1194 rtsp_close_streams(rt);
1617ad97
FB
1195 av_freep(&content);
1196 url_close(rt->rtsp_hd);
1197 return err;
1198}
1199
8b1ab7bf
FB
1200static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1201 uint8_t *buf, int buf_size)
1617ad97
FB
1202{
1203 RTSPState *rt = s->priv_data;
b6892136 1204 int id, len, i, ret;
1617ad97 1205 RTSPStream *rtsp_st;
1617ad97 1206
b6892136
FB
1207#ifdef DEBUG_RTP_TCP
1208 printf("tcp_read_packet:\n");
1209#endif
1617ad97
FB
1210 redo:
1211 for(;;) {
2a42b5c3 1212 ret = url_readbuf(rt->rtsp_hd, buf, 1);
b6892136
FB
1213#ifdef DEBUG_RTP_TCP
1214 printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
1215#endif
1216 if (ret != 1)
8b1ab7bf 1217 return -1;
b6892136 1218 if (buf[0] == '$')
1617ad97
FB
1219 break;
1220 }
2a42b5c3 1221 ret = url_readbuf(rt->rtsp_hd, buf, 3);
b6892136 1222 if (ret != 3)
8b1ab7bf 1223 return -1;
b6892136 1224 id = buf[0];
80fb8234 1225 len = AV_RB16(buf + 1);
b6892136
FB
1226#ifdef DEBUG_RTP_TCP
1227 printf("id=%d len=%d\n", id, len);
1228#endif
8b1ab7bf 1229 if (len > buf_size || len < 12)
1617ad97
FB
1230 goto redo;
1231 /* get the data */
2a42b5c3 1232 ret = url_readbuf(rt->rtsp_hd, buf, len);
b6892136 1233 if (ret != len)
8b1ab7bf 1234 return -1;
115329f1 1235
1617ad97 1236 /* find the matching stream */
8b1ab7bf
FB
1237 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1238 rtsp_st = rt->rtsp_streams[i];
115329f1
DB
1239 if (id >= rtsp_st->interleaved_min &&
1240 id <= rtsp_st->interleaved_max)
1617ad97
FB
1241 goto found;
1242 }
1243 goto redo;
1244 found:
8b1ab7bf
FB
1245 *prtsp_st = rtsp_st;
1246 return len;
1617ad97
FB
1247}
1248
115329f1 1249static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
8b1ab7bf 1250 uint8_t *buf, int buf_size)
1617ad97 1251{
8b1ab7bf 1252 RTSPState *rt = s->priv_data;
1617ad97
FB
1253 RTSPStream *rtsp_st;
1254 fd_set rfds;
1255 int fd1, fd2, fd_max, n, i, ret;
1617ad97
FB
1256 struct timeval tv;
1257
1258 for(;;) {
b7b8fc34 1259 if (url_interrupt_cb())
a960a1e0 1260 return AVERROR(EINTR);
1617ad97
FB
1261 FD_ZERO(&rfds);
1262 fd_max = -1;
8b1ab7bf
FB
1263 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1264 rtsp_st = rt->rtsp_streams[i];
1617ad97 1265 /* currently, we cannot probe RTCP handle because of blocking restrictions */
8b1ab7bf 1266 rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
1617ad97
FB
1267 if (fd1 > fd_max)
1268 fd_max = fd1;
1269 FD_SET(fd1, &rfds);
1270 }
1617ad97 1271 tv.tv_sec = 0;
b7b8fc34 1272 tv.tv_usec = 100 * 1000;
1617ad97
FB
1273 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1274 if (n > 0) {
8b1ab7bf
FB
1275 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1276 rtsp_st = rt->rtsp_streams[i];
1277 rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
1617ad97 1278 if (FD_ISSET(fd1, &rfds)) {
8b1ab7bf
FB
1279 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1280 if (ret > 0) {
1281 *prtsp_st = rtsp_st;
1617ad97
FB
1282 return ret;
1283 }
1284 }
1285 }
1286 }
1287 }
1288}
1289
1290static int rtsp_read_packet(AVFormatContext *s,
1291 AVPacket *pkt)
1292{
1293 RTSPState *rt = s->priv_data;
8b1ab7bf
FB
1294 RTSPStream *rtsp_st;
1295 int ret, len;
1296 uint8_t buf[RTP_MAX_PACKET_LENGTH];
1297
1298 /* get next frames from the same RTP packet */
1299 if (rt->cur_rtp) {
1300 ret = rtp_parse_packet(rt->cur_rtp, pkt, NULL, 0);
1301 if (ret == 0) {
1302 rt->cur_rtp = NULL;
1303 return 0;
1304 } else if (ret == 1) {
1305 return 0;
1306 } else {
1307 rt->cur_rtp = NULL;
1308 }
1309 }
1617ad97 1310
8b1ab7bf
FB
1311 /* read next RTP packet */
1312 redo:
1617ad97
FB
1313 switch(rt->protocol) {
1314 default:
1315 case RTSP_PROTOCOL_RTP_TCP:
8b1ab7bf 1316 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1617ad97
FB
1317 break;
1318 case RTSP_PROTOCOL_RTP_UDP:
8b1ab7bf
FB
1319 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
1320 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
74ef8b43 1321 if (len >=0 && rtsp_st->rtp_ctx)
dbf30963 1322 rtp_check_and_send_back_rr(rtsp_st->rtp_ctx, len);
1617ad97
FB
1323 break;
1324 }
8b1ab7bf 1325 if (len < 0)
489b0d4d 1326 return len;
8b1ab7bf
FB
1327 ret = rtp_parse_packet(rtsp_st->rtp_ctx, pkt, buf, len);
1328 if (ret < 0)
1329 goto redo;
1330 if (ret == 1) {
1331 /* more packets may follow, so we save the RTP context */
1332 rt->cur_rtp = rtsp_st->rtp_ctx;
1333 }
1334 return 0;
1617ad97
FB
1335}
1336
ff762d6e 1337static int rtsp_read_play(AVFormatContext *s)
b7b8fc34 1338{
ff762d6e 1339 RTSPState *rt = s->priv_data;
b7b8fc34
FB
1340 RTSPHeader reply1, *reply = &reply1;
1341 char cmd[1024];
1342
bc874dae 1343 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
ff762d6e
FB
1344
1345 if (rt->state == RTSP_STATE_PAUSED) {
115329f1 1346 snprintf(cmd, sizeof(cmd),
ff762d6e
FB
1347 "PLAY %s RTSP/1.0\r\n",
1348 s->filename);
1349 } else {
115329f1 1350 snprintf(cmd, sizeof(cmd),
ff762d6e
FB
1351 "PLAY %s RTSP/1.0\r\n"
1352 "Range: npt=%0.3f-\r\n",
1353 s->filename,
1354 (double)rt->seek_timestamp / AV_TIME_BASE);
1355 }
b7b8fc34
FB
1356 rtsp_send_cmd(s, cmd, reply, NULL);
1357 if (reply->status_code != RTSP_STATUS_OK) {
1358 return -1;
b7b8fc34 1359 }
5f86057f
RB
1360 rt->state = RTSP_STATE_PLAYING;
1361 return 0;
b7b8fc34
FB
1362}
1363
ff762d6e
FB
1364/* pause the stream */
1365static int rtsp_read_pause(AVFormatContext *s)
b7b8fc34 1366{
ff762d6e 1367 RTSPState *rt = s->priv_data;
b7b8fc34
FB
1368 RTSPHeader reply1, *reply = &reply1;
1369 char cmd[1024];
1370
b7b8fc34 1371 rt = s->priv_data;
115329f1 1372
ff762d6e
FB
1373 if (rt->state != RTSP_STATE_PLAYING)
1374 return 0;
1375
115329f1 1376 snprintf(cmd, sizeof(cmd),
ff762d6e 1377 "PAUSE %s RTSP/1.0\r\n",
b7b8fc34
FB
1378 s->filename);
1379 rtsp_send_cmd(s, cmd, reply, NULL);
1380 if (reply->status_code != RTSP_STATUS_OK) {
1381 return -1;
b7b8fc34 1382 }
5f86057f
RB
1383 rt->state = RTSP_STATE_PAUSED;
1384 return 0;
b7b8fc34
FB
1385}
1386
115329f1 1387static int rtsp_read_seek(AVFormatContext *s, int stream_index,
7b3c1382 1388 int64_t timestamp, int flags)
ff762d6e
FB
1389{
1390 RTSPState *rt = s->priv_data;
115329f1 1391
50755217 1392 rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
ff762d6e
FB
1393 switch(rt->state) {
1394 default:
1395 case RTSP_STATE_IDLE:
1396 break;
1397 case RTSP_STATE_PLAYING:
1398 if (rtsp_read_play(s) != 0)
1399 return -1;
1400 break;
1401 case RTSP_STATE_PAUSED:
1402 rt->state = RTSP_STATE_IDLE;
1403 break;
1404 }
1405 return 0;
1406}
1407
1617ad97
FB
1408static int rtsp_read_close(AVFormatContext *s)
1409{
1410 RTSPState *rt = s->priv_data;
1617ad97 1411 RTSPHeader reply1, *reply = &reply1;
1617ad97
FB
1412 char cmd[1024];
1413
b6892136 1414#if 0
1617ad97
FB
1415 /* NOTE: it is valid to flush the buffer here */
1416 if (rt->protocol == RTSP_PROTOCOL_RTP_TCP) {
1417 url_fclose(&rt->rtsp_gb);
1418 }
b6892136 1419#endif
115329f1 1420 snprintf(cmd, sizeof(cmd),
b6892136 1421 "TEARDOWN %s RTSP/1.0\r\n",
1617ad97
FB
1422 s->filename);
1423 rtsp_send_cmd(s, cmd, reply, NULL);
1424
8b1ab7bf 1425 rtsp_close_streams(rt);
1617ad97
FB
1426 url_close(rt->rtsp_hd);
1427 return 0;
1428}
1429
96862926 1430#ifdef CONFIG_RTSP_DEMUXER
d2a067d1 1431AVInputFormat rtsp_demuxer = {
1617ad97 1432 "rtsp",
bde15e74 1433 NULL_IF_CONFIG_SMALL("RTSP input format"),
1617ad97
FB
1434 sizeof(RTSPState),
1435 rtsp_probe,
1436 rtsp_read_header,
1437 rtsp_read_packet,
1438 rtsp_read_close,
ff762d6e 1439 rtsp_read_seek,
bb76a117 1440 .flags = AVFMT_NOFILE,
ff762d6e
FB
1441 .read_play = rtsp_read_play,
1442 .read_pause = rtsp_read_pause,
1617ad97 1443};
96862926 1444#endif
1617ad97 1445
cb1fdc61 1446static int sdp_probe(AVProbeData *p1)
93ced3e8 1447{
0e1ceacd 1448 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
cb1fdc61
FB
1449
1450 /* we look for a line beginning "c=IN IP4" */
0e1ceacd 1451 while (p < p_end && *p != '\0') {
f7d78f36 1452 if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
cb1fdc61 1453 return AVPROBE_SCORE_MAX / 2;
0e1ceacd
MN
1454
1455 while(p < p_end - 1 && *p != '\n') p++;
1456 if (++p >= p_end)
cb1fdc61 1457 break;
cb1fdc61
FB
1458 if (*p == '\r')
1459 p++;
1460 }
93ced3e8
FB
1461 return 0;
1462}
1463
1464#define SDP_MAX_SIZE 8192
1465
1466static int sdp_read_header(AVFormatContext *s,
1467 AVFormatParameters *ap)
1468{
8b1ab7bf 1469 RTSPState *rt = s->priv_data;
93ced3e8
FB
1470 RTSPStream *rtsp_st;
1471 int size, i, err;
1472 char *content;
1473 char url[1024];
8b1ab7bf 1474 AVStream *st;
93ced3e8
FB
1475
1476 /* read the whole sdp file */
1477 /* XXX: better loading */
1478 content = av_malloc(SDP_MAX_SIZE);
899681cd 1479 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
93ced3e8
FB
1480 if (size <= 0) {
1481 av_free(content);
1482 return AVERROR_INVALIDDATA;
1483 }
1484 content[size] ='\0';
1485
1486 sdp_parse(s, content);
1487 av_free(content);
1488
1489 /* open each RTP stream */
8b1ab7bf
FB
1490 for(i=0;i<rt->nb_rtsp_streams;i++) {
1491 rtsp_st = rt->rtsp_streams[i];
115329f1 1492
d2bf42be 1493 snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
115329f1 1494 inet_ntoa(rtsp_st->sdp_ip),
93ced3e8 1495 rtsp_st->sdp_port,
d2bf42be 1496 rtsp_st->sdp_port,
93ced3e8 1497 rtsp_st->sdp_ttl);
dbf30963 1498 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
93ced3e8
FB
1499 err = AVERROR_INVALIDDATA;
1500 goto fail;
1501 }
8b1ab7bf
FB
1502 /* open the RTP context */
1503 st = NULL;
1504 if (rtsp_st->stream_index >= 0)
1505 st = s->streams[rtsp_st->stream_index];
1506 if (!st)
1507 s->ctx_flags |= AVFMTCTX_NOHEADER;
dbf30963 1508 rtsp_st->rtp_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data);
8b1ab7bf 1509 if (!rtsp_st->rtp_ctx) {
769e10f0 1510 err = AVERROR(ENOMEM);
8b1ab7bf 1511 goto fail;
4934884a
RM
1512 } else {
1513 if(rtsp_st->dynamic_handler) {
1514 rtsp_st->rtp_ctx->dynamic_protocol_context= rtsp_st->dynamic_protocol_context;
1515 rtsp_st->rtp_ctx->parse_packet= rtsp_st->dynamic_handler->parse_packet;
1516 }
8b1ab7bf 1517 }
93ced3e8
FB
1518 }
1519 return 0;
1520 fail:
8b1ab7bf 1521 rtsp_close_streams(rt);
93ced3e8
FB
1522 return err;
1523}
1524
1525static int sdp_read_packet(AVFormatContext *s,
1526 AVPacket *pkt)
1527{
8b1ab7bf 1528 return rtsp_read_packet(s, pkt);
93ced3e8
FB
1529}
1530
1531static int sdp_read_close(AVFormatContext *s)
1532{
8b1ab7bf
FB
1533 RTSPState *rt = s->priv_data;
1534 rtsp_close_streams(rt);
93ced3e8
FB
1535 return 0;
1536}
1537
ff70e601
MR
1538#ifdef CONFIG_SDP_DEMUXER
1539AVInputFormat sdp_demuxer = {
93ced3e8 1540 "sdp",
bde15e74 1541 NULL_IF_CONFIG_SMALL("SDP"),
93ced3e8
FB
1542 sizeof(RTSPState),
1543 sdp_probe,
1544 sdp_read_header,
1545 sdp_read_packet,
1546 sdp_read_close,
1547};
ff70e601 1548#endif
93ced3e8 1549
e7047005 1550#ifdef CONFIG_REDIR_DEMUXER
1617ad97
FB
1551/* dummy redirector format (used directly in av_open_input_file now) */
1552static int redir_probe(AVProbeData *pd)
1553{
1554 const char *p;
1555 p = pd->buf;
1556 while (redir_isspace(*p))
1557 p++;
f7d78f36
MR
1558 if (av_strstart(p, "http://", NULL) ||
1559 av_strstart(p, "rtsp://", NULL))
1617ad97
FB
1560 return AVPROBE_SCORE_MAX;
1561 return 0;
1562}
1563
e8acf0ed 1564static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
1617ad97
FB
1565{
1566 char buf[4096], *q;
1567 int c;
1568 AVFormatContext *ic = NULL;
e8acf0ed 1569 ByteIOContext *f = s->pb;
1617ad97
FB
1570
1571 /* parse each URL and try to open it */
1572 c = url_fgetc(f);
1573 while (c != URL_EOF) {
1574 /* skip spaces */
1575 for(;;) {
1576 if (!redir_isspace(c))
1577 break;
1578 c = url_fgetc(f);
1579 }
1580 if (c == URL_EOF)
1581 break;
1582 /* record url */
1583 q = buf;
1584 for(;;) {
1585 if (c == URL_EOF || redir_isspace(c))
1586 break;
1587 if ((q - buf) < sizeof(buf) - 1)
1588 *q++ = c;
1589 c = url_fgetc(f);
1590 }
1591 *q = '\0';
1592 //printf("URL='%s'\n", buf);
1593 /* try to open the media file */
1594 if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
1595 break;
1596 }
1617ad97 1597 if (!ic)
6f3e0b21 1598 return AVERROR(EIO);
e8acf0ed
LA
1599
1600 *s = *ic;
1601 url_fclose(f);
1602
1603 return 0;
1617ad97
FB
1604}
1605
d2a067d1 1606AVInputFormat redir_demuxer = {
1617ad97 1607 "redir",
bde15e74 1608 NULL_IF_CONFIG_SMALL("Redirector format"),
1617ad97
FB
1609 0,
1610 redir_probe,
e8acf0ed 1611 redir_read_header,
1617ad97
FB
1612 NULL,
1613 NULL,
1614};
e7047005 1615#endif