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
56KB

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