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.

1818 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. static int url_readbuf(URLContext *h, unsigned char *buf, int size)
  649. {
  650. int ret, len;
  651. len = 0;
  652. while (len < size) {
  653. ret = url_read(h, buf+len, size-len);
  654. if (ret < 1)
  655. return ret;
  656. len += ret;
  657. }
  658. return len;
  659. }
  660. /* skip a RTP/TCP interleaved packet */
  661. static void rtsp_skip_packet(AVFormatContext *s)
  662. {
  663. RTSPState *rt = s->priv_data;
  664. int ret, len, len1;
  665. uint8_t buf[1024];
  666. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  667. if (ret != 3)
  668. return;
  669. len = AV_RB16(buf + 1);
  670. dprintf(s, "skipping RTP packet len=%d\n", len);
  671. /* skip payload */
  672. while (len > 0) {
  673. len1 = len;
  674. if (len1 > sizeof(buf))
  675. len1 = sizeof(buf);
  676. ret = url_readbuf(rt->rtsp_hd, buf, len1);
  677. if (ret != len1)
  678. return;
  679. len -= len1;
  680. }
  681. }
  682. /**
  683. * Read a RTSP message from the server, or prepare to read data
  684. * packets if we're reading data interleaved over the TCP/RTSP
  685. * connection as well.
  686. *
  687. * @param s RTSP demuxer context
  688. * @param reply pointer where the RTSP message header will be stored
  689. * @param content_ptr pointer where the RTSP message body, if any, will
  690. * be stored (length is in \p reply)
  691. * @param return_on_interleaved_data whether the function may return if we
  692. * encounter a data marker ('$'), which precedes data
  693. * packets over interleaved TCP/RTSP connections. If this
  694. * is set, this function will return 1 after encountering
  695. * a '$'. If it is not set, the function will skip any
  696. * data packets (if they are encountered), until a reply
  697. * has been fully parsed. If no more data is available
  698. * without parsing a reply, it will return an error.
  699. *
  700. * @returns 1 if a data packets is ready to be received, -1 on error,
  701. * and 0 on success.
  702. */
  703. static int
  704. rtsp_read_reply (AVFormatContext *s, RTSPMessageHeader *reply,
  705. unsigned char **content_ptr, int return_on_interleaved_data)
  706. {
  707. RTSPState *rt = s->priv_data;
  708. char buf[4096], buf1[1024], *q;
  709. unsigned char ch;
  710. const char *p;
  711. int ret, content_length, line_count = 0;
  712. unsigned char *content = NULL;
  713. memset(reply, 0, sizeof(*reply));
  714. /* parse reply (XXX: use buffers) */
  715. rt->last_reply[0] = '\0';
  716. for(;;) {
  717. q = buf;
  718. for(;;) {
  719. ret = url_readbuf(rt->rtsp_hd, &ch, 1);
  720. #ifdef DEBUG_RTP_TCP
  721. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  722. #endif
  723. if (ret != 1)
  724. return -1;
  725. if (ch == '\n')
  726. break;
  727. if (ch == '$') {
  728. /* XXX: only parse it if first char on line ? */
  729. if (return_on_interleaved_data) {
  730. return 1;
  731. } else
  732. rtsp_skip_packet(s);
  733. } else if (ch != '\r') {
  734. if ((q - buf) < sizeof(buf) - 1)
  735. *q++ = ch;
  736. }
  737. }
  738. *q = '\0';
  739. dprintf(s, "line='%s'\n", buf);
  740. /* test if last line */
  741. if (buf[0] == '\0')
  742. break;
  743. p = buf;
  744. if (line_count == 0) {
  745. /* get reply code */
  746. get_word(buf1, sizeof(buf1), &p);
  747. get_word(buf1, sizeof(buf1), &p);
  748. reply->status_code = atoi(buf1);
  749. } else {
  750. rtsp_parse_line(reply, p);
  751. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  752. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  753. }
  754. line_count++;
  755. }
  756. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  757. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  758. content_length = reply->content_length;
  759. if (content_length > 0) {
  760. /* leave some room for a trailing '\0' (useful for simple parsing) */
  761. content = av_malloc(content_length + 1);
  762. (void)url_readbuf(rt->rtsp_hd, content, content_length);
  763. content[content_length] = '\0';
  764. }
  765. if (content_ptr)
  766. *content_ptr = content;
  767. else
  768. av_free(content);
  769. return 0;
  770. }
  771. static void rtsp_send_cmd_async (AVFormatContext *s,
  772. const char *cmd, RTSPMessageHeader *reply,
  773. unsigned char **content_ptr)
  774. {
  775. RTSPState *rt = s->priv_data;
  776. char buf[4096], buf1[1024];
  777. rt->seq++;
  778. av_strlcpy(buf, cmd, sizeof(buf));
  779. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  780. av_strlcat(buf, buf1, sizeof(buf));
  781. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  782. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  783. av_strlcat(buf, buf1, sizeof(buf));
  784. }
  785. av_strlcat(buf, "\r\n", sizeof(buf));
  786. dprintf(s, "Sending:\n%s--\n", buf);
  787. url_write(rt->rtsp_hd, buf, strlen(buf));
  788. rt->last_cmd_time = av_gettime();
  789. }
  790. static void rtsp_send_cmd (AVFormatContext *s,
  791. const char *cmd, RTSPMessageHeader *reply,
  792. unsigned char **content_ptr)
  793. {
  794. rtsp_send_cmd_async(s, cmd, reply, content_ptr);
  795. rtsp_read_reply(s, reply, content_ptr, 0);
  796. }
  797. /* close and free RTSP streams */
  798. static void rtsp_close_streams(RTSPState *rt)
  799. {
  800. int i;
  801. RTSPStream *rtsp_st;
  802. for(i=0;i<rt->nb_rtsp_streams;i++) {
  803. rtsp_st = rt->rtsp_streams[i];
  804. if (rtsp_st) {
  805. if (rtsp_st->transport_priv) {
  806. if (rt->transport == RTSP_TRANSPORT_RDT)
  807. ff_rdt_parse_close(rtsp_st->transport_priv);
  808. else
  809. rtp_parse_close(rtsp_st->transport_priv);
  810. }
  811. if (rtsp_st->rtp_handle)
  812. url_close(rtsp_st->rtp_handle);
  813. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  814. rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
  815. }
  816. }
  817. av_free(rt->rtsp_streams);
  818. if (rt->asf_ctx) {
  819. av_close_input_stream (rt->asf_ctx);
  820. rt->asf_ctx = NULL;
  821. }
  822. }
  823. static int
  824. rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  825. {
  826. RTSPState *rt = s->priv_data;
  827. AVStream *st = NULL;
  828. /* open the RTP context */
  829. if (rtsp_st->stream_index >= 0)
  830. st = s->streams[rtsp_st->stream_index];
  831. if (!st)
  832. s->ctx_flags |= AVFMTCTX_NOHEADER;
  833. if (rt->transport == RTSP_TRANSPORT_RDT)
  834. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  835. rtsp_st->dynamic_protocol_context,
  836. rtsp_st->dynamic_handler);
  837. else
  838. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  839. rtsp_st->sdp_payload_type,
  840. &rtsp_st->rtp_payload_data);
  841. if (!rtsp_st->transport_priv) {
  842. return AVERROR(ENOMEM);
  843. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  844. if(rtsp_st->dynamic_handler) {
  845. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  846. rtsp_st->dynamic_protocol_context,
  847. rtsp_st->dynamic_handler);
  848. }
  849. }
  850. return 0;
  851. }
  852. /**
  853. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  854. */
  855. static int
  856. make_setup_request (AVFormatContext *s, const char *host, int port,
  857. int lower_transport, const char *real_challenge)
  858. {
  859. RTSPState *rt = s->priv_data;
  860. int rtx, j, i, err, interleave = 0;
  861. RTSPStream *rtsp_st;
  862. RTSPMessageHeader reply1, *reply = &reply1;
  863. char cmd[2048];
  864. const char *trans_pref;
  865. if (rt->transport == RTSP_TRANSPORT_RDT)
  866. trans_pref = "x-pn-tng";
  867. else
  868. trans_pref = "RTP/AVP";
  869. /* default timeout: 1 minute */
  870. rt->timeout = 60;
  871. /* for each stream, make the setup request */
  872. /* XXX: we assume the same server is used for the control of each
  873. RTSP stream */
  874. for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  875. char transport[2048];
  876. /**
  877. * WMS serves all UDP data over a single connection, the RTX, which
  878. * isn't necessarily the first in the SDP but has to be the first
  879. * to be set up, else the second/third SETUP will fail with a 461.
  880. */
  881. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  882. rt->server_type == RTSP_SERVER_WMS) {
  883. if (i == 0) {
  884. /* rtx first */
  885. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  886. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  887. if (len >= 4 &&
  888. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4, "/rtx"))
  889. break;
  890. }
  891. if (rtx == rt->nb_rtsp_streams)
  892. return -1; /* no RTX found */
  893. rtsp_st = rt->rtsp_streams[rtx];
  894. } else
  895. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  896. } else
  897. rtsp_st = rt->rtsp_streams[i];
  898. /* RTP/UDP */
  899. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  900. char buf[256];
  901. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  902. port = reply->transports[0].client_port_min;
  903. goto have_port;
  904. }
  905. /* first try in specified port range */
  906. if (RTSP_RTP_PORT_MIN != 0) {
  907. while(j <= RTSP_RTP_PORT_MAX) {
  908. snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
  909. j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
  910. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
  911. goto rtp_opened;
  912. }
  913. }
  914. }
  915. /* then try on any port
  916. ** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  917. ** err = AVERROR_INVALIDDATA;
  918. ** goto fail;
  919. ** }
  920. */
  921. rtp_opened:
  922. port = rtp_get_local_port(rtsp_st->rtp_handle);
  923. have_port:
  924. snprintf(transport, sizeof(transport) - 1,
  925. "%s/UDP;", trans_pref);
  926. if (rt->server_type != RTSP_SERVER_REAL)
  927. av_strlcat(transport, "unicast;", sizeof(transport));
  928. av_strlcatf(transport, sizeof(transport),
  929. "client_port=%d", port);
  930. if (rt->transport == RTSP_TRANSPORT_RTP &&
  931. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  932. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  933. }
  934. /* RTP/TCP */
  935. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  936. /** For WMS streams, the application streams are only used for
  937. * UDP. When trying to set it up for TCP streams, the server
  938. * will return an error. Therefore, we skip those streams. */
  939. if (rt->server_type == RTSP_SERVER_WMS &&
  940. s->streams[rtsp_st->stream_index]->codec->codec_type == CODEC_TYPE_DATA)
  941. continue;
  942. snprintf(transport, sizeof(transport) - 1,
  943. "%s/TCP;", trans_pref);
  944. if (rt->server_type == RTSP_SERVER_WMS)
  945. av_strlcat(transport, "unicast;", sizeof(transport));
  946. av_strlcatf(transport, sizeof(transport),
  947. "interleaved=%d-%d",
  948. interleave, interleave + 1);
  949. interleave += 2;
  950. }
  951. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  952. snprintf(transport, sizeof(transport) - 1,
  953. "%s/UDP;multicast", trans_pref);
  954. }
  955. if (rt->server_type == RTSP_SERVER_REAL ||
  956. rt->server_type == RTSP_SERVER_WMS)
  957. av_strlcat(transport, ";mode=play", sizeof(transport));
  958. snprintf(cmd, sizeof(cmd),
  959. "SETUP %s RTSP/1.0\r\n"
  960. "Transport: %s\r\n",
  961. rtsp_st->control_url, transport);
  962. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  963. char real_res[41], real_csum[9];
  964. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  965. real_challenge);
  966. av_strlcatf(cmd, sizeof(cmd),
  967. "If-Match: %s\r\n"
  968. "RealChallenge2: %s, sd=%s\r\n",
  969. rt->session_id, real_res, real_csum);
  970. }
  971. rtsp_send_cmd(s, cmd, reply, NULL);
  972. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  973. err = 1;
  974. goto fail;
  975. } else if (reply->status_code != RTSP_STATUS_OK ||
  976. reply->nb_transports != 1) {
  977. err = AVERROR_INVALIDDATA;
  978. goto fail;
  979. }
  980. /* XXX: same protocol for all streams is required */
  981. if (i > 0) {
  982. if (reply->transports[0].lower_transport != rt->lower_transport ||
  983. reply->transports[0].transport != rt->transport) {
  984. err = AVERROR_INVALIDDATA;
  985. goto fail;
  986. }
  987. } else {
  988. rt->lower_transport = reply->transports[0].lower_transport;
  989. rt->transport = reply->transports[0].transport;
  990. }
  991. /* close RTP connection if not choosen */
  992. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  993. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  994. url_close(rtsp_st->rtp_handle);
  995. rtsp_st->rtp_handle = NULL;
  996. }
  997. switch(reply->transports[0].lower_transport) {
  998. case RTSP_LOWER_TRANSPORT_TCP:
  999. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1000. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1001. break;
  1002. case RTSP_LOWER_TRANSPORT_UDP:
  1003. {
  1004. char url[1024];
  1005. /* XXX: also use address if specified */
  1006. snprintf(url, sizeof(url), "rtp://%s:%d",
  1007. host, reply->transports[0].server_port_min);
  1008. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1009. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1010. err = AVERROR_INVALIDDATA;
  1011. goto fail;
  1012. }
  1013. }
  1014. break;
  1015. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1016. {
  1017. char url[1024];
  1018. struct in_addr in;
  1019. in.s_addr = htonl(reply->transports[0].destination);
  1020. snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
  1021. inet_ntoa(in),
  1022. reply->transports[0].port_min,
  1023. reply->transports[0].ttl);
  1024. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1025. err = AVERROR_INVALIDDATA;
  1026. goto fail;
  1027. }
  1028. }
  1029. break;
  1030. }
  1031. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1032. goto fail;
  1033. }
  1034. if (reply->timeout > 0)
  1035. rt->timeout = reply->timeout;
  1036. if (rt->server_type == RTSP_SERVER_REAL)
  1037. rt->need_subscription = 1;
  1038. return 0;
  1039. fail:
  1040. for (i=0; i<rt->nb_rtsp_streams; i++) {
  1041. if (rt->rtsp_streams[i]->rtp_handle) {
  1042. url_close(rt->rtsp_streams[i]->rtp_handle);
  1043. rt->rtsp_streams[i]->rtp_handle = NULL;
  1044. }
  1045. }
  1046. return err;
  1047. }
  1048. static int rtsp_read_header(AVFormatContext *s,
  1049. AVFormatParameters *ap)
  1050. {
  1051. RTSPState *rt = s->priv_data;
  1052. char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
  1053. URLContext *rtsp_hd;
  1054. int port, ret, err;
  1055. RTSPMessageHeader reply1, *reply = &reply1;
  1056. unsigned char *content = NULL;
  1057. int lower_transport_mask = 0;
  1058. char real_challenge[64];
  1059. /* extract hostname and port */
  1060. url_split(NULL, 0, NULL, 0,
  1061. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1062. if (port < 0)
  1063. port = RTSP_DEFAULT_PORT;
  1064. /* search for options */
  1065. option_list = strchr(path, '?');
  1066. if (option_list) {
  1067. /* remove the options from the path */
  1068. *option_list++ = 0;
  1069. while(option_list) {
  1070. /* move the option pointer */
  1071. option = option_list;
  1072. option_list = strchr(option_list, '&');
  1073. if (option_list)
  1074. *(option_list++) = 0;
  1075. /* handle the options */
  1076. if (strcmp(option, "udp") == 0)
  1077. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
  1078. else if (strcmp(option, "multicast") == 0)
  1079. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1080. else if (strcmp(option, "tcp") == 0)
  1081. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
  1082. }
  1083. }
  1084. if (!lower_transport_mask)
  1085. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1086. /* open the tcp connexion */
  1087. snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
  1088. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
  1089. return AVERROR(EIO);
  1090. rt->rtsp_hd = rtsp_hd;
  1091. rt->seq = 0;
  1092. /* request options supported by the server; this also detects server type */
  1093. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1094. snprintf(cmd, sizeof(cmd),
  1095. "OPTIONS %s RTSP/1.0\r\n", s->filename);
  1096. if (rt->server_type == RTSP_SERVER_REAL)
  1097. av_strlcat(cmd,
  1098. /**
  1099. * The following entries are required for proper
  1100. * streaming from a Realmedia server. They are
  1101. * interdependent in some way although we currently
  1102. * don't quite understand how. Values were copied
  1103. * from mplayer SVN r23589.
  1104. * @param CompanyID is a 16-byte ID in base64
  1105. * @param ClientChallenge is a 16-byte ID in hex
  1106. */
  1107. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1108. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1109. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1110. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1111. sizeof(cmd));
  1112. rtsp_send_cmd(s, cmd, reply, NULL);
  1113. if (reply->status_code != RTSP_STATUS_OK) {
  1114. err = AVERROR_INVALIDDATA;
  1115. goto fail;
  1116. }
  1117. /* detect server type if not standard-compliant RTP */
  1118. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1119. rt->server_type = RTSP_SERVER_REAL;
  1120. continue;
  1121. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1122. rt->server_type = RTSP_SERVER_WMS;
  1123. } else if (rt->server_type == RTSP_SERVER_REAL) {
  1124. strcpy(real_challenge, reply->real_challenge);
  1125. }
  1126. break;
  1127. }
  1128. /* describe the stream */
  1129. snprintf(cmd, sizeof(cmd),
  1130. "DESCRIBE %s RTSP/1.0\r\n"
  1131. "Accept: application/sdp\r\n",
  1132. s->filename);
  1133. if (rt->server_type == RTSP_SERVER_REAL) {
  1134. /**
  1135. * The Require: attribute is needed for proper streaming from
  1136. * Realmedia servers.
  1137. */
  1138. av_strlcat(cmd,
  1139. "Require: com.real.retain-entity-for-setup\r\n",
  1140. sizeof(cmd));
  1141. }
  1142. rtsp_send_cmd(s, cmd, reply, &content);
  1143. if (!content) {
  1144. err = AVERROR_INVALIDDATA;
  1145. goto fail;
  1146. }
  1147. if (reply->status_code != RTSP_STATUS_OK) {
  1148. err = AVERROR_INVALIDDATA;
  1149. goto fail;
  1150. }
  1151. /* now we got the SDP description, we parse it */
  1152. ret = sdp_parse(s, (const char *)content);
  1153. av_freep(&content);
  1154. if (ret < 0) {
  1155. err = AVERROR_INVALIDDATA;
  1156. goto fail;
  1157. }
  1158. do {
  1159. int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)];
  1160. err = make_setup_request(s, host, port, lower_transport,
  1161. rt->server_type == RTSP_SERVER_REAL ?
  1162. real_challenge : NULL);
  1163. if (err < 0)
  1164. goto fail;
  1165. lower_transport_mask &= ~(1 << lower_transport);
  1166. if (lower_transport_mask == 0 && err == 1) {
  1167. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1168. goto fail;
  1169. }
  1170. } while (err);
  1171. rt->state = RTSP_STATE_IDLE;
  1172. rt->seek_timestamp = 0; /* default is to start stream at position
  1173. zero */
  1174. if (ap->initial_pause) {
  1175. /* do not start immediately */
  1176. } else {
  1177. if (rtsp_read_play(s) < 0) {
  1178. err = AVERROR_INVALIDDATA;
  1179. goto fail;
  1180. }
  1181. }
  1182. return 0;
  1183. fail:
  1184. rtsp_close_streams(rt);
  1185. av_freep(&content);
  1186. url_close(rt->rtsp_hd);
  1187. return err;
  1188. }
  1189. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1190. uint8_t *buf, int buf_size)
  1191. {
  1192. RTSPState *rt = s->priv_data;
  1193. int id, len, i, ret;
  1194. RTSPStream *rtsp_st;
  1195. #ifdef DEBUG_RTP_TCP
  1196. dprintf(s, "tcp_read_packet:\n");
  1197. #endif
  1198. redo:
  1199. for(;;) {
  1200. RTSPMessageHeader reply;
  1201. ret = rtsp_read_reply(s, &reply, NULL, 1);
  1202. if (ret == -1)
  1203. return -1;
  1204. if (ret == 1) /* received '$' */
  1205. break;
  1206. /* XXX: parse message */
  1207. }
  1208. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  1209. if (ret != 3)
  1210. return -1;
  1211. id = buf[0];
  1212. len = AV_RB16(buf + 1);
  1213. #ifdef DEBUG_RTP_TCP
  1214. dprintf(s, "id=%d len=%d\n", id, len);
  1215. #endif
  1216. if (len > buf_size || len < 12)
  1217. goto redo;
  1218. /* get the data */
  1219. ret = url_readbuf(rt->rtsp_hd, buf, len);
  1220. if (ret != len)
  1221. return -1;
  1222. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1223. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1224. return -1;
  1225. /* find the matching stream */
  1226. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1227. rtsp_st = rt->rtsp_streams[i];
  1228. if (id >= rtsp_st->interleaved_min &&
  1229. id <= rtsp_st->interleaved_max)
  1230. goto found;
  1231. }
  1232. goto redo;
  1233. found:
  1234. *prtsp_st = rtsp_st;
  1235. return len;
  1236. }
  1237. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1238. uint8_t *buf, int buf_size)
  1239. {
  1240. RTSPState *rt = s->priv_data;
  1241. RTSPStream *rtsp_st;
  1242. fd_set rfds;
  1243. int fd, fd_max, n, i, ret, tcp_fd;
  1244. struct timeval tv;
  1245. for(;;) {
  1246. if (url_interrupt_cb())
  1247. return AVERROR(EINTR);
  1248. FD_ZERO(&rfds);
  1249. if (rt->rtsp_hd) {
  1250. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1251. FD_SET(tcp_fd, &rfds);
  1252. } else {
  1253. fd_max = 0;
  1254. tcp_fd = -1;
  1255. }
  1256. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1257. rtsp_st = rt->rtsp_streams[i];
  1258. if (rtsp_st->rtp_handle) {
  1259. /* currently, we cannot probe RTCP handle because of
  1260. * blocking restrictions */
  1261. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1262. if (fd > fd_max)
  1263. fd_max = fd;
  1264. FD_SET(fd, &rfds);
  1265. }
  1266. }
  1267. tv.tv_sec = 0;
  1268. tv.tv_usec = 100 * 1000;
  1269. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1270. if (n > 0) {
  1271. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1272. rtsp_st = rt->rtsp_streams[i];
  1273. if (rtsp_st->rtp_handle) {
  1274. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1275. if (FD_ISSET(fd, &rfds)) {
  1276. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1277. if (ret > 0) {
  1278. *prtsp_st = rtsp_st;
  1279. return ret;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. if (FD_ISSET(tcp_fd, &rfds)) {
  1285. RTSPMessageHeader reply;
  1286. rtsp_read_reply(s, &reply, NULL, 0);
  1287. /* XXX: parse message */
  1288. }
  1289. }
  1290. }
  1291. }
  1292. static int rtsp_read_packet(AVFormatContext *s,
  1293. AVPacket *pkt)
  1294. {
  1295. RTSPState *rt = s->priv_data;
  1296. RTSPStream *rtsp_st;
  1297. int ret, len;
  1298. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1299. RTSPMessageHeader reply1, *reply = &reply1;
  1300. char cmd[1024];
  1301. if (rt->server_type == RTSP_SERVER_REAL) {
  1302. int i;
  1303. enum AVDiscard cache[MAX_STREAMS];
  1304. for (i = 0; i < s->nb_streams; i++)
  1305. cache[i] = s->streams[i]->discard;
  1306. if (!rt->need_subscription) {
  1307. if (memcmp (cache, rt->real_setup_cache,
  1308. sizeof(enum AVDiscard) * s->nb_streams)) {
  1309. av_strlcatf(cmd, sizeof(cmd),
  1310. "SET_PARAMETER %s RTSP/1.0\r\n"
  1311. "Unsubscribe: %s\r\n",
  1312. s->filename, rt->last_subscription);
  1313. rtsp_send_cmd(s, cmd, reply, NULL);
  1314. if (reply->status_code != RTSP_STATUS_OK)
  1315. return AVERROR_INVALIDDATA;
  1316. rt->need_subscription = 1;
  1317. }
  1318. }
  1319. if (rt->need_subscription) {
  1320. int r, rule_nr, first = 1;
  1321. memcpy(rt->real_setup_cache, cache,
  1322. sizeof(enum AVDiscard) * s->nb_streams);
  1323. rt->last_subscription[0] = 0;
  1324. snprintf(cmd, sizeof(cmd),
  1325. "SET_PARAMETER %s RTSP/1.0\r\n"
  1326. "Subscribe: ",
  1327. s->filename);
  1328. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1329. rule_nr = 0;
  1330. for (r = 0; r < s->nb_streams; r++) {
  1331. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1332. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1333. if (!first)
  1334. av_strlcat(rt->last_subscription, ",",
  1335. sizeof(rt->last_subscription));
  1336. ff_rdt_subscribe_rule(
  1337. rt->last_subscription,
  1338. sizeof(rt->last_subscription), i, rule_nr);
  1339. first = 0;
  1340. }
  1341. rule_nr++;
  1342. }
  1343. }
  1344. }
  1345. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1346. rtsp_send_cmd(s, cmd, reply, NULL);
  1347. if (reply->status_code != RTSP_STATUS_OK)
  1348. return AVERROR_INVALIDDATA;
  1349. rt->need_subscription = 0;
  1350. if (rt->state == RTSP_STATE_PLAYING)
  1351. rtsp_read_play (s);
  1352. }
  1353. }
  1354. /* get next frames from the same RTP packet */
  1355. if (rt->cur_transport_priv) {
  1356. if (rt->transport == RTSP_TRANSPORT_RDT)
  1357. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1358. else
  1359. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1360. if (ret == 0) {
  1361. rt->cur_transport_priv = NULL;
  1362. return 0;
  1363. } else if (ret == 1) {
  1364. return 0;
  1365. } else {
  1366. rt->cur_transport_priv = NULL;
  1367. }
  1368. }
  1369. /* read next RTP packet */
  1370. redo:
  1371. switch(rt->lower_transport) {
  1372. default:
  1373. case RTSP_LOWER_TRANSPORT_TCP:
  1374. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1375. break;
  1376. case RTSP_LOWER_TRANSPORT_UDP:
  1377. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1378. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1379. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1380. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1381. break;
  1382. }
  1383. if (len < 0)
  1384. return len;
  1385. if (rt->transport == RTSP_TRANSPORT_RDT)
  1386. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1387. else
  1388. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1389. if (ret < 0)
  1390. goto redo;
  1391. if (ret == 1) {
  1392. /* more packets may follow, so we save the RTP context */
  1393. rt->cur_transport_priv = rtsp_st->transport_priv;
  1394. }
  1395. /* send dummy request to keep TCP connection alive */
  1396. if ((rt->server_type == RTSP_SERVER_WMS ||
  1397. rt->server_type == RTSP_SERVER_REAL) &&
  1398. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1399. if (rt->server_type == RTSP_SERVER_WMS) {
  1400. snprintf(cmd, sizeof(cmd) - 1,
  1401. "GET_PARAMETER %s RTSP/1.0\r\n",
  1402. s->filename);
  1403. rtsp_send_cmd_async(s, cmd, reply, NULL);
  1404. } else {
  1405. rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n",
  1406. reply, NULL);
  1407. }
  1408. }
  1409. return 0;
  1410. }
  1411. static int rtsp_read_play(AVFormatContext *s)
  1412. {
  1413. RTSPState *rt = s->priv_data;
  1414. RTSPMessageHeader reply1, *reply = &reply1;
  1415. char cmd[1024];
  1416. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1417. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1418. if (rt->state == RTSP_STATE_PAUSED) {
  1419. snprintf(cmd, sizeof(cmd),
  1420. "PLAY %s RTSP/1.0\r\n",
  1421. s->filename);
  1422. } else {
  1423. snprintf(cmd, sizeof(cmd),
  1424. "PLAY %s RTSP/1.0\r\n"
  1425. "Range: npt=%0.3f-\r\n",
  1426. s->filename,
  1427. (double)rt->seek_timestamp / AV_TIME_BASE);
  1428. }
  1429. rtsp_send_cmd(s, cmd, reply, NULL);
  1430. if (reply->status_code != RTSP_STATUS_OK) {
  1431. return -1;
  1432. }
  1433. }
  1434. rt->state = RTSP_STATE_PLAYING;
  1435. return 0;
  1436. }
  1437. /* pause the stream */
  1438. static int rtsp_read_pause(AVFormatContext *s)
  1439. {
  1440. RTSPState *rt = s->priv_data;
  1441. RTSPMessageHeader reply1, *reply = &reply1;
  1442. char cmd[1024];
  1443. rt = s->priv_data;
  1444. if (rt->state != RTSP_STATE_PLAYING)
  1445. return 0;
  1446. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1447. snprintf(cmd, sizeof(cmd),
  1448. "PAUSE %s RTSP/1.0\r\n",
  1449. s->filename);
  1450. rtsp_send_cmd(s, cmd, reply, NULL);
  1451. if (reply->status_code != RTSP_STATUS_OK) {
  1452. return -1;
  1453. }
  1454. }
  1455. rt->state = RTSP_STATE_PAUSED;
  1456. return 0;
  1457. }
  1458. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1459. int64_t timestamp, int flags)
  1460. {
  1461. RTSPState *rt = s->priv_data;
  1462. rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
  1463. switch(rt->state) {
  1464. default:
  1465. case RTSP_STATE_IDLE:
  1466. break;
  1467. case RTSP_STATE_PLAYING:
  1468. if (rtsp_read_play(s) != 0)
  1469. return -1;
  1470. break;
  1471. case RTSP_STATE_PAUSED:
  1472. rt->state = RTSP_STATE_IDLE;
  1473. break;
  1474. }
  1475. return 0;
  1476. }
  1477. static int rtsp_read_close(AVFormatContext *s)
  1478. {
  1479. RTSPState *rt = s->priv_data;
  1480. RTSPMessageHeader reply1, *reply = &reply1;
  1481. char cmd[1024];
  1482. #if 0
  1483. /* NOTE: it is valid to flush the buffer here */
  1484. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1485. url_fclose(&rt->rtsp_gb);
  1486. }
  1487. #endif
  1488. snprintf(cmd, sizeof(cmd),
  1489. "TEARDOWN %s RTSP/1.0\r\n",
  1490. s->filename);
  1491. rtsp_send_cmd(s, cmd, reply, NULL);
  1492. rtsp_close_streams(rt);
  1493. url_close(rt->rtsp_hd);
  1494. return 0;
  1495. }
  1496. #if CONFIG_RTSP_DEMUXER
  1497. AVInputFormat rtsp_demuxer = {
  1498. "rtsp",
  1499. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1500. sizeof(RTSPState),
  1501. rtsp_probe,
  1502. rtsp_read_header,
  1503. rtsp_read_packet,
  1504. rtsp_read_close,
  1505. rtsp_read_seek,
  1506. .flags = AVFMT_NOFILE,
  1507. .read_play = rtsp_read_play,
  1508. .read_pause = rtsp_read_pause,
  1509. };
  1510. #endif
  1511. static int sdp_probe(AVProbeData *p1)
  1512. {
  1513. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1514. /* we look for a line beginning "c=IN IP4" */
  1515. while (p < p_end && *p != '\0') {
  1516. if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
  1517. return AVPROBE_SCORE_MAX / 2;
  1518. while(p < p_end - 1 && *p != '\n') p++;
  1519. if (++p >= p_end)
  1520. break;
  1521. if (*p == '\r')
  1522. p++;
  1523. }
  1524. return 0;
  1525. }
  1526. #define SDP_MAX_SIZE 8192
  1527. static int sdp_read_header(AVFormatContext *s,
  1528. AVFormatParameters *ap)
  1529. {
  1530. RTSPState *rt = s->priv_data;
  1531. RTSPStream *rtsp_st;
  1532. int size, i, err;
  1533. char *content;
  1534. char url[1024];
  1535. /* read the whole sdp file */
  1536. /* XXX: better loading */
  1537. content = av_malloc(SDP_MAX_SIZE);
  1538. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1539. if (size <= 0) {
  1540. av_free(content);
  1541. return AVERROR_INVALIDDATA;
  1542. }
  1543. content[size] ='\0';
  1544. sdp_parse(s, content);
  1545. av_free(content);
  1546. /* open each RTP stream */
  1547. for(i=0;i<rt->nb_rtsp_streams;i++) {
  1548. rtsp_st = rt->rtsp_streams[i];
  1549. snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
  1550. inet_ntoa(rtsp_st->sdp_ip),
  1551. rtsp_st->sdp_port,
  1552. rtsp_st->sdp_port,
  1553. rtsp_st->sdp_ttl);
  1554. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1555. err = AVERROR_INVALIDDATA;
  1556. goto fail;
  1557. }
  1558. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1559. goto fail;
  1560. }
  1561. return 0;
  1562. fail:
  1563. rtsp_close_streams(rt);
  1564. return err;
  1565. }
  1566. static int sdp_read_packet(AVFormatContext *s,
  1567. AVPacket *pkt)
  1568. {
  1569. return rtsp_read_packet(s, pkt);
  1570. }
  1571. static int sdp_read_close(AVFormatContext *s)
  1572. {
  1573. RTSPState *rt = s->priv_data;
  1574. rtsp_close_streams(rt);
  1575. return 0;
  1576. }
  1577. #if CONFIG_SDP_DEMUXER
  1578. AVInputFormat sdp_demuxer = {
  1579. "sdp",
  1580. NULL_IF_CONFIG_SMALL("SDP"),
  1581. sizeof(RTSPState),
  1582. sdp_probe,
  1583. sdp_read_header,
  1584. sdp_read_packet,
  1585. sdp_read_close,
  1586. };
  1587. #endif
  1588. #if CONFIG_REDIR_DEMUXER
  1589. /* dummy redirector format (used directly in av_open_input_file now) */
  1590. static int redir_probe(AVProbeData *pd)
  1591. {
  1592. const char *p;
  1593. p = pd->buf;
  1594. skip_spaces(&p);
  1595. if (av_strstart(p, "http://", NULL) ||
  1596. av_strstart(p, "rtsp://", NULL))
  1597. return AVPROBE_SCORE_MAX;
  1598. return 0;
  1599. }
  1600. static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1601. {
  1602. char buf[4096], *q;
  1603. int c;
  1604. AVFormatContext *ic = NULL;
  1605. ByteIOContext *f = s->pb;
  1606. /* parse each URL and try to open it */
  1607. c = url_fgetc(f);
  1608. while (c != URL_EOF) {
  1609. /* skip spaces */
  1610. for(;;) {
  1611. if (!redir_isspace(c))
  1612. break;
  1613. c = url_fgetc(f);
  1614. }
  1615. if (c == URL_EOF)
  1616. break;
  1617. /* record url */
  1618. q = buf;
  1619. for(;;) {
  1620. if (c == URL_EOF || redir_isspace(c))
  1621. break;
  1622. if ((q - buf) < sizeof(buf) - 1)
  1623. *q++ = c;
  1624. c = url_fgetc(f);
  1625. }
  1626. *q = '\0';
  1627. //printf("URL='%s'\n", buf);
  1628. /* try to open the media file */
  1629. if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
  1630. break;
  1631. }
  1632. if (!ic)
  1633. return AVERROR(EIO);
  1634. *s = *ic;
  1635. url_fclose(f);
  1636. return 0;
  1637. }
  1638. AVInputFormat redir_demuxer = {
  1639. "redir",
  1640. NULL_IF_CONFIG_SMALL("Redirector format"),
  1641. 0,
  1642. redir_probe,
  1643. redir_read_header,
  1644. NULL,
  1645. NULL,
  1646. };
  1647. #endif