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.

2107 lines
72KB

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