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.

2108 lines
70KB

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