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.

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