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.

2123 lines
72KB

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