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.

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