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.

2055 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. av_freep(&rt->auth_b64);
  574. }
  575. static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
  576. URLContext *handle)
  577. {
  578. RTSPState *rt = s->priv_data;
  579. AVFormatContext *rtpctx;
  580. int ret;
  581. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  582. if (!rtp_format)
  583. return NULL;
  584. /* Allocate an AVFormatContext for each output stream */
  585. rtpctx = avformat_alloc_context();
  586. if (!rtpctx)
  587. return NULL;
  588. rtpctx->oformat = rtp_format;
  589. if (!av_new_stream(rtpctx, 0)) {
  590. av_free(rtpctx);
  591. return NULL;
  592. }
  593. /* Copy the max delay setting; the rtp muxer reads this. */
  594. rtpctx->max_delay = s->max_delay;
  595. /* Copy other stream parameters. */
  596. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  597. /* Set the synchronized start time. */
  598. rtpctx->start_time_realtime = rt->start_time;
  599. /* Remove the local codec, link to the original codec
  600. * context instead, to give the rtp muxer access to
  601. * codec parameters. */
  602. av_free(rtpctx->streams[0]->codec);
  603. rtpctx->streams[0]->codec = st->codec;
  604. if (handle) {
  605. url_fdopen(&rtpctx->pb, handle);
  606. } else
  607. url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
  608. ret = av_write_header(rtpctx);
  609. if (ret) {
  610. if (handle) {
  611. url_fclose(rtpctx->pb);
  612. } else {
  613. uint8_t *ptr;
  614. url_close_dyn_buf(rtpctx->pb, &ptr);
  615. av_free(ptr);
  616. }
  617. av_free(rtpctx->streams[0]);
  618. av_free(rtpctx);
  619. return NULL;
  620. }
  621. /* Copy the RTP AVStream timebase back to the original AVStream */
  622. st->time_base = rtpctx->streams[0]->time_base;
  623. return rtpctx;
  624. }
  625. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  626. {
  627. RTSPState *rt = s->priv_data;
  628. AVStream *st = NULL;
  629. /* open the RTP context */
  630. if (rtsp_st->stream_index >= 0)
  631. st = s->streams[rtsp_st->stream_index];
  632. if (!st)
  633. s->ctx_flags |= AVFMTCTX_NOHEADER;
  634. if (s->oformat) {
  635. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  636. /* Ownage of rtp_handle is passed to the rtp mux context */
  637. rtsp_st->rtp_handle = NULL;
  638. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  639. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  640. rtsp_st->dynamic_protocol_context,
  641. rtsp_st->dynamic_handler);
  642. else
  643. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  644. rtsp_st->sdp_payload_type,
  645. &rtsp_st->rtp_payload_data);
  646. if (!rtsp_st->transport_priv) {
  647. return AVERROR(ENOMEM);
  648. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  649. if (rtsp_st->dynamic_handler) {
  650. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  651. rtsp_st->dynamic_protocol_context,
  652. rtsp_st->dynamic_handler);
  653. }
  654. }
  655. return 0;
  656. }
  657. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  658. static int rtsp_probe(AVProbeData *p)
  659. {
  660. if (av_strstart(p->filename, "rtsp:", NULL))
  661. return AVPROBE_SCORE_MAX;
  662. return 0;
  663. }
  664. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  665. {
  666. const char *p;
  667. int v;
  668. p = *pp;
  669. skip_spaces(&p);
  670. v = strtol(p, (char **)&p, 10);
  671. if (*p == '-') {
  672. p++;
  673. *min_ptr = v;
  674. v = strtol(p, (char **)&p, 10);
  675. *max_ptr = v;
  676. } else {
  677. *min_ptr = v;
  678. *max_ptr = v;
  679. }
  680. *pp = p;
  681. }
  682. /* XXX: only one transport specification is parsed */
  683. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  684. {
  685. char transport_protocol[16];
  686. char profile[16];
  687. char lower_transport[16];
  688. char parameter[16];
  689. RTSPTransportField *th;
  690. char buf[256];
  691. reply->nb_transports = 0;
  692. for (;;) {
  693. skip_spaces(&p);
  694. if (*p == '\0')
  695. break;
  696. th = &reply->transports[reply->nb_transports];
  697. get_word_sep(transport_protocol, sizeof(transport_protocol),
  698. "/", &p);
  699. if (!strcasecmp (transport_protocol, "rtp")) {
  700. get_word_sep(profile, sizeof(profile), "/;,", &p);
  701. lower_transport[0] = '\0';
  702. /* rtp/avp/<protocol> */
  703. if (*p == '/') {
  704. get_word_sep(lower_transport, sizeof(lower_transport),
  705. ";,", &p);
  706. }
  707. th->transport = RTSP_TRANSPORT_RTP;
  708. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  709. !strcasecmp (transport_protocol, "x-real-rdt")) {
  710. /* x-pn-tng/<protocol> */
  711. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  712. profile[0] = '\0';
  713. th->transport = RTSP_TRANSPORT_RDT;
  714. }
  715. if (!strcasecmp(lower_transport, "TCP"))
  716. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  717. else
  718. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  719. if (*p == ';')
  720. p++;
  721. /* get each parameter */
  722. while (*p != '\0' && *p != ',') {
  723. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  724. if (!strcmp(parameter, "port")) {
  725. if (*p == '=') {
  726. p++;
  727. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  728. }
  729. } else if (!strcmp(parameter, "client_port")) {
  730. if (*p == '=') {
  731. p++;
  732. rtsp_parse_range(&th->client_port_min,
  733. &th->client_port_max, &p);
  734. }
  735. } else if (!strcmp(parameter, "server_port")) {
  736. if (*p == '=') {
  737. p++;
  738. rtsp_parse_range(&th->server_port_min,
  739. &th->server_port_max, &p);
  740. }
  741. } else if (!strcmp(parameter, "interleaved")) {
  742. if (*p == '=') {
  743. p++;
  744. rtsp_parse_range(&th->interleaved_min,
  745. &th->interleaved_max, &p);
  746. }
  747. } else if (!strcmp(parameter, "multicast")) {
  748. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  749. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  750. } else if (!strcmp(parameter, "ttl")) {
  751. if (*p == '=') {
  752. p++;
  753. th->ttl = strtol(p, (char **)&p, 10);
  754. }
  755. } else if (!strcmp(parameter, "destination")) {
  756. struct in_addr ipaddr;
  757. if (*p == '=') {
  758. p++;
  759. get_word_sep(buf, sizeof(buf), ";,", &p);
  760. if (ff_inet_aton(buf, &ipaddr))
  761. th->destination = ntohl(ipaddr.s_addr);
  762. }
  763. }
  764. while (*p != ';' && *p != '\0' && *p != ',')
  765. p++;
  766. if (*p == ';')
  767. p++;
  768. }
  769. if (*p == ',')
  770. p++;
  771. reply->nb_transports++;
  772. }
  773. }
  774. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf)
  775. {
  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. }
  807. }
  808. /* skip a RTP/TCP interleaved packet */
  809. void ff_rtsp_skip_packet(AVFormatContext *s)
  810. {
  811. RTSPState *rt = s->priv_data;
  812. int ret, len, len1;
  813. uint8_t buf[1024];
  814. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  815. if (ret != 3)
  816. return;
  817. len = AV_RB16(buf + 1);
  818. dprintf(s, "skipping RTP packet len=%d\n", len);
  819. /* skip payload */
  820. while (len > 0) {
  821. len1 = len;
  822. if (len1 > sizeof(buf))
  823. len1 = sizeof(buf);
  824. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  825. if (ret != len1)
  826. return;
  827. len -= len1;
  828. }
  829. }
  830. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  831. unsigned char **content_ptr,
  832. int return_on_interleaved_data)
  833. {
  834. RTSPState *rt = s->priv_data;
  835. char buf[4096], buf1[1024], *q;
  836. unsigned char ch;
  837. const char *p;
  838. int ret, content_length, line_count = 0;
  839. unsigned char *content = NULL;
  840. memset(reply, 0, sizeof(*reply));
  841. /* parse reply (XXX: use buffers) */
  842. rt->last_reply[0] = '\0';
  843. for (;;) {
  844. q = buf;
  845. for (;;) {
  846. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  847. #ifdef DEBUG_RTP_TCP
  848. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  849. #endif
  850. if (ret != 1)
  851. return -1;
  852. if (ch == '\n')
  853. break;
  854. if (ch == '$') {
  855. /* XXX: only parse it if first char on line ? */
  856. if (return_on_interleaved_data) {
  857. return 1;
  858. } else
  859. ff_rtsp_skip_packet(s);
  860. } else if (ch != '\r') {
  861. if ((q - buf) < sizeof(buf) - 1)
  862. *q++ = ch;
  863. }
  864. }
  865. *q = '\0';
  866. dprintf(s, "line='%s'\n", buf);
  867. /* test if last line */
  868. if (buf[0] == '\0')
  869. break;
  870. p = buf;
  871. if (line_count == 0) {
  872. /* get reply code */
  873. get_word(buf1, sizeof(buf1), &p);
  874. get_word(buf1, sizeof(buf1), &p);
  875. reply->status_code = atoi(buf1);
  876. } else {
  877. ff_rtsp_parse_line(reply, p);
  878. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  879. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  880. }
  881. line_count++;
  882. }
  883. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  884. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  885. content_length = reply->content_length;
  886. if (content_length > 0) {
  887. /* leave some room for a trailing '\0' (useful for simple parsing) */
  888. content = av_malloc(content_length + 1);
  889. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  890. content[content_length] = '\0';
  891. }
  892. if (content_ptr)
  893. *content_ptr = content;
  894. else
  895. av_free(content);
  896. if (rt->seq != reply->seq) {
  897. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  898. rt->seq, reply->seq);
  899. }
  900. /* EOS */
  901. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  902. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  903. reply->notice == 2306 /* Continuous Feed Terminated */) {
  904. rt->state = RTSP_STATE_IDLE;
  905. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  906. return AVERROR(EIO); /* data or server error */
  907. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  908. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  909. return AVERROR(EPERM);
  910. return 0;
  911. }
  912. void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  913. const char *cmd,
  914. const unsigned char *send_content,
  915. int send_content_length)
  916. {
  917. RTSPState *rt = s->priv_data;
  918. char buf[4096], buf1[1024];
  919. rt->seq++;
  920. av_strlcpy(buf, cmd, sizeof(buf));
  921. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  922. av_strlcat(buf, buf1, sizeof(buf));
  923. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  924. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  925. av_strlcat(buf, buf1, sizeof(buf));
  926. }
  927. if (rt->auth_b64)
  928. av_strlcatf(buf, sizeof(buf),
  929. "Authorization: Basic %s\r\n",
  930. rt->auth_b64);
  931. if (send_content_length > 0 && send_content)
  932. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  933. av_strlcat(buf, "\r\n", sizeof(buf));
  934. dprintf(s, "Sending:\n%s--\n", buf);
  935. url_write(rt->rtsp_hd, buf, strlen(buf));
  936. if (send_content_length > 0 && send_content)
  937. url_write(rt->rtsp_hd, send_content, send_content_length);
  938. rt->last_cmd_time = av_gettime();
  939. }
  940. void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *cmd)
  941. {
  942. ff_rtsp_send_cmd_with_content_async(s, cmd, NULL, 0);
  943. }
  944. void ff_rtsp_send_cmd(AVFormatContext *s,
  945. const char *cmd, RTSPMessageHeader *reply,
  946. unsigned char **content_ptr)
  947. {
  948. ff_rtsp_send_cmd_with_content(s, cmd, reply, content_ptr, NULL, 0);
  949. }
  950. void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  951. const char *cmd,
  952. RTSPMessageHeader *reply,
  953. unsigned char **content_ptr,
  954. const unsigned char *send_content,
  955. int send_content_length)
  956. {
  957. ff_rtsp_send_cmd_with_content_async(s, cmd, send_content, send_content_length);
  958. ff_rtsp_read_reply(s, reply, content_ptr, 0);
  959. }
  960. /**
  961. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  962. */
  963. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  964. int lower_transport, const char *real_challenge)
  965. {
  966. RTSPState *rt = s->priv_data;
  967. int rtx, j, i, err, interleave = 0;
  968. RTSPStream *rtsp_st;
  969. RTSPMessageHeader reply1, *reply = &reply1;
  970. char cmd[2048];
  971. const char *trans_pref;
  972. if (rt->transport == RTSP_TRANSPORT_RDT)
  973. trans_pref = "x-pn-tng";
  974. else
  975. trans_pref = "RTP/AVP";
  976. /* default timeout: 1 minute */
  977. rt->timeout = 60;
  978. /* for each stream, make the setup request */
  979. /* XXX: we assume the same server is used for the control of each
  980. * RTSP stream */
  981. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  982. char transport[2048];
  983. /**
  984. * WMS serves all UDP data over a single connection, the RTX, which
  985. * isn't necessarily the first in the SDP but has to be the first
  986. * to be set up, else the second/third SETUP will fail with a 461.
  987. */
  988. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  989. rt->server_type == RTSP_SERVER_WMS) {
  990. if (i == 0) {
  991. /* rtx first */
  992. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  993. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  994. if (len >= 4 &&
  995. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  996. "/rtx"))
  997. break;
  998. }
  999. if (rtx == rt->nb_rtsp_streams)
  1000. return -1; /* no RTX found */
  1001. rtsp_st = rt->rtsp_streams[rtx];
  1002. } else
  1003. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  1004. } else
  1005. rtsp_st = rt->rtsp_streams[i];
  1006. /* RTP/UDP */
  1007. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  1008. char buf[256];
  1009. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  1010. port = reply->transports[0].client_port_min;
  1011. goto have_port;
  1012. }
  1013. /* first try in specified port range */
  1014. if (RTSP_RTP_PORT_MIN != 0) {
  1015. while (j <= RTSP_RTP_PORT_MAX) {
  1016. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  1017. "?localport=%d", j);
  1018. /* we will use two ports per rtp stream (rtp and rtcp) */
  1019. j += 2;
  1020. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  1021. goto rtp_opened;
  1022. }
  1023. }
  1024. #if 0
  1025. /* then try on any port */
  1026. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  1027. err = AVERROR_INVALIDDATA;
  1028. goto fail;
  1029. }
  1030. #endif
  1031. rtp_opened:
  1032. port = rtp_get_local_port(rtsp_st->rtp_handle);
  1033. have_port:
  1034. snprintf(transport, sizeof(transport) - 1,
  1035. "%s/UDP;", trans_pref);
  1036. if (rt->server_type != RTSP_SERVER_REAL)
  1037. av_strlcat(transport, "unicast;", sizeof(transport));
  1038. av_strlcatf(transport, sizeof(transport),
  1039. "client_port=%d", port);
  1040. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1041. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1042. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1043. }
  1044. /* RTP/TCP */
  1045. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1046. /** For WMS streams, the application streams are only used for
  1047. * UDP. When trying to set it up for TCP streams, the server
  1048. * will return an error. Therefore, we skip those streams. */
  1049. if (rt->server_type == RTSP_SERVER_WMS &&
  1050. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1051. CODEC_TYPE_DATA)
  1052. continue;
  1053. snprintf(transport, sizeof(transport) - 1,
  1054. "%s/TCP;", trans_pref);
  1055. if (rt->server_type == RTSP_SERVER_WMS)
  1056. av_strlcat(transport, "unicast;", sizeof(transport));
  1057. av_strlcatf(transport, sizeof(transport),
  1058. "interleaved=%d-%d",
  1059. interleave, interleave + 1);
  1060. interleave += 2;
  1061. }
  1062. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1063. snprintf(transport, sizeof(transport) - 1,
  1064. "%s/UDP;multicast", trans_pref);
  1065. }
  1066. if (s->oformat) {
  1067. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1068. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1069. rt->server_type == RTSP_SERVER_WMS)
  1070. av_strlcat(transport, ";mode=play", sizeof(transport));
  1071. snprintf(cmd, sizeof(cmd),
  1072. "SETUP %s RTSP/1.0\r\n"
  1073. "Transport: %s\r\n",
  1074. rtsp_st->control_url, transport);
  1075. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  1076. char real_res[41], real_csum[9];
  1077. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1078. real_challenge);
  1079. av_strlcatf(cmd, sizeof(cmd),
  1080. "If-Match: %s\r\n"
  1081. "RealChallenge2: %s, sd=%s\r\n",
  1082. rt->session_id, real_res, real_csum);
  1083. }
  1084. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1085. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1086. err = 1;
  1087. goto fail;
  1088. } else if (reply->status_code != RTSP_STATUS_OK ||
  1089. reply->nb_transports != 1) {
  1090. err = AVERROR_INVALIDDATA;
  1091. goto fail;
  1092. }
  1093. /* XXX: same protocol for all streams is required */
  1094. if (i > 0) {
  1095. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1096. reply->transports[0].transport != rt->transport) {
  1097. err = AVERROR_INVALIDDATA;
  1098. goto fail;
  1099. }
  1100. } else {
  1101. rt->lower_transport = reply->transports[0].lower_transport;
  1102. rt->transport = reply->transports[0].transport;
  1103. }
  1104. /* close RTP connection if not choosen */
  1105. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1106. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1107. url_close(rtsp_st->rtp_handle);
  1108. rtsp_st->rtp_handle = NULL;
  1109. }
  1110. switch(reply->transports[0].lower_transport) {
  1111. case RTSP_LOWER_TRANSPORT_TCP:
  1112. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1113. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1114. break;
  1115. case RTSP_LOWER_TRANSPORT_UDP: {
  1116. char url[1024];
  1117. /* XXX: also use address if specified */
  1118. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1119. reply->transports[0].server_port_min, NULL);
  1120. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1121. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1122. err = AVERROR_INVALIDDATA;
  1123. goto fail;
  1124. }
  1125. /* Try to initialize the connection state in a
  1126. * potential NAT router by sending dummy packets.
  1127. * RTP/RTCP dummy packets are used for RDT, too.
  1128. */
  1129. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1130. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1131. break;
  1132. }
  1133. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1134. char url[1024];
  1135. struct in_addr in;
  1136. int port, ttl;
  1137. if (reply->transports[0].destination) {
  1138. in.s_addr = htonl(reply->transports[0].destination);
  1139. port = reply->transports[0].port_min;
  1140. ttl = reply->transports[0].ttl;
  1141. } else {
  1142. in = rtsp_st->sdp_ip;
  1143. port = rtsp_st->sdp_port;
  1144. ttl = rtsp_st->sdp_ttl;
  1145. }
  1146. ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
  1147. port, "?ttl=%d", ttl);
  1148. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1149. err = AVERROR_INVALIDDATA;
  1150. goto fail;
  1151. }
  1152. break;
  1153. }
  1154. }
  1155. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1156. goto fail;
  1157. }
  1158. if (reply->timeout > 0)
  1159. rt->timeout = reply->timeout;
  1160. if (rt->server_type == RTSP_SERVER_REAL)
  1161. rt->need_subscription = 1;
  1162. return 0;
  1163. fail:
  1164. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1165. if (rt->rtsp_streams[i]->rtp_handle) {
  1166. url_close(rt->rtsp_streams[i]->rtp_handle);
  1167. rt->rtsp_streams[i]->rtp_handle = NULL;
  1168. }
  1169. }
  1170. return err;
  1171. }
  1172. static int rtsp_read_play(AVFormatContext *s)
  1173. {
  1174. RTSPState *rt = s->priv_data;
  1175. RTSPMessageHeader reply1, *reply = &reply1;
  1176. char cmd[1024];
  1177. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1178. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1179. if (rt->state == RTSP_STATE_PAUSED) {
  1180. snprintf(cmd, sizeof(cmd),
  1181. "PLAY %s RTSP/1.0\r\n",
  1182. rt->control_uri);
  1183. } else {
  1184. snprintf(cmd, sizeof(cmd),
  1185. "PLAY %s RTSP/1.0\r\n"
  1186. "Range: npt=%0.3f-\r\n",
  1187. rt->control_uri,
  1188. (double)rt->seek_timestamp / AV_TIME_BASE);
  1189. }
  1190. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1191. if (reply->status_code != RTSP_STATUS_OK) {
  1192. return -1;
  1193. }
  1194. }
  1195. rt->state = RTSP_STATE_STREAMING;
  1196. return 0;
  1197. }
  1198. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1199. {
  1200. RTSPState *rt = s->priv_data;
  1201. char cmd[1024];
  1202. unsigned char *content = NULL;
  1203. int ret;
  1204. /* describe the stream */
  1205. snprintf(cmd, sizeof(cmd),
  1206. "DESCRIBE %s RTSP/1.0\r\n"
  1207. "Accept: application/sdp\r\n",
  1208. rt->control_uri);
  1209. if (rt->server_type == RTSP_SERVER_REAL) {
  1210. /**
  1211. * The Require: attribute is needed for proper streaming from
  1212. * Realmedia servers.
  1213. */
  1214. av_strlcat(cmd,
  1215. "Require: com.real.retain-entity-for-setup\r\n",
  1216. sizeof(cmd));
  1217. }
  1218. ff_rtsp_send_cmd(s, cmd, reply, &content);
  1219. if (!content)
  1220. return AVERROR_INVALIDDATA;
  1221. if (reply->status_code != RTSP_STATUS_OK) {
  1222. av_freep(&content);
  1223. return AVERROR_INVALIDDATA;
  1224. }
  1225. /* now we got the SDP description, we parse it */
  1226. ret = sdp_parse(s, (const char *)content);
  1227. av_freep(&content);
  1228. if (ret < 0)
  1229. return AVERROR_INVALIDDATA;
  1230. return 0;
  1231. }
  1232. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1233. {
  1234. RTSPState *rt = s->priv_data;
  1235. RTSPMessageHeader reply1, *reply = &reply1;
  1236. char cmd[1024];
  1237. int i;
  1238. char *sdp;
  1239. AVFormatContext sdp_ctx, *ctx_array[1];
  1240. rt->start_time = av_gettime();
  1241. /* Announce the stream */
  1242. snprintf(cmd, sizeof(cmd),
  1243. "ANNOUNCE %s RTSP/1.0\r\n"
  1244. "Content-Type: application/sdp\r\n",
  1245. rt->control_uri);
  1246. sdp = av_mallocz(8192);
  1247. if (sdp == NULL)
  1248. return AVERROR(ENOMEM);
  1249. /* We create the SDP based on the RTSP AVFormatContext where we
  1250. * aren't allowed to change the filename field. (We create the SDP
  1251. * based on the RTSP context since the contexts for the RTP streams
  1252. * don't exist yet.) In order to specify a custom URL with the actual
  1253. * peer IP instead of the originally specified hostname, we create
  1254. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1255. *
  1256. * FIXME: Create the SDP without copying the AVFormatContext.
  1257. * This either requires setting up the RTP stream AVFormatContexts
  1258. * already here (complicating things immensely) or getting a more
  1259. * flexible SDP creation interface.
  1260. */
  1261. sdp_ctx = *s;
  1262. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1263. "rtsp", NULL, addr, -1, NULL);
  1264. ctx_array[0] = &sdp_ctx;
  1265. if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
  1266. av_free(sdp);
  1267. return AVERROR_INVALIDDATA;
  1268. }
  1269. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1270. ff_rtsp_send_cmd_with_content(s, cmd, reply, NULL, sdp, strlen(sdp));
  1271. av_free(sdp);
  1272. if (reply->status_code != RTSP_STATUS_OK)
  1273. return AVERROR_INVALIDDATA;
  1274. /* Set up the RTSPStreams for each AVStream */
  1275. for (i = 0; i < s->nb_streams; i++) {
  1276. RTSPStream *rtsp_st;
  1277. AVStream *st = s->streams[i];
  1278. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1279. if (!rtsp_st)
  1280. return AVERROR(ENOMEM);
  1281. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1282. st->priv_data = rtsp_st;
  1283. rtsp_st->stream_index = i;
  1284. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1285. /* Note, this must match the relative uri set in the sdp content */
  1286. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1287. "/streamid=%d", i);
  1288. }
  1289. return 0;
  1290. }
  1291. int ff_rtsp_connect(AVFormatContext *s)
  1292. {
  1293. RTSPState *rt = s->priv_data;
  1294. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1295. char *option_list, *option, *filename;
  1296. URLContext *rtsp_hd;
  1297. int port, err, tcp_fd;
  1298. RTSPMessageHeader reply1, *reply = &reply1;
  1299. int lower_transport_mask = 0;
  1300. char real_challenge[64];
  1301. struct sockaddr_storage peer;
  1302. socklen_t peer_len = sizeof(peer);
  1303. if (!ff_network_init())
  1304. return AVERROR(EIO);
  1305. redirect:
  1306. /* extract hostname and port */
  1307. ff_url_split(NULL, 0, auth, sizeof(auth),
  1308. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1309. if (*auth) {
  1310. int auth_len = strlen(auth), b64_len = ((auth_len + 2) / 3) * 4 + 1;
  1311. if (!(rt->auth_b64 = av_malloc(b64_len)))
  1312. return AVERROR(ENOMEM);
  1313. if (!av_base64_encode(rt->auth_b64, b64_len, auth, auth_len)) {
  1314. err = AVERROR(EINVAL);
  1315. goto fail;
  1316. }
  1317. }
  1318. if (port < 0)
  1319. port = RTSP_DEFAULT_PORT;
  1320. /* search for options */
  1321. option_list = strrchr(path, '?');
  1322. if (option_list) {
  1323. /* Strip out the RTSP specific options, write out the rest of
  1324. * the options back into the same string. */
  1325. filename = option_list;
  1326. while (option_list) {
  1327. /* move the option pointer */
  1328. option = ++option_list;
  1329. option_list = strchr(option_list, '&');
  1330. if (option_list)
  1331. *option_list = 0;
  1332. /* handle the options */
  1333. if (!strcmp(option, "udp")) {
  1334. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1335. } else if (!strcmp(option, "multicast")) {
  1336. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1337. } else if (!strcmp(option, "tcp")) {
  1338. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1339. } else {
  1340. /* Write options back into the buffer, using memmove instead
  1341. * of strcpy since the strings may overlap. */
  1342. int len = strlen(option);
  1343. memmove(++filename, option, len);
  1344. filename += len;
  1345. if (option_list) *filename = '&';
  1346. }
  1347. }
  1348. *filename = 0;
  1349. }
  1350. if (!lower_transport_mask)
  1351. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1352. if (s->oformat) {
  1353. /* Only UDP or TCP - UDP multicast isn't supported. */
  1354. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1355. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1356. if (!lower_transport_mask) {
  1357. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1358. "only UDP and TCP are supported for output.\n");
  1359. err = AVERROR(EINVAL);
  1360. goto fail;
  1361. }
  1362. }
  1363. /* open the tcp connexion */
  1364. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1365. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
  1366. err = AVERROR(EIO);
  1367. goto fail;
  1368. }
  1369. rt->rtsp_hd = rtsp_hd;
  1370. rt->seq = 0;
  1371. tcp_fd = url_get_file_handle(rtsp_hd);
  1372. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1373. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1374. NULL, 0, NI_NUMERICHOST);
  1375. }
  1376. /* Construct the URI used in request; this is similar to s->filename,
  1377. * but with authentication credentials removed and RTSP specific options
  1378. * stripped out. */
  1379. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1380. host, port, "%s", path);
  1381. /* request options supported by the server; this also detects server
  1382. * type */
  1383. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1384. snprintf(cmd, sizeof(cmd),
  1385. "OPTIONS %s RTSP/1.0\r\n", rt->control_uri);
  1386. if (rt->server_type == RTSP_SERVER_REAL)
  1387. av_strlcat(cmd,
  1388. /**
  1389. * The following entries are required for proper
  1390. * streaming from a Realmedia server. They are
  1391. * interdependent in some way although we currently
  1392. * don't quite understand how. Values were copied
  1393. * from mplayer SVN r23589.
  1394. * @param CompanyID is a 16-byte ID in base64
  1395. * @param ClientChallenge is a 16-byte ID in hex
  1396. */
  1397. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1398. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1399. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1400. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1401. sizeof(cmd));
  1402. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1403. if (reply->status_code != RTSP_STATUS_OK) {
  1404. err = AVERROR_INVALIDDATA;
  1405. goto fail;
  1406. }
  1407. /* detect server type if not standard-compliant RTP */
  1408. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1409. rt->server_type = RTSP_SERVER_REAL;
  1410. continue;
  1411. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1412. rt->server_type = RTSP_SERVER_WMS;
  1413. } else if (rt->server_type == RTSP_SERVER_REAL)
  1414. strcpy(real_challenge, reply->real_challenge);
  1415. break;
  1416. }
  1417. if (s->iformat)
  1418. err = rtsp_setup_input_streams(s, reply);
  1419. else
  1420. err = rtsp_setup_output_streams(s, host);
  1421. if (err)
  1422. goto fail;
  1423. do {
  1424. int lower_transport = ff_log2_tab[lower_transport_mask &
  1425. ~(lower_transport_mask - 1)];
  1426. err = make_setup_request(s, host, port, lower_transport,
  1427. rt->server_type == RTSP_SERVER_REAL ?
  1428. real_challenge : NULL);
  1429. if (err < 0)
  1430. goto fail;
  1431. lower_transport_mask &= ~(1 << lower_transport);
  1432. if (lower_transport_mask == 0 && err == 1) {
  1433. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1434. goto fail;
  1435. }
  1436. } while (err);
  1437. rt->state = RTSP_STATE_IDLE;
  1438. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1439. return 0;
  1440. fail:
  1441. ff_rtsp_close_streams(s);
  1442. url_close(rt->rtsp_hd);
  1443. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1444. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1445. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1446. reply->status_code,
  1447. s->filename);
  1448. goto redirect;
  1449. }
  1450. ff_network_close();
  1451. return err;
  1452. }
  1453. #endif
  1454. #if CONFIG_RTSP_DEMUXER
  1455. static int rtsp_read_header(AVFormatContext *s,
  1456. AVFormatParameters *ap)
  1457. {
  1458. RTSPState *rt = s->priv_data;
  1459. int ret;
  1460. ret = ff_rtsp_connect(s);
  1461. if (ret)
  1462. return ret;
  1463. if (ap->initial_pause) {
  1464. /* do not start immediately */
  1465. } else {
  1466. if (rtsp_read_play(s) < 0) {
  1467. ff_rtsp_close_streams(s);
  1468. url_close(rt->rtsp_hd);
  1469. return AVERROR_INVALIDDATA;
  1470. }
  1471. }
  1472. return 0;
  1473. }
  1474. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1475. uint8_t *buf, int buf_size)
  1476. {
  1477. RTSPState *rt = s->priv_data;
  1478. RTSPStream *rtsp_st;
  1479. fd_set rfds;
  1480. int fd, fd_max, n, i, ret, tcp_fd;
  1481. struct timeval tv;
  1482. for (;;) {
  1483. if (url_interrupt_cb())
  1484. return AVERROR(EINTR);
  1485. FD_ZERO(&rfds);
  1486. if (rt->rtsp_hd) {
  1487. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1488. FD_SET(tcp_fd, &rfds);
  1489. } else {
  1490. fd_max = 0;
  1491. tcp_fd = -1;
  1492. }
  1493. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1494. rtsp_st = rt->rtsp_streams[i];
  1495. if (rtsp_st->rtp_handle) {
  1496. /* currently, we cannot probe RTCP handle because of
  1497. * blocking restrictions */
  1498. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1499. if (fd > fd_max)
  1500. fd_max = fd;
  1501. FD_SET(fd, &rfds);
  1502. }
  1503. }
  1504. tv.tv_sec = 0;
  1505. tv.tv_usec = 100 * 1000;
  1506. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1507. if (n > 0) {
  1508. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1509. rtsp_st = rt->rtsp_streams[i];
  1510. if (rtsp_st->rtp_handle) {
  1511. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1512. if (FD_ISSET(fd, &rfds)) {
  1513. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1514. if (ret > 0) {
  1515. *prtsp_st = rtsp_st;
  1516. return ret;
  1517. }
  1518. }
  1519. }
  1520. }
  1521. #if CONFIG_RTSP_DEMUXER
  1522. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1523. RTSPMessageHeader reply;
  1524. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1525. if (ret < 0)
  1526. return ret;
  1527. /* XXX: parse message */
  1528. if (rt->state != RTSP_STATE_STREAMING)
  1529. return 0;
  1530. }
  1531. #endif
  1532. }
  1533. }
  1534. }
  1535. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1536. uint8_t *buf, int buf_size)
  1537. {
  1538. RTSPState *rt = s->priv_data;
  1539. int id, len, i, ret;
  1540. RTSPStream *rtsp_st;
  1541. #ifdef DEBUG_RTP_TCP
  1542. dprintf(s, "tcp_read_packet:\n");
  1543. #endif
  1544. redo:
  1545. for (;;) {
  1546. RTSPMessageHeader reply;
  1547. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1548. if (ret == -1)
  1549. return -1;
  1550. if (ret == 1) /* received '$' */
  1551. break;
  1552. /* XXX: parse message */
  1553. if (rt->state != RTSP_STATE_STREAMING)
  1554. return 0;
  1555. }
  1556. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1557. if (ret != 3)
  1558. return -1;
  1559. id = buf[0];
  1560. len = AV_RB16(buf + 1);
  1561. #ifdef DEBUG_RTP_TCP
  1562. dprintf(s, "id=%d len=%d\n", id, len);
  1563. #endif
  1564. if (len > buf_size || len < 12)
  1565. goto redo;
  1566. /* get the data */
  1567. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1568. if (ret != len)
  1569. return -1;
  1570. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1571. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1572. return -1;
  1573. /* find the matching stream */
  1574. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1575. rtsp_st = rt->rtsp_streams[i];
  1576. if (id >= rtsp_st->interleaved_min &&
  1577. id <= rtsp_st->interleaved_max)
  1578. goto found;
  1579. }
  1580. goto redo;
  1581. found:
  1582. *prtsp_st = rtsp_st;
  1583. return len;
  1584. }
  1585. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1586. {
  1587. RTSPState *rt = s->priv_data;
  1588. int ret, len;
  1589. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1590. RTSPStream *rtsp_st;
  1591. /* get next frames from the same RTP packet */
  1592. if (rt->cur_transport_priv) {
  1593. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1594. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1595. } else
  1596. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1597. if (ret == 0) {
  1598. rt->cur_transport_priv = NULL;
  1599. return 0;
  1600. } else if (ret == 1) {
  1601. return 0;
  1602. } else
  1603. rt->cur_transport_priv = NULL;
  1604. }
  1605. /* read next RTP packet */
  1606. redo:
  1607. switch(rt->lower_transport) {
  1608. default:
  1609. #if CONFIG_RTSP_DEMUXER
  1610. case RTSP_LOWER_TRANSPORT_TCP:
  1611. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1612. break;
  1613. #endif
  1614. case RTSP_LOWER_TRANSPORT_UDP:
  1615. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1616. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1617. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1618. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1619. break;
  1620. }
  1621. if (len < 0)
  1622. return len;
  1623. if (len == 0)
  1624. return AVERROR_EOF;
  1625. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1626. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1627. } else
  1628. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1629. if (ret < 0)
  1630. goto redo;
  1631. if (ret == 1)
  1632. /* more packets may follow, so we save the RTP context */
  1633. rt->cur_transport_priv = rtsp_st->transport_priv;
  1634. return ret;
  1635. }
  1636. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1637. {
  1638. RTSPState *rt = s->priv_data;
  1639. int ret;
  1640. RTSPMessageHeader reply1, *reply = &reply1;
  1641. char cmd[1024];
  1642. if (rt->server_type == RTSP_SERVER_REAL) {
  1643. int i;
  1644. enum AVDiscard cache[MAX_STREAMS];
  1645. for (i = 0; i < s->nb_streams; i++)
  1646. cache[i] = s->streams[i]->discard;
  1647. if (!rt->need_subscription) {
  1648. if (memcmp (cache, rt->real_setup_cache,
  1649. sizeof(enum AVDiscard) * s->nb_streams)) {
  1650. snprintf(cmd, sizeof(cmd),
  1651. "SET_PARAMETER %s RTSP/1.0\r\n"
  1652. "Unsubscribe: %s\r\n",
  1653. rt->control_uri, rt->last_subscription);
  1654. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1655. if (reply->status_code != RTSP_STATUS_OK)
  1656. return AVERROR_INVALIDDATA;
  1657. rt->need_subscription = 1;
  1658. }
  1659. }
  1660. if (rt->need_subscription) {
  1661. int r, rule_nr, first = 1;
  1662. memcpy(rt->real_setup_cache, cache,
  1663. sizeof(enum AVDiscard) * s->nb_streams);
  1664. rt->last_subscription[0] = 0;
  1665. snprintf(cmd, sizeof(cmd),
  1666. "SET_PARAMETER %s RTSP/1.0\r\n"
  1667. "Subscribe: ",
  1668. rt->control_uri);
  1669. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1670. rule_nr = 0;
  1671. for (r = 0; r < s->nb_streams; r++) {
  1672. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1673. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1674. if (!first)
  1675. av_strlcat(rt->last_subscription, ",",
  1676. sizeof(rt->last_subscription));
  1677. ff_rdt_subscribe_rule(
  1678. rt->last_subscription,
  1679. sizeof(rt->last_subscription), i, rule_nr);
  1680. first = 0;
  1681. }
  1682. rule_nr++;
  1683. }
  1684. }
  1685. }
  1686. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1687. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1688. if (reply->status_code != RTSP_STATUS_OK)
  1689. return AVERROR_INVALIDDATA;
  1690. rt->need_subscription = 0;
  1691. if (rt->state == RTSP_STATE_STREAMING)
  1692. rtsp_read_play (s);
  1693. }
  1694. }
  1695. ret = rtsp_fetch_packet(s, pkt);
  1696. if (ret < 0)
  1697. return ret;
  1698. /* send dummy request to keep TCP connection alive */
  1699. if ((rt->server_type == RTSP_SERVER_WMS ||
  1700. rt->server_type == RTSP_SERVER_REAL) &&
  1701. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1702. if (rt->server_type == RTSP_SERVER_WMS) {
  1703. snprintf(cmd, sizeof(cmd) - 1,
  1704. "GET_PARAMETER %s RTSP/1.0\r\n",
  1705. rt->control_uri);
  1706. ff_rtsp_send_cmd_async(s, cmd);
  1707. } else {
  1708. ff_rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n");
  1709. }
  1710. }
  1711. return 0;
  1712. }
  1713. /* pause the stream */
  1714. static int rtsp_read_pause(AVFormatContext *s)
  1715. {
  1716. RTSPState *rt = s->priv_data;
  1717. RTSPMessageHeader reply1, *reply = &reply1;
  1718. char cmd[1024];
  1719. rt = s->priv_data;
  1720. if (rt->state != RTSP_STATE_STREAMING)
  1721. return 0;
  1722. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1723. snprintf(cmd, sizeof(cmd),
  1724. "PAUSE %s RTSP/1.0\r\n",
  1725. rt->control_uri);
  1726. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1727. if (reply->status_code != RTSP_STATUS_OK) {
  1728. return -1;
  1729. }
  1730. }
  1731. rt->state = RTSP_STATE_PAUSED;
  1732. return 0;
  1733. }
  1734. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1735. int64_t timestamp, int flags)
  1736. {
  1737. RTSPState *rt = s->priv_data;
  1738. rt->seek_timestamp = av_rescale_q(timestamp,
  1739. s->streams[stream_index]->time_base,
  1740. AV_TIME_BASE_Q);
  1741. switch(rt->state) {
  1742. default:
  1743. case RTSP_STATE_IDLE:
  1744. break;
  1745. case RTSP_STATE_STREAMING:
  1746. if (rtsp_read_pause(s) != 0)
  1747. return -1;
  1748. rt->state = RTSP_STATE_SEEKING;
  1749. if (rtsp_read_play(s) != 0)
  1750. return -1;
  1751. break;
  1752. case RTSP_STATE_PAUSED:
  1753. rt->state = RTSP_STATE_IDLE;
  1754. break;
  1755. }
  1756. return 0;
  1757. }
  1758. static int rtsp_read_close(AVFormatContext *s)
  1759. {
  1760. RTSPState *rt = s->priv_data;
  1761. char cmd[1024];
  1762. #if 0
  1763. /* NOTE: it is valid to flush the buffer here */
  1764. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1765. url_fclose(&rt->rtsp_gb);
  1766. }
  1767. #endif
  1768. snprintf(cmd, sizeof(cmd),
  1769. "TEARDOWN %s RTSP/1.0\r\n",
  1770. rt->control_uri);
  1771. ff_rtsp_send_cmd_async(s, cmd);
  1772. ff_rtsp_close_streams(s);
  1773. url_close(rt->rtsp_hd);
  1774. ff_network_close();
  1775. return 0;
  1776. }
  1777. AVInputFormat rtsp_demuxer = {
  1778. "rtsp",
  1779. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1780. sizeof(RTSPState),
  1781. rtsp_probe,
  1782. rtsp_read_header,
  1783. rtsp_read_packet,
  1784. rtsp_read_close,
  1785. rtsp_read_seek,
  1786. .flags = AVFMT_NOFILE,
  1787. .read_play = rtsp_read_play,
  1788. .read_pause = rtsp_read_pause,
  1789. };
  1790. #endif
  1791. static int sdp_probe(AVProbeData *p1)
  1792. {
  1793. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1794. /* we look for a line beginning "c=IN IP4" */
  1795. while (p < p_end && *p != '\0') {
  1796. if (p + sizeof("c=IN IP4") - 1 < p_end &&
  1797. av_strstart(p, "c=IN IP4", NULL))
  1798. return AVPROBE_SCORE_MAX / 2;
  1799. while (p < p_end - 1 && *p != '\n') p++;
  1800. if (++p >= p_end)
  1801. break;
  1802. if (*p == '\r')
  1803. p++;
  1804. }
  1805. return 0;
  1806. }
  1807. #define SDP_MAX_SIZE 8192
  1808. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1809. {
  1810. RTSPState *rt = s->priv_data;
  1811. RTSPStream *rtsp_st;
  1812. int size, i, err;
  1813. char *content;
  1814. char url[1024];
  1815. if (!ff_network_init())
  1816. return AVERROR(EIO);
  1817. /* read the whole sdp file */
  1818. /* XXX: better loading */
  1819. content = av_malloc(SDP_MAX_SIZE);
  1820. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1821. if (size <= 0) {
  1822. av_free(content);
  1823. return AVERROR_INVALIDDATA;
  1824. }
  1825. content[size] ='\0';
  1826. sdp_parse(s, content);
  1827. av_free(content);
  1828. /* open each RTP stream */
  1829. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1830. rtsp_st = rt->rtsp_streams[i];
  1831. ff_url_join(url, sizeof(url), "rtp", NULL,
  1832. inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
  1833. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1834. rtsp_st->sdp_ttl);
  1835. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1836. err = AVERROR_INVALIDDATA;
  1837. goto fail;
  1838. }
  1839. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1840. goto fail;
  1841. }
  1842. return 0;
  1843. fail:
  1844. ff_rtsp_close_streams(s);
  1845. ff_network_close();
  1846. return err;
  1847. }
  1848. static int sdp_read_close(AVFormatContext *s)
  1849. {
  1850. ff_rtsp_close_streams(s);
  1851. ff_network_close();
  1852. return 0;
  1853. }
  1854. AVInputFormat sdp_demuxer = {
  1855. "sdp",
  1856. NULL_IF_CONFIG_SMALL("SDP"),
  1857. sizeof(RTSPState),
  1858. sdp_probe,
  1859. sdp_read_header,
  1860. rtsp_fetch_packet,
  1861. sdp_read_close,
  1862. };