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.

1774 lines
57KB

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