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.

2001 lines
65KB

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