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.

1831 lines
59KB

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