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.

2090 lines
69KB

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