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.

2069 lines
74KB

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