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.

2073 lines
74KB

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