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.

2051 lines
67KB

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