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.

2180 lines
73KB

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