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.

1944 lines
67KB

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