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.

2142 lines
77KB

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