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.

1942 lines
67KB

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