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.

2157 lines
78KB

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