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.

1836 lines
60KB

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