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.

2224 lines
75KB

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