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.

2060 lines
68KB

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