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.

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