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