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.

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