You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1804 lines
58KB

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