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.

2200 lines
74KB

  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. #include "libavutil/base64.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/random_seed.h"
  25. #include "avformat.h"
  26. #include <sys/time.h>
  27. #if HAVE_SYS_SELECT_H
  28. #include <sys/select.h>
  29. #endif
  30. #include <strings.h>
  31. #include "internal.h"
  32. #include "network.h"
  33. #include "os_support.h"
  34. #include "http.h"
  35. #include "rtsp.h"
  36. #include "rtpdec.h"
  37. #include "rdt.h"
  38. #include "rtpdec_asf.h"
  39. //#define DEBUG
  40. //#define DEBUG_RTP_TCP
  41. #if LIBAVFORMAT_VERSION_INT < (53 << 16)
  42. int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
  43. #endif
  44. /* Timeout values for socket select, in ms,
  45. * and read_packet(), in seconds */
  46. #define SELECT_TIMEOUT_MS 100
  47. #define READ_PACKET_TIMEOUT_S 10
  48. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
  49. #define SPACE_CHARS " \t\r\n"
  50. /* we use memchr() instead of strchr() here because strchr() will return
  51. * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
  52. #define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
  53. static void skip_spaces(const char **pp)
  54. {
  55. const char *p;
  56. p = *pp;
  57. while (redir_isspace(*p))
  58. p++;
  59. *pp = p;
  60. }
  61. static void get_word_until_chars(char *buf, int buf_size,
  62. const char *sep, const char **pp)
  63. {
  64. const char *p;
  65. char *q;
  66. p = *pp;
  67. skip_spaces(&p);
  68. q = buf;
  69. while (!strchr(sep, *p) && *p != '\0') {
  70. if ((q - buf) < buf_size - 1)
  71. *q++ = *p;
  72. p++;
  73. }
  74. if (buf_size > 0)
  75. *q = '\0';
  76. *pp = p;
  77. }
  78. static void get_word_sep(char *buf, int buf_size, const char *sep,
  79. const char **pp)
  80. {
  81. if (**pp == '/') (*pp)++;
  82. get_word_until_chars(buf, buf_size, sep, pp);
  83. }
  84. static void get_word(char *buf, int buf_size, const char **pp)
  85. {
  86. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  87. }
  88. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  89. static int sdp_parse_rtpmap(AVFormatContext *s,
  90. AVCodecContext *codec, RTSPStream *rtsp_st,
  91. int payload_type, const char *p)
  92. {
  93. char buf[256];
  94. int i;
  95. AVCodec *c;
  96. const char *c_name;
  97. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  98. * see if we can handle this kind of payload.
  99. * The space should normally not be there but some Real streams or
  100. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  101. * have a trailing space. */
  102. get_word_sep(buf, sizeof(buf), "/ ", &p);
  103. if (payload_type >= RTP_PT_PRIVATE) {
  104. RTPDynamicProtocolHandler *handler;
  105. for (handler = RTPFirstDynamicPayloadHandler;
  106. handler; handler = handler->next) {
  107. if (!strcasecmp(buf, handler->enc_name) &&
  108. codec->codec_type == handler->codec_type) {
  109. codec->codec_id = handler->codec_id;
  110. rtsp_st->dynamic_handler = handler;
  111. if (handler->open)
  112. rtsp_st->dynamic_protocol_context = handler->open();
  113. break;
  114. }
  115. }
  116. } else {
  117. /* We are in a standard case
  118. * (from http://www.iana.org/assignments/rtp-parameters). */
  119. /* search into AVRtpPayloadTypes[] */
  120. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  121. }
  122. c = avcodec_find_decoder(codec->codec_id);
  123. if (c && c->name)
  124. c_name = c->name;
  125. else
  126. c_name = "(null)";
  127. get_word_sep(buf, sizeof(buf), "/", &p);
  128. i = atoi(buf);
  129. switch (codec->codec_type) {
  130. case AVMEDIA_TYPE_AUDIO:
  131. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  132. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  133. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  134. if (i > 0) {
  135. codec->sample_rate = i;
  136. get_word_sep(buf, sizeof(buf), "/", &p);
  137. i = atoi(buf);
  138. if (i > 0)
  139. codec->channels = i;
  140. // TODO: there is a bug here; if it is a mono stream, and
  141. // less than 22000Hz, faad upconverts to stereo and twice
  142. // the frequency. No problem, but the sample rate is being
  143. // set here by the sdp line. Patch on its way. (rdm)
  144. }
  145. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  146. codec->sample_rate);
  147. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  148. codec->channels);
  149. break;
  150. case AVMEDIA_TYPE_VIDEO:
  151. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  152. break;
  153. default:
  154. break;
  155. }
  156. return 0;
  157. }
  158. /* return the length and optionally the data */
  159. static int hex_to_data(uint8_t *data, const char *p)
  160. {
  161. int c, len, v;
  162. len = 0;
  163. v = 1;
  164. for (;;) {
  165. skip_spaces(&p);
  166. if (*p == '\0')
  167. break;
  168. c = toupper((unsigned char) *p++);
  169. if (c >= '0' && c <= '9')
  170. c = c - '0';
  171. else if (c >= 'A' && c <= 'F')
  172. c = c - 'A' + 10;
  173. else
  174. break;
  175. v = (v << 4) | c;
  176. if (v & 0x100) {
  177. if (data)
  178. data[len] = v;
  179. len++;
  180. v = 1;
  181. }
  182. }
  183. return len;
  184. }
  185. static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
  186. char *attr, char *value)
  187. {
  188. switch (codec->codec_id) {
  189. case CODEC_ID_MPEG4:
  190. case CODEC_ID_AAC:
  191. if (!strcmp(attr, "config")) {
  192. /* decode the hexa encoded parameter */
  193. int len = hex_to_data(NULL, value);
  194. if (codec->extradata)
  195. av_free(codec->extradata);
  196. codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
  197. if (!codec->extradata)
  198. return;
  199. codec->extradata_size = len;
  200. hex_to_data(codec->extradata, value);
  201. }
  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 parameters and the corresponding 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 response. This
  233. * is broken out as a function because it is used in rtp_h264.c, which is
  234. * forthcoming. */
  235. int ff_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. char value[4096];
  255. int i;
  256. RTSPStream *rtsp_st = st->priv_data;
  257. AVCodecContext *codec = st->codec;
  258. RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
  259. /* loop on each attribute */
  260. while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
  261. value, sizeof(value))) {
  262. /* grab the codec extra_data from the config parameter of the fmtp
  263. * line */
  264. sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
  265. attr, value);
  266. /* Looking for a known attribute */
  267. for (i = 0; attr_names[i].str; ++i) {
  268. if (!strcasecmp(attr, attr_names[i].str)) {
  269. if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
  270. *(int *)((char *)rtp_payload_data +
  271. attr_names[i].offset) = atoi(value);
  272. } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
  273. *(char **)((char *)rtp_payload_data +
  274. attr_names[i].offset) = av_strdup(value);
  275. }
  276. }
  277. }
  278. }
  279. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  280. * and end time.
  281. * Used for seeking in the rtp stream.
  282. */
  283. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  284. {
  285. char buf[256];
  286. skip_spaces(&p);
  287. if (!av_stristart(p, "npt=", &p))
  288. return;
  289. *start = AV_NOPTS_VALUE;
  290. *end = AV_NOPTS_VALUE;
  291. get_word_sep(buf, sizeof(buf), "-", &p);
  292. *start = parse_date(buf, 1);
  293. if (*p == '-') {
  294. p++;
  295. get_word_sep(buf, sizeof(buf), "-", &p);
  296. *end = parse_date(buf, 1);
  297. }
  298. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  299. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  300. }
  301. typedef struct SDPParseState {
  302. /* SDP only */
  303. struct in_addr default_ip;
  304. int default_ttl;
  305. int skip_media; ///< set if an unknown m= line occurs
  306. } SDPParseState;
  307. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  308. int letter, const char *buf)
  309. {
  310. RTSPState *rt = s->priv_data;
  311. char buf1[64], st_type[64];
  312. const char *p;
  313. enum AVMediaType codec_type;
  314. int payload_type, i;
  315. AVStream *st;
  316. RTSPStream *rtsp_st;
  317. struct in_addr sdp_ip;
  318. int ttl;
  319. dprintf(s, "sdp: %c='%s'\n", letter, buf);
  320. p = buf;
  321. if (s1->skip_media && letter != 'm')
  322. return;
  323. switch (letter) {
  324. case 'c':
  325. get_word(buf1, sizeof(buf1), &p);
  326. if (strcmp(buf1, "IN") != 0)
  327. return;
  328. get_word(buf1, sizeof(buf1), &p);
  329. if (strcmp(buf1, "IP4") != 0)
  330. return;
  331. get_word_sep(buf1, sizeof(buf1), "/", &p);
  332. if (ff_inet_aton(buf1, &sdp_ip) == 0)
  333. return;
  334. ttl = 16;
  335. if (*p == '/') {
  336. p++;
  337. get_word_sep(buf1, sizeof(buf1), "/", &p);
  338. ttl = atoi(buf1);
  339. }
  340. if (s->nb_streams == 0) {
  341. s1->default_ip = sdp_ip;
  342. s1->default_ttl = ttl;
  343. } else {
  344. st = s->streams[s->nb_streams - 1];
  345. rtsp_st = st->priv_data;
  346. rtsp_st->sdp_ip = sdp_ip;
  347. rtsp_st->sdp_ttl = ttl;
  348. }
  349. break;
  350. case 's':
  351. av_metadata_set2(&s->metadata, "title", p, 0);
  352. break;
  353. case 'i':
  354. if (s->nb_streams == 0) {
  355. av_metadata_set2(&s->metadata, "comment", p, 0);
  356. break;
  357. }
  358. break;
  359. case 'm':
  360. /* new stream */
  361. s1->skip_media = 0;
  362. get_word(st_type, sizeof(st_type), &p);
  363. if (!strcmp(st_type, "audio")) {
  364. codec_type = AVMEDIA_TYPE_AUDIO;
  365. } else if (!strcmp(st_type, "video")) {
  366. codec_type = AVMEDIA_TYPE_VIDEO;
  367. } else if (!strcmp(st_type, "application")) {
  368. codec_type = AVMEDIA_TYPE_DATA;
  369. } else {
  370. s1->skip_media = 1;
  371. return;
  372. }
  373. rtsp_st = av_mallocz(sizeof(RTSPStream));
  374. if (!rtsp_st)
  375. return;
  376. rtsp_st->stream_index = -1;
  377. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  378. rtsp_st->sdp_ip = s1->default_ip;
  379. rtsp_st->sdp_ttl = s1->default_ttl;
  380. get_word(buf1, sizeof(buf1), &p); /* port */
  381. rtsp_st->sdp_port = atoi(buf1);
  382. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  383. /* XXX: handle list of formats */
  384. get_word(buf1, sizeof(buf1), &p); /* format list */
  385. rtsp_st->sdp_payload_type = atoi(buf1);
  386. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  387. /* no corresponding stream */
  388. } else {
  389. st = av_new_stream(s, 0);
  390. if (!st)
  391. return;
  392. st->priv_data = rtsp_st;
  393. rtsp_st->stream_index = st->index;
  394. st->codec->codec_type = codec_type;
  395. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  396. /* if standard payload type, we can find the codec right now */
  397. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  398. }
  399. }
  400. /* put a default control url */
  401. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  402. sizeof(rtsp_st->control_url));
  403. break;
  404. case 'a':
  405. if (av_strstart(p, "control:", &p)) {
  406. if (s->nb_streams == 0) {
  407. if (!strncmp(p, "rtsp://", 7))
  408. av_strlcpy(rt->control_uri, p,
  409. sizeof(rt->control_uri));
  410. } else {
  411. char proto[32];
  412. /* get the control url */
  413. st = s->streams[s->nb_streams - 1];
  414. rtsp_st = st->priv_data;
  415. /* XXX: may need to add full url resolution */
  416. ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  417. NULL, NULL, 0, p);
  418. if (proto[0] == '\0') {
  419. /* relative control URL */
  420. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  421. av_strlcat(rtsp_st->control_url, "/",
  422. sizeof(rtsp_st->control_url));
  423. av_strlcat(rtsp_st->control_url, p,
  424. sizeof(rtsp_st->control_url));
  425. } else
  426. av_strlcpy(rtsp_st->control_url, p,
  427. sizeof(rtsp_st->control_url));
  428. }
  429. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  430. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  431. get_word(buf1, sizeof(buf1), &p);
  432. payload_type = atoi(buf1);
  433. st = s->streams[s->nb_streams - 1];
  434. rtsp_st = st->priv_data;
  435. sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
  436. } else if (av_strstart(p, "fmtp:", &p)) {
  437. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  438. get_word(buf1, sizeof(buf1), &p);
  439. payload_type = atoi(buf1);
  440. for (i = 0; i < s->nb_streams; i++) {
  441. st = s->streams[i];
  442. rtsp_st = st->priv_data;
  443. if (rtsp_st->sdp_payload_type == payload_type) {
  444. if (!(rtsp_st->dynamic_handler &&
  445. rtsp_st->dynamic_handler->parse_sdp_a_line &&
  446. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  447. i, rtsp_st->dynamic_protocol_context, buf)))
  448. sdp_parse_fmtp(st, p);
  449. }
  450. }
  451. } else if (av_strstart(p, "framesize:", &p)) {
  452. // let dynamic protocol handlers have a stab at the line.
  453. get_word(buf1, sizeof(buf1), &p);
  454. payload_type = atoi(buf1);
  455. for (i = 0; i < s->nb_streams; i++) {
  456. st = s->streams[i];
  457. rtsp_st = st->priv_data;
  458. if (rtsp_st->sdp_payload_type == payload_type &&
  459. rtsp_st->dynamic_handler &&
  460. rtsp_st->dynamic_handler->parse_sdp_a_line)
  461. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  462. rtsp_st->dynamic_protocol_context, buf);
  463. }
  464. } else if (av_strstart(p, "range:", &p)) {
  465. int64_t start, end;
  466. // this is so that seeking on a streamed file can work.
  467. rtsp_parse_range_npt(p, &start, &end);
  468. s->start_time = start;
  469. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  470. s->duration = (end == AV_NOPTS_VALUE) ?
  471. AV_NOPTS_VALUE : end - start;
  472. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  473. if (atoi(p) == 1)
  474. rt->transport = RTSP_TRANSPORT_RDT;
  475. } else {
  476. if (rt->server_type == RTSP_SERVER_WMS)
  477. ff_wms_parse_sdp_a_line(s, p);
  478. if (s->nb_streams > 0) {
  479. if (rt->server_type == RTSP_SERVER_REAL)
  480. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  481. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  482. if (rtsp_st->dynamic_handler &&
  483. rtsp_st->dynamic_handler->parse_sdp_a_line)
  484. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  485. s->nb_streams - 1,
  486. rtsp_st->dynamic_protocol_context, buf);
  487. }
  488. }
  489. break;
  490. }
  491. }
  492. static int sdp_parse(AVFormatContext *s, const char *content)
  493. {
  494. const char *p;
  495. int letter;
  496. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  497. * contain long SDP lines containing complete ASF Headers (several
  498. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  499. * "rulebooks" describing their properties. Therefore, the SDP line
  500. * buffer is large.
  501. *
  502. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  503. * in rtpdec_xiph.c. */
  504. char buf[16384], *q;
  505. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  506. memset(s1, 0, sizeof(SDPParseState));
  507. p = content;
  508. for (;;) {
  509. skip_spaces(&p);
  510. letter = *p;
  511. if (letter == '\0')
  512. break;
  513. p++;
  514. if (*p != '=')
  515. goto next_line;
  516. p++;
  517. /* get the content */
  518. q = buf;
  519. while (*p != '\n' && *p != '\r' && *p != '\0') {
  520. if ((q - buf) < sizeof(buf) - 1)
  521. *q++ = *p;
  522. p++;
  523. }
  524. *q = '\0';
  525. sdp_parse_line(s, s1, letter, buf);
  526. next_line:
  527. while (*p != '\n' && *p != '\0')
  528. p++;
  529. if (*p == '\n')
  530. p++;
  531. }
  532. return 0;
  533. }
  534. /* close and free RTSP streams */
  535. void ff_rtsp_close_streams(AVFormatContext *s)
  536. {
  537. RTSPState *rt = s->priv_data;
  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 (s->oformat) {
  545. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  546. av_write_trailer(rtpctx);
  547. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  548. uint8_t *ptr;
  549. url_close_dyn_buf(rtpctx->pb, &ptr);
  550. av_free(ptr);
  551. } else {
  552. url_fclose(rtpctx->pb);
  553. }
  554. av_metadata_free(&rtpctx->streams[0]->metadata);
  555. av_metadata_free(&rtpctx->metadata);
  556. av_free(rtpctx->streams[0]);
  557. av_free(rtpctx);
  558. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  559. ff_rdt_parse_close(rtsp_st->transport_priv);
  560. else
  561. rtp_parse_close(rtsp_st->transport_priv);
  562. }
  563. if (rtsp_st->rtp_handle)
  564. url_close(rtsp_st->rtp_handle);
  565. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  566. rtsp_st->dynamic_handler->close(
  567. rtsp_st->dynamic_protocol_context);
  568. }
  569. }
  570. av_free(rt->rtsp_streams);
  571. if (rt->asf_ctx) {
  572. av_close_input_stream (rt->asf_ctx);
  573. rt->asf_ctx = NULL;
  574. }
  575. }
  576. static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
  577. URLContext *handle)
  578. {
  579. RTSPState *rt = s->priv_data;
  580. AVFormatContext *rtpctx;
  581. int ret;
  582. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  583. if (!rtp_format)
  584. return NULL;
  585. /* Allocate an AVFormatContext for each output stream */
  586. rtpctx = avformat_alloc_context();
  587. if (!rtpctx)
  588. return NULL;
  589. rtpctx->oformat = rtp_format;
  590. if (!av_new_stream(rtpctx, 0)) {
  591. av_free(rtpctx);
  592. return NULL;
  593. }
  594. /* Copy the max delay setting; the rtp muxer reads this. */
  595. rtpctx->max_delay = s->max_delay;
  596. /* Copy other stream parameters. */
  597. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  598. /* Set the synchronized start time. */
  599. rtpctx->start_time_realtime = rt->start_time;
  600. /* Remove the local codec, link to the original codec
  601. * context instead, to give the rtp muxer access to
  602. * codec parameters. */
  603. av_free(rtpctx->streams[0]->codec);
  604. rtpctx->streams[0]->codec = st->codec;
  605. if (handle) {
  606. url_fdopen(&rtpctx->pb, handle);
  607. } else
  608. url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
  609. ret = av_write_header(rtpctx);
  610. if (ret) {
  611. if (handle) {
  612. url_fclose(rtpctx->pb);
  613. } else {
  614. uint8_t *ptr;
  615. url_close_dyn_buf(rtpctx->pb, &ptr);
  616. av_free(ptr);
  617. }
  618. av_free(rtpctx->streams[0]);
  619. av_free(rtpctx);
  620. return NULL;
  621. }
  622. /* Copy the RTP AVStream timebase back to the original AVStream */
  623. st->time_base = rtpctx->streams[0]->time_base;
  624. return rtpctx;
  625. }
  626. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  627. {
  628. RTSPState *rt = s->priv_data;
  629. AVStream *st = NULL;
  630. /* open the RTP context */
  631. if (rtsp_st->stream_index >= 0)
  632. st = s->streams[rtsp_st->stream_index];
  633. if (!st)
  634. s->ctx_flags |= AVFMTCTX_NOHEADER;
  635. if (s->oformat) {
  636. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  637. /* Ownership of rtp_handle is passed to the rtp mux context */
  638. rtsp_st->rtp_handle = NULL;
  639. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  640. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  641. rtsp_st->dynamic_protocol_context,
  642. rtsp_st->dynamic_handler);
  643. else
  644. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  645. rtsp_st->sdp_payload_type,
  646. &rtsp_st->rtp_payload_data);
  647. if (!rtsp_st->transport_priv) {
  648. return AVERROR(ENOMEM);
  649. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  650. if (rtsp_st->dynamic_handler) {
  651. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  652. rtsp_st->dynamic_protocol_context,
  653. rtsp_st->dynamic_handler);
  654. }
  655. }
  656. return 0;
  657. }
  658. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  659. static int rtsp_probe(AVProbeData *p)
  660. {
  661. if (av_strstart(p->filename, "rtsp:", NULL))
  662. return AVPROBE_SCORE_MAX;
  663. return 0;
  664. }
  665. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  666. {
  667. const char *p;
  668. int v;
  669. p = *pp;
  670. skip_spaces(&p);
  671. v = strtol(p, (char **)&p, 10);
  672. if (*p == '-') {
  673. p++;
  674. *min_ptr = v;
  675. v = strtol(p, (char **)&p, 10);
  676. *max_ptr = v;
  677. } else {
  678. *min_ptr = v;
  679. *max_ptr = v;
  680. }
  681. *pp = p;
  682. }
  683. /* XXX: only one transport specification is parsed */
  684. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  685. {
  686. char transport_protocol[16];
  687. char profile[16];
  688. char lower_transport[16];
  689. char parameter[16];
  690. RTSPTransportField *th;
  691. char buf[256];
  692. reply->nb_transports = 0;
  693. for (;;) {
  694. skip_spaces(&p);
  695. if (*p == '\0')
  696. break;
  697. th = &reply->transports[reply->nb_transports];
  698. get_word_sep(transport_protocol, sizeof(transport_protocol),
  699. "/", &p);
  700. if (!strcasecmp (transport_protocol, "rtp")) {
  701. get_word_sep(profile, sizeof(profile), "/;,", &p);
  702. lower_transport[0] = '\0';
  703. /* rtp/avp/<protocol> */
  704. if (*p == '/') {
  705. get_word_sep(lower_transport, sizeof(lower_transport),
  706. ";,", &p);
  707. }
  708. th->transport = RTSP_TRANSPORT_RTP;
  709. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  710. !strcasecmp (transport_protocol, "x-real-rdt")) {
  711. /* x-pn-tng/<protocol> */
  712. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  713. profile[0] = '\0';
  714. th->transport = RTSP_TRANSPORT_RDT;
  715. }
  716. if (!strcasecmp(lower_transport, "TCP"))
  717. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  718. else
  719. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  720. if (*p == ';')
  721. p++;
  722. /* get each parameter */
  723. while (*p != '\0' && *p != ',') {
  724. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  725. if (!strcmp(parameter, "port")) {
  726. if (*p == '=') {
  727. p++;
  728. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  729. }
  730. } else if (!strcmp(parameter, "client_port")) {
  731. if (*p == '=') {
  732. p++;
  733. rtsp_parse_range(&th->client_port_min,
  734. &th->client_port_max, &p);
  735. }
  736. } else if (!strcmp(parameter, "server_port")) {
  737. if (*p == '=') {
  738. p++;
  739. rtsp_parse_range(&th->server_port_min,
  740. &th->server_port_max, &p);
  741. }
  742. } else if (!strcmp(parameter, "interleaved")) {
  743. if (*p == '=') {
  744. p++;
  745. rtsp_parse_range(&th->interleaved_min,
  746. &th->interleaved_max, &p);
  747. }
  748. } else if (!strcmp(parameter, "multicast")) {
  749. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  750. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  751. } else if (!strcmp(parameter, "ttl")) {
  752. if (*p == '=') {
  753. p++;
  754. th->ttl = strtol(p, (char **)&p, 10);
  755. }
  756. } else if (!strcmp(parameter, "destination")) {
  757. struct in_addr ipaddr;
  758. if (*p == '=') {
  759. p++;
  760. get_word_sep(buf, sizeof(buf), ";,", &p);
  761. if (ff_inet_aton(buf, &ipaddr))
  762. th->destination = ntohl(ipaddr.s_addr);
  763. }
  764. }
  765. while (*p != ';' && *p != '\0' && *p != ',')
  766. p++;
  767. if (*p == ';')
  768. p++;
  769. }
  770. if (*p == ',')
  771. p++;
  772. reply->nb_transports++;
  773. }
  774. }
  775. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  776. HTTPAuthState *auth_state)
  777. {
  778. const char *p;
  779. /* NOTE: we do case independent match for broken servers */
  780. p = buf;
  781. if (av_stristart(p, "Session:", &p)) {
  782. int t;
  783. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  784. if (av_stristart(p, ";timeout=", &p) &&
  785. (t = strtol(p, NULL, 10)) > 0) {
  786. reply->timeout = t;
  787. }
  788. } else if (av_stristart(p, "Content-Length:", &p)) {
  789. reply->content_length = strtol(p, NULL, 10);
  790. } else if (av_stristart(p, "Transport:", &p)) {
  791. rtsp_parse_transport(reply, p);
  792. } else if (av_stristart(p, "CSeq:", &p)) {
  793. reply->seq = strtol(p, NULL, 10);
  794. } else if (av_stristart(p, "Range:", &p)) {
  795. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  796. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  797. skip_spaces(&p);
  798. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  799. } else if (av_stristart(p, "Server:", &p)) {
  800. skip_spaces(&p);
  801. av_strlcpy(reply->server, p, sizeof(reply->server));
  802. } else if (av_stristart(p, "Notice:", &p) ||
  803. av_stristart(p, "X-Notice:", &p)) {
  804. reply->notice = strtol(p, NULL, 10);
  805. } else if (av_stristart(p, "Location:", &p)) {
  806. skip_spaces(&p);
  807. av_strlcpy(reply->location, p , sizeof(reply->location));
  808. } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
  809. skip_spaces(&p);
  810. ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
  811. } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
  812. skip_spaces(&p);
  813. ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
  814. }
  815. }
  816. /* skip a RTP/TCP interleaved packet */
  817. void ff_rtsp_skip_packet(AVFormatContext *s)
  818. {
  819. RTSPState *rt = s->priv_data;
  820. int ret, len, len1;
  821. uint8_t buf[1024];
  822. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  823. if (ret != 3)
  824. return;
  825. len = AV_RB16(buf + 1);
  826. dprintf(s, "skipping RTP packet len=%d\n", len);
  827. /* skip payload */
  828. while (len > 0) {
  829. len1 = len;
  830. if (len1 > sizeof(buf))
  831. len1 = sizeof(buf);
  832. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  833. if (ret != len1)
  834. return;
  835. len -= len1;
  836. }
  837. }
  838. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  839. unsigned char **content_ptr,
  840. int return_on_interleaved_data)
  841. {
  842. RTSPState *rt = s->priv_data;
  843. char buf[4096], buf1[1024], *q;
  844. unsigned char ch;
  845. const char *p;
  846. int ret, content_length, line_count = 0;
  847. unsigned char *content = NULL;
  848. memset(reply, 0, sizeof(*reply));
  849. /* parse reply (XXX: use buffers) */
  850. rt->last_reply[0] = '\0';
  851. for (;;) {
  852. q = buf;
  853. for (;;) {
  854. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  855. #ifdef DEBUG_RTP_TCP
  856. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  857. #endif
  858. if (ret != 1)
  859. return -1;
  860. if (ch == '\n')
  861. break;
  862. if (ch == '$') {
  863. /* XXX: only parse it if first char on line ? */
  864. if (return_on_interleaved_data) {
  865. return 1;
  866. } else
  867. ff_rtsp_skip_packet(s);
  868. } else if (ch != '\r') {
  869. if ((q - buf) < sizeof(buf) - 1)
  870. *q++ = ch;
  871. }
  872. }
  873. *q = '\0';
  874. dprintf(s, "line='%s'\n", buf);
  875. /* test if last line */
  876. if (buf[0] == '\0')
  877. break;
  878. p = buf;
  879. if (line_count == 0) {
  880. /* get reply code */
  881. get_word(buf1, sizeof(buf1), &p);
  882. get_word(buf1, sizeof(buf1), &p);
  883. reply->status_code = atoi(buf1);
  884. } else {
  885. ff_rtsp_parse_line(reply, p, &rt->auth_state);
  886. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  887. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  888. }
  889. line_count++;
  890. }
  891. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  892. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  893. content_length = reply->content_length;
  894. if (content_length > 0) {
  895. /* leave some room for a trailing '\0' (useful for simple parsing) */
  896. content = av_malloc(content_length + 1);
  897. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  898. content[content_length] = '\0';
  899. }
  900. if (content_ptr)
  901. *content_ptr = content;
  902. else
  903. av_free(content);
  904. if (rt->seq != reply->seq) {
  905. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  906. rt->seq, reply->seq);
  907. }
  908. /* EOS */
  909. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  910. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  911. reply->notice == 2306 /* Continuous Feed Terminated */) {
  912. rt->state = RTSP_STATE_IDLE;
  913. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  914. return AVERROR(EIO); /* data or server error */
  915. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  916. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  917. return AVERROR(EPERM);
  918. return 0;
  919. }
  920. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  921. const char *method, const char *url,
  922. const char *headers,
  923. const unsigned char *send_content,
  924. int send_content_length)
  925. {
  926. RTSPState *rt = s->priv_data;
  927. char buf[4096], *out_buf;
  928. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  929. /* Add in RTSP headers */
  930. out_buf = buf;
  931. rt->seq++;
  932. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  933. if (headers)
  934. av_strlcat(buf, headers, sizeof(buf));
  935. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  936. if (rt->session_id[0] != '\0' && (!headers ||
  937. !strstr(headers, "\nIf-Match:"))) {
  938. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  939. }
  940. if (rt->auth[0]) {
  941. char *str = ff_http_auth_create_response(&rt->auth_state,
  942. rt->auth, url, method);
  943. if (str)
  944. av_strlcat(buf, str, sizeof(buf));
  945. av_free(str);
  946. }
  947. if (send_content_length > 0 && send_content)
  948. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  949. av_strlcat(buf, "\r\n", sizeof(buf));
  950. /* base64 encode rtsp if tunneling */
  951. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  952. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  953. out_buf = base64buf;
  954. }
  955. dprintf(s, "Sending:\n%s--\n", buf);
  956. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  957. if (send_content_length > 0 && send_content) {
  958. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  959. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  960. "with content data not supported\n");
  961. return AVERROR_PATCHWELCOME;
  962. }
  963. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  964. }
  965. rt->last_cmd_time = av_gettime();
  966. return 0;
  967. }
  968. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  969. const char *url, const char *headers)
  970. {
  971. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  972. }
  973. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  974. const char *headers, RTSPMessageHeader *reply,
  975. unsigned char **content_ptr)
  976. {
  977. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  978. content_ptr, NULL, 0);
  979. }
  980. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  981. const char *method, const char *url,
  982. const char *header,
  983. RTSPMessageHeader *reply,
  984. unsigned char **content_ptr,
  985. const unsigned char *send_content,
  986. int send_content_length)
  987. {
  988. RTSPState *rt = s->priv_data;
  989. HTTPAuthType cur_auth_type;
  990. int ret;
  991. retry:
  992. cur_auth_type = rt->auth_state.auth_type;
  993. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  994. send_content,
  995. send_content_length)))
  996. return ret;
  997. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
  998. return ret;
  999. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  1000. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  1001. goto retry;
  1002. return 0;
  1003. }
  1004. /**
  1005. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  1006. */
  1007. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  1008. int lower_transport, const char *real_challenge)
  1009. {
  1010. RTSPState *rt = s->priv_data;
  1011. int rtx, j, i, err, interleave = 0;
  1012. RTSPStream *rtsp_st;
  1013. RTSPMessageHeader reply1, *reply = &reply1;
  1014. char cmd[2048];
  1015. const char *trans_pref;
  1016. if (rt->transport == RTSP_TRANSPORT_RDT)
  1017. trans_pref = "x-pn-tng";
  1018. else
  1019. trans_pref = "RTP/AVP";
  1020. /* default timeout: 1 minute */
  1021. rt->timeout = 60;
  1022. /* for each stream, make the setup request */
  1023. /* XXX: we assume the same server is used for the control of each
  1024. * RTSP stream */
  1025. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  1026. char transport[2048];
  1027. /**
  1028. * WMS serves all UDP data over a single connection, the RTX, which
  1029. * isn't necessarily the first in the SDP but has to be the first
  1030. * to be set up, else the second/third SETUP will fail with a 461.
  1031. */
  1032. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  1033. rt->server_type == RTSP_SERVER_WMS) {
  1034. if (i == 0) {
  1035. /* rtx first */
  1036. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  1037. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  1038. if (len >= 4 &&
  1039. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  1040. "/rtx"))
  1041. break;
  1042. }
  1043. if (rtx == rt->nb_rtsp_streams)
  1044. return -1; /* no RTX found */
  1045. rtsp_st = rt->rtsp_streams[rtx];
  1046. } else
  1047. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  1048. } else
  1049. rtsp_st = rt->rtsp_streams[i];
  1050. /* RTP/UDP */
  1051. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  1052. char buf[256];
  1053. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  1054. port = reply->transports[0].client_port_min;
  1055. goto have_port;
  1056. }
  1057. /* first try in specified port range */
  1058. if (RTSP_RTP_PORT_MIN != 0) {
  1059. while (j <= RTSP_RTP_PORT_MAX) {
  1060. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  1061. "?localport=%d", j);
  1062. /* we will use two ports per rtp stream (rtp and rtcp) */
  1063. j += 2;
  1064. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  1065. goto rtp_opened;
  1066. }
  1067. }
  1068. #if 0
  1069. /* then try on any port */
  1070. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  1071. err = AVERROR_INVALIDDATA;
  1072. goto fail;
  1073. }
  1074. #endif
  1075. rtp_opened:
  1076. port = rtp_get_local_port(rtsp_st->rtp_handle);
  1077. have_port:
  1078. snprintf(transport, sizeof(transport) - 1,
  1079. "%s/UDP;", trans_pref);
  1080. if (rt->server_type != RTSP_SERVER_REAL)
  1081. av_strlcat(transport, "unicast;", sizeof(transport));
  1082. av_strlcatf(transport, sizeof(transport),
  1083. "client_port=%d", port);
  1084. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1085. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1086. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1087. }
  1088. /* RTP/TCP */
  1089. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1090. /** For WMS streams, the application streams are only used for
  1091. * UDP. When trying to set it up for TCP streams, the server
  1092. * will return an error. Therefore, we skip those streams. */
  1093. if (rt->server_type == RTSP_SERVER_WMS &&
  1094. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1095. AVMEDIA_TYPE_DATA)
  1096. continue;
  1097. snprintf(transport, sizeof(transport) - 1,
  1098. "%s/TCP;", trans_pref);
  1099. if (rt->server_type == RTSP_SERVER_WMS)
  1100. av_strlcat(transport, "unicast;", sizeof(transport));
  1101. av_strlcatf(transport, sizeof(transport),
  1102. "interleaved=%d-%d",
  1103. interleave, interleave + 1);
  1104. interleave += 2;
  1105. }
  1106. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1107. snprintf(transport, sizeof(transport) - 1,
  1108. "%s/UDP;multicast", trans_pref);
  1109. }
  1110. if (s->oformat) {
  1111. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1112. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1113. rt->server_type == RTSP_SERVER_WMS)
  1114. av_strlcat(transport, ";mode=play", sizeof(transport));
  1115. snprintf(cmd, sizeof(cmd),
  1116. "Transport: %s\r\n",
  1117. transport);
  1118. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  1119. char real_res[41], real_csum[9];
  1120. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1121. real_challenge);
  1122. av_strlcatf(cmd, sizeof(cmd),
  1123. "If-Match: %s\r\n"
  1124. "RealChallenge2: %s, sd=%s\r\n",
  1125. rt->session_id, real_res, real_csum);
  1126. }
  1127. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1128. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1129. err = 1;
  1130. goto fail;
  1131. } else if (reply->status_code != RTSP_STATUS_OK ||
  1132. reply->nb_transports != 1) {
  1133. err = AVERROR_INVALIDDATA;
  1134. goto fail;
  1135. }
  1136. /* XXX: same protocol for all streams is required */
  1137. if (i > 0) {
  1138. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1139. reply->transports[0].transport != rt->transport) {
  1140. err = AVERROR_INVALIDDATA;
  1141. goto fail;
  1142. }
  1143. } else {
  1144. rt->lower_transport = reply->transports[0].lower_transport;
  1145. rt->transport = reply->transports[0].transport;
  1146. }
  1147. /* close RTP connection if not choosen */
  1148. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1149. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1150. url_close(rtsp_st->rtp_handle);
  1151. rtsp_st->rtp_handle = NULL;
  1152. }
  1153. switch(reply->transports[0].lower_transport) {
  1154. case RTSP_LOWER_TRANSPORT_TCP:
  1155. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1156. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1157. break;
  1158. case RTSP_LOWER_TRANSPORT_UDP: {
  1159. char url[1024];
  1160. /* XXX: also use address if specified */
  1161. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1162. reply->transports[0].server_port_min, NULL);
  1163. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1164. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1165. err = AVERROR_INVALIDDATA;
  1166. goto fail;
  1167. }
  1168. /* Try to initialize the connection state in a
  1169. * potential NAT router by sending dummy packets.
  1170. * RTP/RTCP dummy packets are used for RDT, too.
  1171. */
  1172. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1173. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1174. break;
  1175. }
  1176. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1177. char url[1024];
  1178. struct in_addr in;
  1179. int port, ttl;
  1180. if (reply->transports[0].destination) {
  1181. in.s_addr = htonl(reply->transports[0].destination);
  1182. port = reply->transports[0].port_min;
  1183. ttl = reply->transports[0].ttl;
  1184. } else {
  1185. in = rtsp_st->sdp_ip;
  1186. port = rtsp_st->sdp_port;
  1187. ttl = rtsp_st->sdp_ttl;
  1188. }
  1189. ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
  1190. port, "?ttl=%d", ttl);
  1191. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1192. err = AVERROR_INVALIDDATA;
  1193. goto fail;
  1194. }
  1195. break;
  1196. }
  1197. }
  1198. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1199. goto fail;
  1200. }
  1201. if (reply->timeout > 0)
  1202. rt->timeout = reply->timeout;
  1203. if (rt->server_type == RTSP_SERVER_REAL)
  1204. rt->need_subscription = 1;
  1205. return 0;
  1206. fail:
  1207. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1208. if (rt->rtsp_streams[i]->rtp_handle) {
  1209. url_close(rt->rtsp_streams[i]->rtp_handle);
  1210. rt->rtsp_streams[i]->rtp_handle = NULL;
  1211. }
  1212. }
  1213. return err;
  1214. }
  1215. static int rtsp_read_play(AVFormatContext *s)
  1216. {
  1217. RTSPState *rt = s->priv_data;
  1218. RTSPMessageHeader reply1, *reply = &reply1;
  1219. int i;
  1220. char cmd[1024];
  1221. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1222. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1223. if (rt->state == RTSP_STATE_PAUSED) {
  1224. cmd[0] = 0;
  1225. } else {
  1226. snprintf(cmd, sizeof(cmd),
  1227. "Range: npt=%0.3f-\r\n",
  1228. (double)rt->seek_timestamp / AV_TIME_BASE);
  1229. }
  1230. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  1231. if (reply->status_code != RTSP_STATUS_OK) {
  1232. return -1;
  1233. }
  1234. if (reply->range_start != AV_NOPTS_VALUE &&
  1235. rt->transport == RTSP_TRANSPORT_RTP) {
  1236. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1237. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  1238. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1239. AVStream *st = NULL;
  1240. if (!rtpctx)
  1241. continue;
  1242. if (rtsp_st->stream_index >= 0)
  1243. st = s->streams[rtsp_st->stream_index];
  1244. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  1245. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  1246. if (st)
  1247. rtpctx->range_start_offset = av_rescale_q(reply->range_start,
  1248. AV_TIME_BASE_Q,
  1249. st->time_base);
  1250. }
  1251. }
  1252. }
  1253. rt->state = RTSP_STATE_STREAMING;
  1254. return 0;
  1255. }
  1256. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1257. {
  1258. RTSPState *rt = s->priv_data;
  1259. char cmd[1024];
  1260. unsigned char *content = NULL;
  1261. int ret;
  1262. /* describe the stream */
  1263. snprintf(cmd, sizeof(cmd),
  1264. "Accept: application/sdp\r\n");
  1265. if (rt->server_type == RTSP_SERVER_REAL) {
  1266. /**
  1267. * The Require: attribute is needed for proper streaming from
  1268. * Realmedia servers.
  1269. */
  1270. av_strlcat(cmd,
  1271. "Require: com.real.retain-entity-for-setup\r\n",
  1272. sizeof(cmd));
  1273. }
  1274. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  1275. if (!content)
  1276. return AVERROR_INVALIDDATA;
  1277. if (reply->status_code != RTSP_STATUS_OK) {
  1278. av_freep(&content);
  1279. return AVERROR_INVALIDDATA;
  1280. }
  1281. /* now we got the SDP description, we parse it */
  1282. ret = sdp_parse(s, (const char *)content);
  1283. av_freep(&content);
  1284. if (ret < 0)
  1285. return AVERROR_INVALIDDATA;
  1286. return 0;
  1287. }
  1288. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1289. {
  1290. RTSPState *rt = s->priv_data;
  1291. RTSPMessageHeader reply1, *reply = &reply1;
  1292. int i;
  1293. char *sdp;
  1294. AVFormatContext sdp_ctx, *ctx_array[1];
  1295. rt->start_time = av_gettime();
  1296. /* Announce the stream */
  1297. sdp = av_mallocz(8192);
  1298. if (sdp == NULL)
  1299. return AVERROR(ENOMEM);
  1300. /* We create the SDP based on the RTSP AVFormatContext where we
  1301. * aren't allowed to change the filename field. (We create the SDP
  1302. * based on the RTSP context since the contexts for the RTP streams
  1303. * don't exist yet.) In order to specify a custom URL with the actual
  1304. * peer IP instead of the originally specified hostname, we create
  1305. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1306. *
  1307. * FIXME: Create the SDP without copying the AVFormatContext.
  1308. * This either requires setting up the RTP stream AVFormatContexts
  1309. * already here (complicating things immensely) or getting a more
  1310. * flexible SDP creation interface.
  1311. */
  1312. sdp_ctx = *s;
  1313. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1314. "rtsp", NULL, addr, -1, NULL);
  1315. ctx_array[0] = &sdp_ctx;
  1316. if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
  1317. av_free(sdp);
  1318. return AVERROR_INVALIDDATA;
  1319. }
  1320. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1321. ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
  1322. "Content-Type: application/sdp\r\n",
  1323. reply, NULL, sdp, strlen(sdp));
  1324. av_free(sdp);
  1325. if (reply->status_code != RTSP_STATUS_OK)
  1326. return AVERROR_INVALIDDATA;
  1327. /* Set up the RTSPStreams for each AVStream */
  1328. for (i = 0; i < s->nb_streams; i++) {
  1329. RTSPStream *rtsp_st;
  1330. AVStream *st = s->streams[i];
  1331. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1332. if (!rtsp_st)
  1333. return AVERROR(ENOMEM);
  1334. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1335. st->priv_data = rtsp_st;
  1336. rtsp_st->stream_index = i;
  1337. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1338. /* Note, this must match the relative uri set in the sdp content */
  1339. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1340. "/streamid=%d", i);
  1341. }
  1342. return 0;
  1343. }
  1344. void ff_rtsp_close_connections(AVFormatContext *s)
  1345. {
  1346. RTSPState *rt = s->priv_data;
  1347. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1348. url_close(rt->rtsp_hd);
  1349. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1350. }
  1351. int ff_rtsp_connect(AVFormatContext *s)
  1352. {
  1353. RTSPState *rt = s->priv_data;
  1354. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1355. char *option_list, *option, *filename;
  1356. int port, err, tcp_fd;
  1357. RTSPMessageHeader reply1 = {}, *reply = &reply1;
  1358. int lower_transport_mask = 0;
  1359. char real_challenge[64];
  1360. struct sockaddr_storage peer;
  1361. socklen_t peer_len = sizeof(peer);
  1362. if (!ff_network_init())
  1363. return AVERROR(EIO);
  1364. redirect:
  1365. rt->control_transport = RTSP_MODE_PLAIN;
  1366. /* extract hostname and port */
  1367. ff_url_split(NULL, 0, auth, sizeof(auth),
  1368. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1369. if (*auth) {
  1370. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1371. }
  1372. if (port < 0)
  1373. port = RTSP_DEFAULT_PORT;
  1374. /* search for options */
  1375. option_list = strrchr(path, '?');
  1376. if (option_list) {
  1377. /* Strip out the RTSP specific options, write out the rest of
  1378. * the options back into the same string. */
  1379. filename = option_list;
  1380. while (option_list) {
  1381. /* move the option pointer */
  1382. option = ++option_list;
  1383. option_list = strchr(option_list, '&');
  1384. if (option_list)
  1385. *option_list = 0;
  1386. /* handle the options */
  1387. if (!strcmp(option, "udp")) {
  1388. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1389. } else if (!strcmp(option, "multicast")) {
  1390. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1391. } else if (!strcmp(option, "tcp")) {
  1392. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1393. } else if(!strcmp(option, "http")) {
  1394. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1395. rt->control_transport = RTSP_MODE_TUNNEL;
  1396. } else {
  1397. /* Write options back into the buffer, using memmove instead
  1398. * of strcpy since the strings may overlap. */
  1399. int len = strlen(option);
  1400. memmove(++filename, option, len);
  1401. filename += len;
  1402. if (option_list) *filename = '&';
  1403. }
  1404. }
  1405. *filename = 0;
  1406. }
  1407. if (!lower_transport_mask)
  1408. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1409. if (s->oformat) {
  1410. /* Only UDP or TCP - UDP multicast isn't supported. */
  1411. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1412. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1413. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1414. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1415. "only UDP and TCP are supported for output.\n");
  1416. err = AVERROR(EINVAL);
  1417. goto fail;
  1418. }
  1419. }
  1420. /* Construct the URI used in request; this is similar to s->filename,
  1421. * but with authentication credentials removed and RTSP specific options
  1422. * stripped out. */
  1423. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1424. host, port, "%s", path);
  1425. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1426. /* set up initial handshake for tunneling */
  1427. char httpname[1024];
  1428. char sessioncookie[17];
  1429. char headers[1024];
  1430. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1431. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1432. av_get_random_seed(), av_get_random_seed());
  1433. /* GET requests */
  1434. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1435. err = AVERROR(EIO);
  1436. goto fail;
  1437. }
  1438. /* generate GET headers */
  1439. snprintf(headers, sizeof(headers),
  1440. "x-sessioncookie: %s\r\n"
  1441. "Accept: application/x-rtsp-tunnelled\r\n"
  1442. "Pragma: no-cache\r\n"
  1443. "Cache-Control: no-cache\r\n",
  1444. sessioncookie);
  1445. ff_http_set_headers(rt->rtsp_hd, headers);
  1446. /* complete the connection */
  1447. if (url_connect(rt->rtsp_hd)) {
  1448. err = AVERROR(EIO);
  1449. goto fail;
  1450. }
  1451. /* POST requests */
  1452. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1453. err = AVERROR(EIO);
  1454. goto fail;
  1455. }
  1456. /* generate POST headers */
  1457. snprintf(headers, sizeof(headers),
  1458. "x-sessioncookie: %s\r\n"
  1459. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1460. "Pragma: no-cache\r\n"
  1461. "Cache-Control: no-cache\r\n"
  1462. "Content-Length: 32767\r\n"
  1463. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1464. sessioncookie);
  1465. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1466. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1467. /* Initialize the authentication state for the POST session. The HTTP
  1468. * protocol implementation doesn't properly handle multi-pass
  1469. * authentication for POST requests, since it would require one of
  1470. * the following:
  1471. * - implementing Expect: 100-continue, which many HTTP servers
  1472. * don't support anyway, even less the RTSP servers that do HTTP
  1473. * tunneling
  1474. * - sending the whole POST data until getting a 401 reply specifying
  1475. * what authentication method to use, then resending all that data
  1476. * - waiting for potential 401 replies directly after sending the
  1477. * POST header (waiting for some unspecified time)
  1478. * Therefore, we copy the full auth state, which works for both basic
  1479. * and digest. (For digest, we would have to synchronize the nonce
  1480. * count variable between the two sessions, if we'd do more requests
  1481. * with the original session, though.)
  1482. */
  1483. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1484. /* complete the connection */
  1485. if (url_connect(rt->rtsp_hd_out)) {
  1486. err = AVERROR(EIO);
  1487. goto fail;
  1488. }
  1489. } else {
  1490. /* open the tcp connection */
  1491. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1492. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1493. err = AVERROR(EIO);
  1494. goto fail;
  1495. }
  1496. rt->rtsp_hd_out = rt->rtsp_hd;
  1497. }
  1498. rt->seq = 0;
  1499. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1500. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1501. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1502. NULL, 0, NI_NUMERICHOST);
  1503. }
  1504. /* request options supported by the server; this also detects server
  1505. * type */
  1506. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1507. cmd[0] = 0;
  1508. if (rt->server_type == RTSP_SERVER_REAL)
  1509. av_strlcat(cmd,
  1510. /**
  1511. * The following entries are required for proper
  1512. * streaming from a Realmedia server. They are
  1513. * interdependent in some way although we currently
  1514. * don't quite understand how. Values were copied
  1515. * from mplayer SVN r23589.
  1516. * @param CompanyID is a 16-byte ID in base64
  1517. * @param ClientChallenge is a 16-byte ID in hex
  1518. */
  1519. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1520. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1521. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1522. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1523. sizeof(cmd));
  1524. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1525. if (reply->status_code != RTSP_STATUS_OK) {
  1526. err = AVERROR_INVALIDDATA;
  1527. goto fail;
  1528. }
  1529. /* detect server type if not standard-compliant RTP */
  1530. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1531. rt->server_type = RTSP_SERVER_REAL;
  1532. continue;
  1533. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1534. rt->server_type = RTSP_SERVER_WMS;
  1535. } else if (rt->server_type == RTSP_SERVER_REAL)
  1536. strcpy(real_challenge, reply->real_challenge);
  1537. break;
  1538. }
  1539. if (s->iformat)
  1540. err = rtsp_setup_input_streams(s, reply);
  1541. else
  1542. err = rtsp_setup_output_streams(s, host);
  1543. if (err)
  1544. goto fail;
  1545. do {
  1546. int lower_transport = ff_log2_tab[lower_transport_mask &
  1547. ~(lower_transport_mask - 1)];
  1548. err = make_setup_request(s, host, port, lower_transport,
  1549. rt->server_type == RTSP_SERVER_REAL ?
  1550. real_challenge : NULL);
  1551. if (err < 0)
  1552. goto fail;
  1553. lower_transport_mask &= ~(1 << lower_transport);
  1554. if (lower_transport_mask == 0 && err == 1) {
  1555. err = FF_NETERROR(EPROTONOSUPPORT);
  1556. goto fail;
  1557. }
  1558. } while (err);
  1559. rt->state = RTSP_STATE_IDLE;
  1560. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1561. return 0;
  1562. fail:
  1563. ff_rtsp_close_streams(s);
  1564. ff_rtsp_close_connections(s);
  1565. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1566. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1567. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1568. reply->status_code,
  1569. s->filename);
  1570. goto redirect;
  1571. }
  1572. ff_network_close();
  1573. return err;
  1574. }
  1575. #endif
  1576. #if CONFIG_RTSP_DEMUXER
  1577. static int rtsp_read_header(AVFormatContext *s,
  1578. AVFormatParameters *ap)
  1579. {
  1580. int ret;
  1581. ret = ff_rtsp_connect(s);
  1582. if (ret)
  1583. return ret;
  1584. if (ap->initial_pause) {
  1585. /* do not start immediately */
  1586. } else {
  1587. if (rtsp_read_play(s) < 0) {
  1588. ff_rtsp_close_streams(s);
  1589. ff_rtsp_close_connections(s);
  1590. return AVERROR_INVALIDDATA;
  1591. }
  1592. }
  1593. return 0;
  1594. }
  1595. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1596. uint8_t *buf, int buf_size)
  1597. {
  1598. RTSPState *rt = s->priv_data;
  1599. RTSPStream *rtsp_st;
  1600. fd_set rfds;
  1601. int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1602. struct timeval tv;
  1603. for (;;) {
  1604. if (url_interrupt_cb())
  1605. return AVERROR(EINTR);
  1606. FD_ZERO(&rfds);
  1607. if (rt->rtsp_hd) {
  1608. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1609. FD_SET(tcp_fd, &rfds);
  1610. } else {
  1611. fd_max = 0;
  1612. tcp_fd = -1;
  1613. }
  1614. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1615. rtsp_st = rt->rtsp_streams[i];
  1616. if (rtsp_st->rtp_handle) {
  1617. /* currently, we cannot probe RTCP handle because of
  1618. * blocking restrictions */
  1619. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1620. if (fd > fd_max)
  1621. fd_max = fd;
  1622. FD_SET(fd, &rfds);
  1623. }
  1624. }
  1625. tv.tv_sec = 0;
  1626. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1627. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1628. if (n > 0) {
  1629. timeout_cnt = 0;
  1630. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1631. rtsp_st = rt->rtsp_streams[i];
  1632. if (rtsp_st->rtp_handle) {
  1633. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1634. if (FD_ISSET(fd, &rfds)) {
  1635. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1636. if (ret > 0) {
  1637. *prtsp_st = rtsp_st;
  1638. return ret;
  1639. }
  1640. }
  1641. }
  1642. }
  1643. #if CONFIG_RTSP_DEMUXER
  1644. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1645. RTSPMessageHeader reply;
  1646. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1647. if (ret < 0)
  1648. return ret;
  1649. /* XXX: parse message */
  1650. if (rt->state != RTSP_STATE_STREAMING)
  1651. return 0;
  1652. }
  1653. #endif
  1654. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1655. return FF_NETERROR(ETIMEDOUT);
  1656. } else if (n < 0 && errno != EINTR)
  1657. return AVERROR(errno);
  1658. }
  1659. }
  1660. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1661. uint8_t *buf, int buf_size)
  1662. {
  1663. RTSPState *rt = s->priv_data;
  1664. int id, len, i, ret;
  1665. RTSPStream *rtsp_st;
  1666. #ifdef DEBUG_RTP_TCP
  1667. dprintf(s, "tcp_read_packet:\n");
  1668. #endif
  1669. redo:
  1670. for (;;) {
  1671. RTSPMessageHeader reply;
  1672. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1673. if (ret == -1)
  1674. return -1;
  1675. if (ret == 1) /* received '$' */
  1676. break;
  1677. /* XXX: parse message */
  1678. if (rt->state != RTSP_STATE_STREAMING)
  1679. return 0;
  1680. }
  1681. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1682. if (ret != 3)
  1683. return -1;
  1684. id = buf[0];
  1685. len = AV_RB16(buf + 1);
  1686. #ifdef DEBUG_RTP_TCP
  1687. dprintf(s, "id=%d len=%d\n", id, len);
  1688. #endif
  1689. if (len > buf_size || len < 12)
  1690. goto redo;
  1691. /* get the data */
  1692. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1693. if (ret != len)
  1694. return -1;
  1695. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1696. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1697. return -1;
  1698. /* find the matching stream */
  1699. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1700. rtsp_st = rt->rtsp_streams[i];
  1701. if (id >= rtsp_st->interleaved_min &&
  1702. id <= rtsp_st->interleaved_max)
  1703. goto found;
  1704. }
  1705. goto redo;
  1706. found:
  1707. *prtsp_st = rtsp_st;
  1708. return len;
  1709. }
  1710. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1711. {
  1712. RTSPState *rt = s->priv_data;
  1713. int ret, len;
  1714. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1715. RTSPStream *rtsp_st;
  1716. /* get next frames from the same RTP packet */
  1717. if (rt->cur_transport_priv) {
  1718. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1719. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1720. } else
  1721. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1722. if (ret == 0) {
  1723. rt->cur_transport_priv = NULL;
  1724. return 0;
  1725. } else if (ret == 1) {
  1726. return 0;
  1727. } else
  1728. rt->cur_transport_priv = NULL;
  1729. }
  1730. /* read next RTP packet */
  1731. redo:
  1732. switch(rt->lower_transport) {
  1733. default:
  1734. #if CONFIG_RTSP_DEMUXER
  1735. case RTSP_LOWER_TRANSPORT_TCP:
  1736. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1737. break;
  1738. #endif
  1739. case RTSP_LOWER_TRANSPORT_UDP:
  1740. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1741. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1742. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1743. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1744. break;
  1745. }
  1746. if (len < 0)
  1747. return len;
  1748. if (len == 0)
  1749. return AVERROR_EOF;
  1750. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1751. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1752. } else {
  1753. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1754. if (ret < 0) {
  1755. /* Either bad packet, or a RTCP packet. Check if the
  1756. * first_rtcp_ntp_time field was initialized. */
  1757. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1758. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1759. /* first_rtcp_ntp_time has been initialized for this stream,
  1760. * copy the same value to all other uninitialized streams,
  1761. * in order to map their timestamp origin to the same ntp time
  1762. * as this one. */
  1763. int i;
  1764. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1765. RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv;
  1766. if (rtpctx2 &&
  1767. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1768. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1769. }
  1770. }
  1771. }
  1772. }
  1773. if (ret < 0)
  1774. goto redo;
  1775. if (ret == 1)
  1776. /* more packets may follow, so we save the RTP context */
  1777. rt->cur_transport_priv = rtsp_st->transport_priv;
  1778. return ret;
  1779. }
  1780. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1781. {
  1782. RTSPState *rt = s->priv_data;
  1783. int ret;
  1784. RTSPMessageHeader reply1, *reply = &reply1;
  1785. char cmd[1024];
  1786. if (rt->server_type == RTSP_SERVER_REAL) {
  1787. int i;
  1788. enum AVDiscard cache[MAX_STREAMS];
  1789. for (i = 0; i < s->nb_streams; i++)
  1790. cache[i] = s->streams[i]->discard;
  1791. if (!rt->need_subscription) {
  1792. if (memcmp (cache, rt->real_setup_cache,
  1793. sizeof(enum AVDiscard) * s->nb_streams)) {
  1794. snprintf(cmd, sizeof(cmd),
  1795. "Unsubscribe: %s\r\n",
  1796. rt->last_subscription);
  1797. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1798. cmd, reply, NULL);
  1799. if (reply->status_code != RTSP_STATUS_OK)
  1800. return AVERROR_INVALIDDATA;
  1801. rt->need_subscription = 1;
  1802. }
  1803. }
  1804. if (rt->need_subscription) {
  1805. int r, rule_nr, first = 1;
  1806. memcpy(rt->real_setup_cache, cache,
  1807. sizeof(enum AVDiscard) * s->nb_streams);
  1808. rt->last_subscription[0] = 0;
  1809. snprintf(cmd, sizeof(cmd),
  1810. "Subscribe: ");
  1811. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1812. rule_nr = 0;
  1813. for (r = 0; r < s->nb_streams; r++) {
  1814. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1815. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1816. if (!first)
  1817. av_strlcat(rt->last_subscription, ",",
  1818. sizeof(rt->last_subscription));
  1819. ff_rdt_subscribe_rule(
  1820. rt->last_subscription,
  1821. sizeof(rt->last_subscription), i, rule_nr);
  1822. first = 0;
  1823. }
  1824. rule_nr++;
  1825. }
  1826. }
  1827. }
  1828. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1829. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1830. cmd, reply, NULL);
  1831. if (reply->status_code != RTSP_STATUS_OK)
  1832. return AVERROR_INVALIDDATA;
  1833. rt->need_subscription = 0;
  1834. if (rt->state == RTSP_STATE_STREAMING)
  1835. rtsp_read_play (s);
  1836. }
  1837. }
  1838. ret = rtsp_fetch_packet(s, pkt);
  1839. if (ret < 0)
  1840. return ret;
  1841. /* send dummy request to keep TCP connection alive */
  1842. if ((rt->server_type == RTSP_SERVER_WMS ||
  1843. rt->server_type == RTSP_SERVER_REAL) &&
  1844. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1845. if (rt->server_type == RTSP_SERVER_WMS) {
  1846. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  1847. } else {
  1848. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  1849. }
  1850. }
  1851. return 0;
  1852. }
  1853. /* pause the stream */
  1854. static int rtsp_read_pause(AVFormatContext *s)
  1855. {
  1856. RTSPState *rt = s->priv_data;
  1857. RTSPMessageHeader reply1, *reply = &reply1;
  1858. if (rt->state != RTSP_STATE_STREAMING)
  1859. return 0;
  1860. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1861. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  1862. if (reply->status_code != RTSP_STATUS_OK) {
  1863. return -1;
  1864. }
  1865. }
  1866. rt->state = RTSP_STATE_PAUSED;
  1867. return 0;
  1868. }
  1869. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1870. int64_t timestamp, int flags)
  1871. {
  1872. RTSPState *rt = s->priv_data;
  1873. rt->seek_timestamp = av_rescale_q(timestamp,
  1874. s->streams[stream_index]->time_base,
  1875. AV_TIME_BASE_Q);
  1876. switch(rt->state) {
  1877. default:
  1878. case RTSP_STATE_IDLE:
  1879. break;
  1880. case RTSP_STATE_STREAMING:
  1881. if (rtsp_read_pause(s) != 0)
  1882. return -1;
  1883. rt->state = RTSP_STATE_SEEKING;
  1884. if (rtsp_read_play(s) != 0)
  1885. return -1;
  1886. break;
  1887. case RTSP_STATE_PAUSED:
  1888. rt->state = RTSP_STATE_IDLE;
  1889. break;
  1890. }
  1891. return 0;
  1892. }
  1893. static int rtsp_read_close(AVFormatContext *s)
  1894. {
  1895. RTSPState *rt = s->priv_data;
  1896. #if 0
  1897. /* NOTE: it is valid to flush the buffer here */
  1898. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1899. url_fclose(&rt->rtsp_gb);
  1900. }
  1901. #endif
  1902. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  1903. ff_rtsp_close_streams(s);
  1904. ff_rtsp_close_connections(s);
  1905. ff_network_close();
  1906. return 0;
  1907. }
  1908. AVInputFormat rtsp_demuxer = {
  1909. "rtsp",
  1910. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1911. sizeof(RTSPState),
  1912. rtsp_probe,
  1913. rtsp_read_header,
  1914. rtsp_read_packet,
  1915. rtsp_read_close,
  1916. rtsp_read_seek,
  1917. .flags = AVFMT_NOFILE,
  1918. .read_play = rtsp_read_play,
  1919. .read_pause = rtsp_read_pause,
  1920. };
  1921. #endif
  1922. static int sdp_probe(AVProbeData *p1)
  1923. {
  1924. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1925. /* we look for a line beginning "c=IN IP4" */
  1926. while (p < p_end && *p != '\0') {
  1927. if (p + sizeof("c=IN IP4") - 1 < p_end &&
  1928. av_strstart(p, "c=IN IP4", NULL))
  1929. return AVPROBE_SCORE_MAX / 2;
  1930. while (p < p_end - 1 && *p != '\n') p++;
  1931. if (++p >= p_end)
  1932. break;
  1933. if (*p == '\r')
  1934. p++;
  1935. }
  1936. return 0;
  1937. }
  1938. #define SDP_MAX_SIZE 8192
  1939. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1940. {
  1941. RTSPState *rt = s->priv_data;
  1942. RTSPStream *rtsp_st;
  1943. int size, i, err;
  1944. char *content;
  1945. char url[1024];
  1946. if (!ff_network_init())
  1947. return AVERROR(EIO);
  1948. /* read the whole sdp file */
  1949. /* XXX: better loading */
  1950. content = av_malloc(SDP_MAX_SIZE);
  1951. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1952. if (size <= 0) {
  1953. av_free(content);
  1954. return AVERROR_INVALIDDATA;
  1955. }
  1956. content[size] ='\0';
  1957. sdp_parse(s, content);
  1958. av_free(content);
  1959. /* open each RTP stream */
  1960. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1961. rtsp_st = rt->rtsp_streams[i];
  1962. ff_url_join(url, sizeof(url), "rtp", NULL,
  1963. inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
  1964. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1965. rtsp_st->sdp_ttl);
  1966. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1967. err = AVERROR_INVALIDDATA;
  1968. goto fail;
  1969. }
  1970. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1971. goto fail;
  1972. }
  1973. return 0;
  1974. fail:
  1975. ff_rtsp_close_streams(s);
  1976. ff_network_close();
  1977. return err;
  1978. }
  1979. static int sdp_read_close(AVFormatContext *s)
  1980. {
  1981. ff_rtsp_close_streams(s);
  1982. ff_network_close();
  1983. return 0;
  1984. }
  1985. AVInputFormat sdp_demuxer = {
  1986. "sdp",
  1987. NULL_IF_CONFIG_SMALL("SDP"),
  1988. sizeof(RTSPState),
  1989. sdp_probe,
  1990. sdp_read_header,
  1991. rtsp_fetch_packet,
  1992. sdp_read_close,
  1993. };