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.

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