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.

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