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.

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