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.

1945 lines
67KB

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