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.

2160 lines
73KB

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