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.

1827 lines
59KB

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