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.

1951 lines
68KB

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