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.

2104 lines
71KB

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