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.

1687 lines
52KB

  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. /* needed by inet_aton() */
  22. #define _SVID_SOURCE
  23. #include "libavutil/avstring.h"
  24. #include "avformat.h"
  25. #include <sys/time.h>
  26. #ifdef HAVE_SYS_SELECT_H
  27. #include <sys/select.h>
  28. #endif
  29. #include <strings.h>
  30. #include "network.h"
  31. #include "rtsp.h"
  32. #include "rtp_internal.h"
  33. #include "rdt.h"
  34. //#define DEBUG
  35. //#define DEBUG_RTP_TCP
  36. enum RTSPClientState {
  37. RTSP_STATE_IDLE,
  38. RTSP_STATE_PLAYING,
  39. RTSP_STATE_PAUSED,
  40. };
  41. enum RTSPServerType {
  42. RTSP_SERVER_RTP, /*< Standard-compliant RTP-server */
  43. RTSP_SERVER_REAL, /*< Realmedia-style server */
  44. RTSP_SERVER_LAST
  45. };
  46. enum RTSPTransport {
  47. RTSP_TRANSPORT_RTP,
  48. RTSP_TRANSPORT_RDT,
  49. RTSP_TRANSPORT_LAST
  50. };
  51. typedef struct RTSPState {
  52. URLContext *rtsp_hd; /* RTSP TCP connexion handle */
  53. int nb_rtsp_streams;
  54. struct RTSPStream **rtsp_streams;
  55. enum RTSPClientState state;
  56. int64_t seek_timestamp;
  57. /* XXX: currently we use unbuffered input */
  58. // ByteIOContext rtsp_gb;
  59. int seq; /* RTSP command sequence number */
  60. char session_id[512];
  61. enum RTSPTransport transport;
  62. enum RTSPLowerTransport lower_transport;
  63. enum RTSPServerType server_type;
  64. char last_reply[2048]; /* XXX: allocate ? */
  65. void *cur_tx;
  66. int need_subscription;
  67. } RTSPState;
  68. typedef struct RTSPStream {
  69. URLContext *rtp_handle; /* RTP stream handle */
  70. void *tx_ctx; /* RTP/RDT parse context */
  71. int stream_index; /* corresponding stream index, if any. -1 if none (MPEG2TS case) */
  72. int interleaved_min, interleaved_max; /* interleave ids, if TCP transport */
  73. char control_url[1024]; /* url for this stream (from SDP) */
  74. int sdp_port; /* port (from SDP content - not used in RTSP) */
  75. struct in_addr sdp_ip; /* IP address (from SDP content - not used in RTSP) */
  76. int sdp_ttl; /* IP TTL (from SDP content - not used in RTSP) */
  77. int sdp_payload_type; /* payload type - only used in SDP */
  78. rtp_payload_data_t rtp_payload_data; /* rtp payload parsing infos from SDP */
  79. RTPDynamicProtocolHandler *dynamic_handler; ///< Only valid if it's a dynamic protocol. (This is the handler structure)
  80. PayloadContext *dynamic_protocol_context; ///< Only valid if it's a dynamic protocol. (This is any private data associated with the dynamic protocol)
  81. } RTSPStream;
  82. static int rtsp_read_play(AVFormatContext *s);
  83. /* XXX: currently, the only way to change the protocols consists in
  84. changing this variable */
  85. #if LIBAVFORMAT_VERSION_INT < (53 << 16)
  86. int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
  87. #endif
  88. static int rtsp_probe(AVProbeData *p)
  89. {
  90. if (av_strstart(p->filename, "rtsp:", NULL))
  91. return AVPROBE_SCORE_MAX;
  92. return 0;
  93. }
  94. static int redir_isspace(int c)
  95. {
  96. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  97. }
  98. static void skip_spaces(const char **pp)
  99. {
  100. const char *p;
  101. p = *pp;
  102. while (redir_isspace(*p))
  103. p++;
  104. *pp = p;
  105. }
  106. static void get_word_sep(char *buf, int buf_size, const char *sep,
  107. const char **pp)
  108. {
  109. const char *p;
  110. char *q;
  111. p = *pp;
  112. if (*p == '/')
  113. p++;
  114. skip_spaces(&p);
  115. q = buf;
  116. while (!strchr(sep, *p) && *p != '\0') {
  117. if ((q - buf) < buf_size - 1)
  118. *q++ = *p;
  119. p++;
  120. }
  121. if (buf_size > 0)
  122. *q = '\0';
  123. *pp = p;
  124. }
  125. static void get_word(char *buf, int buf_size, const char **pp)
  126. {
  127. const char *p;
  128. char *q;
  129. p = *pp;
  130. skip_spaces(&p);
  131. q = buf;
  132. while (!redir_isspace(*p) && *p != '\0') {
  133. if ((q - buf) < buf_size - 1)
  134. *q++ = *p;
  135. p++;
  136. }
  137. if (buf_size > 0)
  138. *q = '\0';
  139. *pp = p;
  140. }
  141. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
  142. params>] */
  143. static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)
  144. {
  145. char buf[256];
  146. int i;
  147. AVCodec *c;
  148. const char *c_name;
  149. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  150. see if we can handle this kind of payload */
  151. get_word_sep(buf, sizeof(buf), "/", &p);
  152. if (payload_type >= RTP_PT_PRIVATE) {
  153. RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
  154. while(handler) {
  155. if (!strcmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
  156. codec->codec_id = handler->codec_id;
  157. rtsp_st->dynamic_handler= handler;
  158. if(handler->open) {
  159. rtsp_st->dynamic_protocol_context= handler->open();
  160. }
  161. break;
  162. }
  163. handler= handler->next;
  164. }
  165. } else {
  166. /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */
  167. /* search into AVRtpPayloadTypes[] */
  168. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  169. }
  170. c = avcodec_find_decoder(codec->codec_id);
  171. if (c && c->name)
  172. c_name = c->name;
  173. else
  174. c_name = (char *)NULL;
  175. if (c_name) {
  176. get_word_sep(buf, sizeof(buf), "/", &p);
  177. i = atoi(buf);
  178. switch (codec->codec_type) {
  179. case CODEC_TYPE_AUDIO:
  180. av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name);
  181. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  182. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  183. if (i > 0) {
  184. codec->sample_rate = i;
  185. get_word_sep(buf, sizeof(buf), "/", &p);
  186. i = atoi(buf);
  187. if (i > 0)
  188. codec->channels = i;
  189. // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the
  190. // frequency. No problem, but the sample rate is being set here by the sdp line. Upcoming patch forthcoming. (rdm)
  191. }
  192. av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);
  193. av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);
  194. break;
  195. case CODEC_TYPE_VIDEO:
  196. av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);
  197. break;
  198. default:
  199. break;
  200. }
  201. return 0;
  202. }
  203. return -1;
  204. }
  205. /* return the length and optionnaly the data */
  206. static int hex_to_data(uint8_t *data, const char *p)
  207. {
  208. int c, len, v;
  209. len = 0;
  210. v = 1;
  211. for(;;) {
  212. skip_spaces(&p);
  213. if (p == '\0')
  214. break;
  215. c = toupper((unsigned char)*p++);
  216. if (c >= '0' && c <= '9')
  217. c = c - '0';
  218. else if (c >= 'A' && c <= 'F')
  219. c = c - 'A' + 10;
  220. else
  221. break;
  222. v = (v << 4) | c;
  223. if (v & 0x100) {
  224. if (data)
  225. data[len] = v;
  226. len++;
  227. v = 1;
  228. }
  229. }
  230. return len;
  231. }
  232. static void sdp_parse_fmtp_config(AVCodecContext *codec, char *attr, char *value)
  233. {
  234. switch (codec->codec_id) {
  235. case CODEC_ID_MPEG4:
  236. case CODEC_ID_AAC:
  237. if (!strcmp(attr, "config")) {
  238. /* decode the hexa encoded parameter */
  239. int len = hex_to_data(NULL, value);
  240. codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
  241. if (!codec->extradata)
  242. return;
  243. codec->extradata_size = len;
  244. hex_to_data(codec->extradata, value);
  245. }
  246. break;
  247. default:
  248. break;
  249. }
  250. return;
  251. }
  252. typedef struct {
  253. const char *str;
  254. uint16_t type;
  255. uint32_t offset;
  256. } AttrNameMap;
  257. /* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
  258. #define ATTR_NAME_TYPE_INT 0
  259. #define ATTR_NAME_TYPE_STR 1
  260. static const AttrNameMap attr_names[]=
  261. {
  262. {"SizeLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, sizelength)},
  263. {"IndexLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexlength)},
  264. {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexdeltalength)},
  265. {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, profile_level_id)},
  266. {"StreamType", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, streamtype)},
  267. {"mode", ATTR_NAME_TYPE_STR, offsetof(rtp_payload_data_t, mode)},
  268. {NULL, -1, -1},
  269. };
  270. /** parse the attribute line from the fmtp a line of an sdp resonse. This is broken out as a function
  271. * because it is used in rtp_h264.c, which is forthcoming.
  272. */
  273. int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
  274. {
  275. skip_spaces(p);
  276. if(**p)
  277. {
  278. get_word_sep(attr, attr_size, "=", p);
  279. if (**p == '=')
  280. (*p)++;
  281. get_word_sep(value, value_size, ";", p);
  282. if (**p == ';')
  283. (*p)++;
  284. return 1;
  285. }
  286. return 0;
  287. }
  288. /* parse a SDP line and save stream attributes */
  289. static void sdp_parse_fmtp(AVStream *st, const char *p)
  290. {
  291. char attr[256];
  292. char value[4096];
  293. int i;
  294. RTSPStream *rtsp_st = st->priv_data;
  295. AVCodecContext *codec = st->codec;
  296. rtp_payload_data_t *rtp_payload_data = &rtsp_st->rtp_payload_data;
  297. /* loop on each attribute */
  298. while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
  299. {
  300. /* grab the codec extra_data from the config parameter of the fmtp line */
  301. sdp_parse_fmtp_config(codec, attr, value);
  302. /* Looking for a known attribute */
  303. for (i = 0; attr_names[i].str; ++i) {
  304. if (!strcasecmp(attr, attr_names[i].str)) {
  305. if (attr_names[i].type == ATTR_NAME_TYPE_INT)
  306. *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
  307. else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
  308. *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
  309. }
  310. }
  311. }
  312. }
  313. /** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
  314. * and end time.
  315. * Used for seeking in the rtp stream.
  316. */
  317. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  318. {
  319. char buf[256];
  320. skip_spaces(&p);
  321. if (!av_stristart(p, "npt=", &p))
  322. return;
  323. *start = AV_NOPTS_VALUE;
  324. *end = AV_NOPTS_VALUE;
  325. get_word_sep(buf, sizeof(buf), "-", &p);
  326. *start = parse_date(buf, 1);
  327. if (*p == '-') {
  328. p++;
  329. get_word_sep(buf, sizeof(buf), "-", &p);
  330. *end = parse_date(buf, 1);
  331. }
  332. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  333. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  334. }
  335. typedef struct SDPParseState {
  336. /* SDP only */
  337. struct in_addr default_ip;
  338. int default_ttl;
  339. } SDPParseState;
  340. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  341. int letter, const char *buf)
  342. {
  343. RTSPState *rt = s->priv_data;
  344. char buf1[64], st_type[64];
  345. const char *p;
  346. enum CodecType codec_type;
  347. int payload_type, i;
  348. AVStream *st;
  349. RTSPStream *rtsp_st;
  350. struct in_addr sdp_ip;
  351. int ttl;
  352. #ifdef DEBUG
  353. printf("sdp: %c='%s'\n", letter, buf);
  354. #endif
  355. p = buf;
  356. switch(letter) {
  357. case 'c':
  358. get_word(buf1, sizeof(buf1), &p);
  359. if (strcmp(buf1, "IN") != 0)
  360. return;
  361. get_word(buf1, sizeof(buf1), &p);
  362. if (strcmp(buf1, "IP4") != 0)
  363. return;
  364. get_word_sep(buf1, sizeof(buf1), "/", &p);
  365. if (inet_aton(buf1, &sdp_ip) == 0)
  366. return;
  367. ttl = 16;
  368. if (*p == '/') {
  369. p++;
  370. get_word_sep(buf1, sizeof(buf1), "/", &p);
  371. ttl = atoi(buf1);
  372. }
  373. if (s->nb_streams == 0) {
  374. s1->default_ip = sdp_ip;
  375. s1->default_ttl = ttl;
  376. } else {
  377. st = s->streams[s->nb_streams - 1];
  378. rtsp_st = st->priv_data;
  379. rtsp_st->sdp_ip = sdp_ip;
  380. rtsp_st->sdp_ttl = ttl;
  381. }
  382. break;
  383. case 's':
  384. av_strlcpy(s->title, p, sizeof(s->title));
  385. break;
  386. case 'i':
  387. if (s->nb_streams == 0) {
  388. av_strlcpy(s->comment, p, sizeof(s->comment));
  389. break;
  390. }
  391. break;
  392. case 'm':
  393. /* new stream */
  394. get_word(st_type, sizeof(st_type), &p);
  395. if (!strcmp(st_type, "audio")) {
  396. codec_type = CODEC_TYPE_AUDIO;
  397. } else if (!strcmp(st_type, "video")) {
  398. codec_type = CODEC_TYPE_VIDEO;
  399. } else {
  400. return;
  401. }
  402. rtsp_st = av_mallocz(sizeof(RTSPStream));
  403. if (!rtsp_st)
  404. return;
  405. rtsp_st->stream_index = -1;
  406. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  407. rtsp_st->sdp_ip = s1->default_ip;
  408. rtsp_st->sdp_ttl = s1->default_ttl;
  409. get_word(buf1, sizeof(buf1), &p); /* port */
  410. rtsp_st->sdp_port = atoi(buf1);
  411. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  412. /* XXX: handle list of formats */
  413. get_word(buf1, sizeof(buf1), &p); /* format list */
  414. rtsp_st->sdp_payload_type = atoi(buf1);
  415. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  416. /* no corresponding stream */
  417. } else {
  418. st = av_new_stream(s, 0);
  419. if (!st)
  420. return;
  421. st->priv_data = rtsp_st;
  422. rtsp_st->stream_index = st->index;
  423. st->codec->codec_type = codec_type;
  424. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  425. /* if standard payload type, we can find the codec right now */
  426. rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  427. }
  428. }
  429. /* put a default control url */
  430. av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
  431. break;
  432. case 'a':
  433. if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
  434. char proto[32];
  435. /* get the control url */
  436. st = s->streams[s->nb_streams - 1];
  437. rtsp_st = st->priv_data;
  438. /* XXX: may need to add full url resolution */
  439. url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
  440. if (proto[0] == '\0') {
  441. /* relative control URL */
  442. av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
  443. av_strlcat(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
  444. } else {
  445. av_strlcpy(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
  446. }
  447. } else if (av_strstart(p, "rtpmap:", &p)) {
  448. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  449. get_word(buf1, sizeof(buf1), &p);
  450. payload_type = atoi(buf1);
  451. for(i = 0; i < s->nb_streams;i++) {
  452. st = s->streams[i];
  453. rtsp_st = st->priv_data;
  454. if (rtsp_st->sdp_payload_type == payload_type) {
  455. sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
  456. }
  457. }
  458. } else if (av_strstart(p, "fmtp:", &p)) {
  459. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  460. get_word(buf1, sizeof(buf1), &p);
  461. payload_type = atoi(buf1);
  462. for(i = 0; i < s->nb_streams;i++) {
  463. st = s->streams[i];
  464. rtsp_st = st->priv_data;
  465. if (rtsp_st->sdp_payload_type == payload_type) {
  466. if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
  467. if(!rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf)) {
  468. sdp_parse_fmtp(st, p);
  469. }
  470. } else {
  471. sdp_parse_fmtp(st, p);
  472. }
  473. }
  474. }
  475. } else if(av_strstart(p, "framesize:", &p)) {
  476. // let dynamic protocol handlers have a stab at the line.
  477. get_word(buf1, sizeof(buf1), &p);
  478. payload_type = atoi(buf1);
  479. for(i = 0; i < s->nb_streams;i++) {
  480. st = s->streams[i];
  481. rtsp_st = st->priv_data;
  482. if (rtsp_st->sdp_payload_type == payload_type) {
  483. if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
  484. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf);
  485. }
  486. }
  487. }
  488. } else if(av_strstart(p, "range:", &p)) {
  489. int64_t start, end;
  490. // this is so that seeking on a streamed file can work.
  491. rtsp_parse_range_npt(p, &start, &end);
  492. s->start_time= start;
  493. s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
  494. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  495. if (atoi(p) == 1)
  496. rt->transport = RTSP_TRANSPORT_RDT;
  497. } else if (s->nb_streams > 0) {
  498. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  499. if (rtsp_st->dynamic_handler &&
  500. rtsp_st->dynamic_handler->parse_sdp_a_line)
  501. rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1,
  502. rtsp_st->dynamic_protocol_context, buf);
  503. }
  504. break;
  505. }
  506. }
  507. static int sdp_parse(AVFormatContext *s, const char *content)
  508. {
  509. const char *p;
  510. int letter;
  511. char buf[2048], *q;
  512. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  513. memset(s1, 0, sizeof(SDPParseState));
  514. p = content;
  515. for(;;) {
  516. skip_spaces(&p);
  517. letter = *p;
  518. if (letter == '\0')
  519. break;
  520. p++;
  521. if (*p != '=')
  522. goto next_line;
  523. p++;
  524. /* get the content */
  525. q = buf;
  526. while (*p != '\n' && *p != '\r' && *p != '\0') {
  527. if ((q - buf) < sizeof(buf) - 1)
  528. *q++ = *p;
  529. p++;
  530. }
  531. *q = '\0';
  532. sdp_parse_line(s, s1, letter, buf);
  533. next_line:
  534. while (*p != '\n' && *p != '\0')
  535. p++;
  536. if (*p == '\n')
  537. p++;
  538. }
  539. return 0;
  540. }
  541. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  542. {
  543. const char *p;
  544. int v;
  545. p = *pp;
  546. skip_spaces(&p);
  547. v = strtol(p, (char **)&p, 10);
  548. if (*p == '-') {
  549. p++;
  550. *min_ptr = v;
  551. v = strtol(p, (char **)&p, 10);
  552. *max_ptr = v;
  553. } else {
  554. *min_ptr = v;
  555. *max_ptr = v;
  556. }
  557. *pp = p;
  558. }
  559. /* XXX: only one transport specification is parsed */
  560. static void rtsp_parse_transport(RTSPHeader *reply, const char *p)
  561. {
  562. char transport_protocol[16];
  563. char profile[16];
  564. char lower_transport[16];
  565. char parameter[16];
  566. RTSPTransportField *th;
  567. char buf[256];
  568. reply->nb_transports = 0;
  569. for(;;) {
  570. skip_spaces(&p);
  571. if (*p == '\0')
  572. break;
  573. th = &reply->transports[reply->nb_transports];
  574. get_word_sep(transport_protocol, sizeof(transport_protocol),
  575. "/", &p);
  576. if (*p == '/')
  577. p++;
  578. if (!strcasecmp (transport_protocol, "rtp")) {
  579. get_word_sep(profile, sizeof(profile), "/;,", &p);
  580. lower_transport[0] = '\0';
  581. /* rtp/avp/<protocol> */
  582. if (*p == '/') {
  583. p++;
  584. get_word_sep(lower_transport, sizeof(lower_transport),
  585. ";,", &p);
  586. }
  587. th->transport = RTSP_TRANSPORT_RTP;
  588. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  589. !strcasecmp (transport_protocol, "x-real-rdt")) {
  590. /* x-pn-tng/<protocol> */
  591. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  592. profile[0] = '\0';
  593. th->transport = RTSP_TRANSPORT_RDT;
  594. }
  595. if (!strcasecmp(lower_transport, "TCP"))
  596. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  597. else
  598. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  599. if (*p == ';')
  600. p++;
  601. /* get each parameter */
  602. while (*p != '\0' && *p != ',') {
  603. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  604. if (!strcmp(parameter, "port")) {
  605. if (*p == '=') {
  606. p++;
  607. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  608. }
  609. } else if (!strcmp(parameter, "client_port")) {
  610. if (*p == '=') {
  611. p++;
  612. rtsp_parse_range(&th->client_port_min,
  613. &th->client_port_max, &p);
  614. }
  615. } else if (!strcmp(parameter, "server_port")) {
  616. if (*p == '=') {
  617. p++;
  618. rtsp_parse_range(&th->server_port_min,
  619. &th->server_port_max, &p);
  620. }
  621. } else if (!strcmp(parameter, "interleaved")) {
  622. if (*p == '=') {
  623. p++;
  624. rtsp_parse_range(&th->interleaved_min,
  625. &th->interleaved_max, &p);
  626. }
  627. } else if (!strcmp(parameter, "multicast")) {
  628. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  629. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  630. } else if (!strcmp(parameter, "ttl")) {
  631. if (*p == '=') {
  632. p++;
  633. th->ttl = strtol(p, (char **)&p, 10);
  634. }
  635. } else if (!strcmp(parameter, "destination")) {
  636. struct in_addr ipaddr;
  637. if (*p == '=') {
  638. p++;
  639. get_word_sep(buf, sizeof(buf), ";,", &p);
  640. if (inet_aton(buf, &ipaddr))
  641. th->destination = ntohl(ipaddr.s_addr);
  642. }
  643. }
  644. while (*p != ';' && *p != '\0' && *p != ',')
  645. p++;
  646. if (*p == ';')
  647. p++;
  648. }
  649. if (*p == ',')
  650. p++;
  651. reply->nb_transports++;
  652. }
  653. }
  654. void rtsp_parse_line(RTSPHeader *reply, const char *buf)
  655. {
  656. const char *p;
  657. /* NOTE: we do case independent match for broken servers */
  658. p = buf;
  659. if (av_stristart(p, "Session:", &p)) {
  660. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  661. } else if (av_stristart(p, "Content-Length:", &p)) {
  662. reply->content_length = strtol(p, NULL, 10);
  663. } else if (av_stristart(p, "Transport:", &p)) {
  664. rtsp_parse_transport(reply, p);
  665. } else if (av_stristart(p, "CSeq:", &p)) {
  666. reply->seq = strtol(p, NULL, 10);
  667. } else if (av_stristart(p, "Range:", &p)) {
  668. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  669. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  670. skip_spaces(&p);
  671. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  672. }
  673. }
  674. static int url_readbuf(URLContext *h, unsigned char *buf, int size)
  675. {
  676. int ret, len;
  677. len = 0;
  678. while (len < size) {
  679. ret = url_read(h, buf+len, size-len);
  680. if (ret < 1)
  681. return ret;
  682. len += ret;
  683. }
  684. return len;
  685. }
  686. /* skip a RTP/TCP interleaved packet */
  687. static void rtsp_skip_packet(AVFormatContext *s)
  688. {
  689. RTSPState *rt = s->priv_data;
  690. int ret, len, len1;
  691. uint8_t buf[1024];
  692. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  693. if (ret != 3)
  694. return;
  695. len = AV_RB16(buf + 1);
  696. #ifdef DEBUG
  697. printf("skipping RTP packet len=%d\n", len);
  698. #endif
  699. /* skip payload */
  700. while (len > 0) {
  701. len1 = len;
  702. if (len1 > sizeof(buf))
  703. len1 = sizeof(buf);
  704. ret = url_readbuf(rt->rtsp_hd, buf, len1);
  705. if (ret != len1)
  706. return;
  707. len -= len1;
  708. }
  709. }
  710. static void rtsp_send_cmd(AVFormatContext *s,
  711. const char *cmd, RTSPHeader *reply,
  712. unsigned char **content_ptr)
  713. {
  714. RTSPState *rt = s->priv_data;
  715. char buf[4096], buf1[1024], *q;
  716. unsigned char ch;
  717. const char *p;
  718. int content_length, line_count;
  719. unsigned char *content = NULL;
  720. memset(reply, 0, sizeof(RTSPHeader));
  721. rt->seq++;
  722. av_strlcpy(buf, cmd, sizeof(buf));
  723. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  724. av_strlcat(buf, buf1, sizeof(buf));
  725. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  726. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  727. av_strlcat(buf, buf1, sizeof(buf));
  728. }
  729. av_strlcat(buf, "\r\n", sizeof(buf));
  730. #ifdef DEBUG
  731. printf("Sending:\n%s--\n", buf);
  732. #endif
  733. url_write(rt->rtsp_hd, buf, strlen(buf));
  734. /* parse reply (XXX: use buffers) */
  735. line_count = 0;
  736. rt->last_reply[0] = '\0';
  737. for(;;) {
  738. q = buf;
  739. for(;;) {
  740. if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
  741. break;
  742. if (ch == '\n')
  743. break;
  744. if (ch == '$') {
  745. /* XXX: only parse it if first char on line ? */
  746. rtsp_skip_packet(s);
  747. } else if (ch != '\r') {
  748. if ((q - buf) < sizeof(buf) - 1)
  749. *q++ = ch;
  750. }
  751. }
  752. *q = '\0';
  753. #ifdef DEBUG
  754. printf("line='%s'\n", buf);
  755. #endif
  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. } else {
  766. rtsp_parse_line(reply, p);
  767. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  768. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  769. }
  770. line_count++;
  771. }
  772. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  773. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  774. content_length = reply->content_length;
  775. if (content_length > 0) {
  776. /* leave some room for a trailing '\0' (useful for simple parsing) */
  777. content = av_malloc(content_length + 1);
  778. (void)url_readbuf(rt->rtsp_hd, content, content_length);
  779. content[content_length] = '\0';
  780. }
  781. if (content_ptr)
  782. *content_ptr = content;
  783. else
  784. av_free(content);
  785. }
  786. /* close and free RTSP streams */
  787. static void rtsp_close_streams(RTSPState *rt)
  788. {
  789. int i;
  790. RTSPStream *rtsp_st;
  791. for(i=0;i<rt->nb_rtsp_streams;i++) {
  792. rtsp_st = rt->rtsp_streams[i];
  793. if (rtsp_st) {
  794. if (rtsp_st->tx_ctx) {
  795. if (rt->transport == RTSP_TRANSPORT_RDT)
  796. ff_rdt_parse_close(rtsp_st->tx_ctx);
  797. else
  798. rtp_parse_close(rtsp_st->tx_ctx);
  799. }
  800. if (rtsp_st->rtp_handle)
  801. url_close(rtsp_st->rtp_handle);
  802. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  803. rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
  804. }
  805. }
  806. av_free(rt->rtsp_streams);
  807. }
  808. static int
  809. rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  810. {
  811. RTSPState *rt = s->priv_data;
  812. AVStream *st = NULL;
  813. /* open the RTP context */
  814. if (rtsp_st->stream_index >= 0)
  815. st = s->streams[rtsp_st->stream_index];
  816. if (!st)
  817. s->ctx_flags |= AVFMTCTX_NOHEADER;
  818. if (rt->transport == RTSP_TRANSPORT_RDT)
  819. rtsp_st->tx_ctx = ff_rdt_parse_open(s, st->index,
  820. rtsp_st->dynamic_protocol_context,
  821. rtsp_st->dynamic_handler);
  822. else
  823. rtsp_st->tx_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  824. rtsp_st->sdp_payload_type,
  825. &rtsp_st->rtp_payload_data);
  826. if (!rtsp_st->tx_ctx) {
  827. return AVERROR(ENOMEM);
  828. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  829. if(rtsp_st->dynamic_handler) {
  830. rtp_parse_set_dynamic_protocol(rtsp_st->tx_ctx,
  831. rtsp_st->dynamic_protocol_context,
  832. rtsp_st->dynamic_handler);
  833. }
  834. }
  835. return 0;
  836. }
  837. /**
  838. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  839. */
  840. static int
  841. make_setup_request (AVFormatContext *s, const char *host, int port,
  842. int lower_transport, const char *real_challenge)
  843. {
  844. RTSPState *rt = s->priv_data;
  845. int j, i, err;
  846. RTSPStream *rtsp_st;
  847. RTSPHeader reply1, *reply = &reply1;
  848. char cmd[2048];
  849. const char *trans_pref;
  850. if (rt->transport == RTSP_TRANSPORT_RDT)
  851. trans_pref = "x-pn-tng";
  852. else
  853. trans_pref = "RTP/AVP";
  854. /* for each stream, make the setup request */
  855. /* XXX: we assume the same server is used for the control of each
  856. RTSP stream */
  857. for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  858. char transport[2048];
  859. rtsp_st = rt->rtsp_streams[i];
  860. /* RTP/UDP */
  861. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  862. char buf[256];
  863. /* first try in specified port range */
  864. if (RTSP_RTP_PORT_MIN != 0) {
  865. while(j <= RTSP_RTP_PORT_MAX) {
  866. snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
  867. j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
  868. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
  869. goto rtp_opened;
  870. }
  871. }
  872. }
  873. /* then try on any port
  874. ** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  875. ** err = AVERROR_INVALIDDATA;
  876. ** goto fail;
  877. ** }
  878. */
  879. rtp_opened:
  880. port = rtp_get_local_port(rtsp_st->rtp_handle);
  881. snprintf(transport, sizeof(transport) - 1,
  882. "%s/UDP;", trans_pref);
  883. if (rt->server_type != RTSP_SERVER_REAL)
  884. av_strlcat(transport, "unicast;", sizeof(transport));
  885. av_strlcatf(transport, sizeof(transport),
  886. "client_port=%d", port);
  887. if (rt->transport == RTSP_TRANSPORT_RTP)
  888. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  889. }
  890. /* RTP/TCP */
  891. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  892. snprintf(transport, sizeof(transport) - 1,
  893. "%s/TCP", trans_pref);
  894. }
  895. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  896. snprintf(transport, sizeof(transport) - 1,
  897. "%s/UDP;multicast", trans_pref);
  898. }
  899. if (rt->server_type == RTSP_SERVER_REAL)
  900. av_strlcat(transport, ";mode=play", sizeof(transport));
  901. snprintf(cmd, sizeof(cmd),
  902. "SETUP %s RTSP/1.0\r\n"
  903. "Transport: %s\r\n",
  904. rtsp_st->control_url, transport);
  905. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  906. char real_res[41], real_csum[9];
  907. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  908. real_challenge);
  909. av_strlcatf(cmd, sizeof(cmd),
  910. "If-Match: %s\r\n"
  911. "RealChallenge2: %s, sd=%s\r\n",
  912. rt->session_id, real_res, real_csum);
  913. }
  914. rtsp_send_cmd(s, cmd, reply, NULL);
  915. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  916. err = 1;
  917. goto fail;
  918. } else if (reply->status_code != RTSP_STATUS_OK ||
  919. reply->nb_transports != 1) {
  920. err = AVERROR_INVALIDDATA;
  921. goto fail;
  922. }
  923. /* XXX: same protocol for all streams is required */
  924. if (i > 0) {
  925. if (reply->transports[0].lower_transport != rt->lower_transport ||
  926. reply->transports[0].transport != rt->transport) {
  927. err = AVERROR_INVALIDDATA;
  928. goto fail;
  929. }
  930. } else {
  931. rt->lower_transport = reply->transports[0].lower_transport;
  932. rt->transport = reply->transports[0].transport;
  933. }
  934. /* close RTP connection if not choosen */
  935. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  936. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  937. url_close(rtsp_st->rtp_handle);
  938. rtsp_st->rtp_handle = NULL;
  939. }
  940. switch(reply->transports[0].lower_transport) {
  941. case RTSP_LOWER_TRANSPORT_TCP:
  942. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  943. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  944. break;
  945. case RTSP_LOWER_TRANSPORT_UDP:
  946. {
  947. char url[1024];
  948. /* XXX: also use address if specified */
  949. snprintf(url, sizeof(url), "rtp://%s:%d",
  950. host, reply->transports[0].server_port_min);
  951. if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  952. err = AVERROR_INVALIDDATA;
  953. goto fail;
  954. }
  955. }
  956. break;
  957. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  958. {
  959. char url[1024];
  960. struct in_addr in;
  961. in.s_addr = htonl(reply->transports[0].destination);
  962. snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
  963. inet_ntoa(in),
  964. reply->transports[0].port_min,
  965. reply->transports[0].ttl);
  966. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  967. err = AVERROR_INVALIDDATA;
  968. goto fail;
  969. }
  970. }
  971. break;
  972. }
  973. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  974. goto fail;
  975. }
  976. if (rt->server_type == RTSP_SERVER_REAL)
  977. rt->need_subscription = 1;
  978. return 0;
  979. fail:
  980. for (i=0; i<rt->nb_rtsp_streams; i++) {
  981. if (rt->rtsp_streams[i]->rtp_handle) {
  982. url_close(rt->rtsp_streams[i]->rtp_handle);
  983. rt->rtsp_streams[i]->rtp_handle = NULL;
  984. }
  985. }
  986. return err;
  987. }
  988. static int rtsp_read_header(AVFormatContext *s,
  989. AVFormatParameters *ap)
  990. {
  991. RTSPState *rt = s->priv_data;
  992. char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
  993. URLContext *rtsp_hd;
  994. int port, ret, err;
  995. RTSPHeader reply1, *reply = &reply1;
  996. unsigned char *content = NULL;
  997. int lower_transport_mask = 0;
  998. char real_challenge[64];
  999. /* extract hostname and port */
  1000. url_split(NULL, 0, NULL, 0,
  1001. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1002. if (port < 0)
  1003. port = RTSP_DEFAULT_PORT;
  1004. /* search for options */
  1005. option_list = strchr(path, '?');
  1006. if (option_list) {
  1007. /* remove the options from the path */
  1008. *option_list++ = 0;
  1009. while(option_list) {
  1010. /* move the option pointer */
  1011. option = option_list;
  1012. option_list = strchr(option_list, '&');
  1013. if (option_list)
  1014. *(option_list++) = 0;
  1015. /* handle the options */
  1016. if (strcmp(option, "udp") == 0)
  1017. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
  1018. else if (strcmp(option, "multicast") == 0)
  1019. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1020. else if (strcmp(option, "tcp") == 0)
  1021. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
  1022. }
  1023. }
  1024. if (!lower_transport_mask)
  1025. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_LAST) - 1;
  1026. /* open the tcp connexion */
  1027. snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
  1028. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
  1029. return AVERROR(EIO);
  1030. rt->rtsp_hd = rtsp_hd;
  1031. rt->seq = 0;
  1032. /* request options supported by the server; this also detects server type */
  1033. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1034. snprintf(cmd, sizeof(cmd),
  1035. "OPTIONS %s RTSP/1.0\r\n", s->filename);
  1036. if (rt->server_type == RTSP_SERVER_REAL)
  1037. av_strlcat(cmd,
  1038. /**
  1039. * The following entries are required for proper
  1040. * streaming from a Realmedia server. They are
  1041. * interdependent in some way although we currently
  1042. * don't quite understand how. Values were copied
  1043. * from mplayer SVN r23589.
  1044. * @param CompanyID is a 16-byte ID in base64
  1045. * @param ClientChallenge is a 16-byte ID in hex
  1046. */
  1047. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1048. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1049. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1050. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1051. sizeof(cmd));
  1052. rtsp_send_cmd(s, cmd, reply, NULL);
  1053. if (reply->status_code != RTSP_STATUS_OK) {
  1054. err = AVERROR_INVALIDDATA;
  1055. goto fail;
  1056. }
  1057. /* detect server type if not standard-compliant RTP */
  1058. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1059. rt->server_type = RTSP_SERVER_REAL;
  1060. continue;
  1061. } else if (rt->server_type == RTSP_SERVER_REAL) {
  1062. strcpy(real_challenge, reply->real_challenge);
  1063. }
  1064. break;
  1065. }
  1066. /* describe the stream */
  1067. snprintf(cmd, sizeof(cmd),
  1068. "DESCRIBE %s RTSP/1.0\r\n"
  1069. "Accept: application/sdp\r\n",
  1070. s->filename);
  1071. if (rt->server_type == RTSP_SERVER_REAL) {
  1072. /**
  1073. * The Require: attribute is needed for proper streaming from
  1074. * Realmedia servers.
  1075. */
  1076. av_strlcat(cmd,
  1077. "Require: com.real.retain-entity-for-setup\r\n",
  1078. sizeof(cmd));
  1079. }
  1080. rtsp_send_cmd(s, cmd, reply, &content);
  1081. if (!content) {
  1082. err = AVERROR_INVALIDDATA;
  1083. goto fail;
  1084. }
  1085. if (reply->status_code != RTSP_STATUS_OK) {
  1086. err = AVERROR_INVALIDDATA;
  1087. goto fail;
  1088. }
  1089. /* now we got the SDP description, we parse it */
  1090. ret = sdp_parse(s, (const char *)content);
  1091. av_freep(&content);
  1092. if (ret < 0) {
  1093. err = AVERROR_INVALIDDATA;
  1094. goto fail;
  1095. }
  1096. do {
  1097. int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)];
  1098. err = make_setup_request(s, host, port, lower_transport,
  1099. rt->server_type == RTSP_SERVER_REAL ?
  1100. real_challenge : NULL);
  1101. if (err < 0)
  1102. goto fail;
  1103. lower_transport_mask &= ~(1 << lower_transport);
  1104. if (lower_transport_mask == 0 && err == 1) {
  1105. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1106. goto fail;
  1107. }
  1108. } while (err);
  1109. rt->state = RTSP_STATE_IDLE;
  1110. rt->seek_timestamp = 0; /* default is to start stream at position
  1111. zero */
  1112. if (ap->initial_pause) {
  1113. /* do not start immediately */
  1114. } else {
  1115. if (rtsp_read_play(s) < 0) {
  1116. err = AVERROR_INVALIDDATA;
  1117. goto fail;
  1118. }
  1119. }
  1120. return 0;
  1121. fail:
  1122. rtsp_close_streams(rt);
  1123. av_freep(&content);
  1124. url_close(rt->rtsp_hd);
  1125. return err;
  1126. }
  1127. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1128. uint8_t *buf, int buf_size)
  1129. {
  1130. RTSPState *rt = s->priv_data;
  1131. int id, len, i, ret;
  1132. RTSPStream *rtsp_st;
  1133. #ifdef DEBUG_RTP_TCP
  1134. printf("tcp_read_packet:\n");
  1135. #endif
  1136. redo:
  1137. for(;;) {
  1138. ret = url_readbuf(rt->rtsp_hd, buf, 1);
  1139. #ifdef DEBUG_RTP_TCP
  1140. printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
  1141. #endif
  1142. if (ret != 1)
  1143. return -1;
  1144. if (buf[0] == '$')
  1145. break;
  1146. }
  1147. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  1148. if (ret != 3)
  1149. return -1;
  1150. id = buf[0];
  1151. len = AV_RB16(buf + 1);
  1152. #ifdef DEBUG_RTP_TCP
  1153. printf("id=%d len=%d\n", id, len);
  1154. #endif
  1155. if (len > buf_size || len < 12)
  1156. goto redo;
  1157. /* get the data */
  1158. ret = url_readbuf(rt->rtsp_hd, buf, len);
  1159. if (ret != len)
  1160. return -1;
  1161. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1162. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1163. return -1;
  1164. /* find the matching stream */
  1165. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1166. rtsp_st = rt->rtsp_streams[i];
  1167. if (id >= rtsp_st->interleaved_min &&
  1168. id <= rtsp_st->interleaved_max)
  1169. goto found;
  1170. }
  1171. goto redo;
  1172. found:
  1173. *prtsp_st = rtsp_st;
  1174. return len;
  1175. }
  1176. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1177. uint8_t *buf, int buf_size)
  1178. {
  1179. RTSPState *rt = s->priv_data;
  1180. RTSPStream *rtsp_st;
  1181. fd_set rfds;
  1182. int fd1, fd2, fd_max, n, i, ret;
  1183. struct timeval tv;
  1184. for(;;) {
  1185. if (url_interrupt_cb())
  1186. return AVERROR(EINTR);
  1187. FD_ZERO(&rfds);
  1188. fd_max = -1;
  1189. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1190. rtsp_st = rt->rtsp_streams[i];
  1191. /* currently, we cannot probe RTCP handle because of blocking restrictions */
  1192. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1193. if (fd1 > fd_max)
  1194. fd_max = fd1;
  1195. FD_SET(fd1, &rfds);
  1196. }
  1197. tv.tv_sec = 0;
  1198. tv.tv_usec = 100 * 1000;
  1199. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1200. if (n > 0) {
  1201. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1202. rtsp_st = rt->rtsp_streams[i];
  1203. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1204. if (FD_ISSET(fd1, &rfds)) {
  1205. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1206. if (ret > 0) {
  1207. *prtsp_st = rtsp_st;
  1208. return ret;
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. static int rtsp_read_packet(AVFormatContext *s,
  1216. AVPacket *pkt)
  1217. {
  1218. RTSPState *rt = s->priv_data;
  1219. RTSPStream *rtsp_st;
  1220. int ret, len;
  1221. uint8_t buf[RTP_MAX_PACKET_LENGTH];
  1222. if (rt->server_type == RTSP_SERVER_REAL && rt->need_subscription) {
  1223. int i;
  1224. RTSPHeader reply1, *reply = &reply1;
  1225. char cmd[1024];
  1226. snprintf(cmd, sizeof(cmd),
  1227. "SET_PARAMETER %s RTSP/1.0\r\n"
  1228. "Subscribe: ",
  1229. s->filename);
  1230. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1231. if (i != 0) av_strlcat(cmd, ",", sizeof(cmd));
  1232. ff_rdt_subscribe_rule(cmd, sizeof(cmd), i, 0);
  1233. if (rt->transport == RTSP_TRANSPORT_RDT)
  1234. ff_rdt_subscribe_rule2(
  1235. rt->rtsp_streams[i]->tx_ctx,
  1236. cmd, sizeof(cmd), i, 0);
  1237. }
  1238. av_strlcat(cmd, "\r\n", sizeof(cmd));
  1239. rtsp_send_cmd(s, cmd, reply, NULL);
  1240. if (reply->status_code != RTSP_STATUS_OK)
  1241. return AVERROR_INVALIDDATA;
  1242. rt->need_subscription = 0;
  1243. if (rt->state == RTSP_STATE_PLAYING)
  1244. rtsp_read_play (s);
  1245. }
  1246. /* get next frames from the same RTP packet */
  1247. if (rt->cur_tx) {
  1248. if (rt->transport == RTSP_TRANSPORT_RDT)
  1249. ret = ff_rdt_parse_packet(rt->cur_tx, pkt, NULL, 0);
  1250. else
  1251. ret = rtp_parse_packet(rt->cur_tx, pkt, NULL, 0);
  1252. if (ret == 0) {
  1253. rt->cur_tx = NULL;
  1254. return 0;
  1255. } else if (ret == 1) {
  1256. return 0;
  1257. } else {
  1258. rt->cur_tx = NULL;
  1259. }
  1260. }
  1261. /* read next RTP packet */
  1262. redo:
  1263. switch(rt->lower_transport) {
  1264. default:
  1265. case RTSP_LOWER_TRANSPORT_TCP:
  1266. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1267. break;
  1268. case RTSP_LOWER_TRANSPORT_UDP:
  1269. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1270. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1271. if (len >=0 && rtsp_st->tx_ctx && rt->transport == RTSP_TRANSPORT_RTP)
  1272. rtp_check_and_send_back_rr(rtsp_st->tx_ctx, len);
  1273. break;
  1274. }
  1275. if (len < 0)
  1276. return len;
  1277. if (rt->transport == RTSP_TRANSPORT_RDT)
  1278. ret = ff_rdt_parse_packet(rtsp_st->tx_ctx, pkt, buf, len);
  1279. else
  1280. ret = rtp_parse_packet(rtsp_st->tx_ctx, pkt, buf, len);
  1281. if (ret < 0)
  1282. goto redo;
  1283. if (ret == 1) {
  1284. /* more packets may follow, so we save the RTP context */
  1285. rt->cur_tx = rtsp_st->tx_ctx;
  1286. }
  1287. return 0;
  1288. }
  1289. static int rtsp_read_play(AVFormatContext *s)
  1290. {
  1291. RTSPState *rt = s->priv_data;
  1292. RTSPHeader reply1, *reply = &reply1;
  1293. char cmd[1024];
  1294. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1295. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1296. if (rt->state == RTSP_STATE_PAUSED) {
  1297. snprintf(cmd, sizeof(cmd),
  1298. "PLAY %s RTSP/1.0\r\n",
  1299. s->filename);
  1300. } else {
  1301. snprintf(cmd, sizeof(cmd),
  1302. "PLAY %s RTSP/1.0\r\n"
  1303. "Range: npt=%0.3f-\r\n",
  1304. s->filename,
  1305. (double)rt->seek_timestamp / AV_TIME_BASE);
  1306. }
  1307. rtsp_send_cmd(s, cmd, reply, NULL);
  1308. if (reply->status_code != RTSP_STATUS_OK) {
  1309. return -1;
  1310. }
  1311. }
  1312. rt->state = RTSP_STATE_PLAYING;
  1313. return 0;
  1314. }
  1315. /* pause the stream */
  1316. static int rtsp_read_pause(AVFormatContext *s)
  1317. {
  1318. RTSPState *rt = s->priv_data;
  1319. RTSPHeader reply1, *reply = &reply1;
  1320. char cmd[1024];
  1321. rt = s->priv_data;
  1322. if (rt->state != RTSP_STATE_PLAYING)
  1323. return 0;
  1324. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1325. snprintf(cmd, sizeof(cmd),
  1326. "PAUSE %s RTSP/1.0\r\n",
  1327. s->filename);
  1328. rtsp_send_cmd(s, cmd, reply, NULL);
  1329. if (reply->status_code != RTSP_STATUS_OK) {
  1330. return -1;
  1331. }
  1332. }
  1333. rt->state = RTSP_STATE_PAUSED;
  1334. return 0;
  1335. }
  1336. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1337. int64_t timestamp, int flags)
  1338. {
  1339. RTSPState *rt = s->priv_data;
  1340. rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
  1341. switch(rt->state) {
  1342. default:
  1343. case RTSP_STATE_IDLE:
  1344. break;
  1345. case RTSP_STATE_PLAYING:
  1346. if (rtsp_read_play(s) != 0)
  1347. return -1;
  1348. break;
  1349. case RTSP_STATE_PAUSED:
  1350. rt->state = RTSP_STATE_IDLE;
  1351. break;
  1352. }
  1353. return 0;
  1354. }
  1355. static int rtsp_read_close(AVFormatContext *s)
  1356. {
  1357. RTSPState *rt = s->priv_data;
  1358. RTSPHeader reply1, *reply = &reply1;
  1359. char cmd[1024];
  1360. #if 0
  1361. /* NOTE: it is valid to flush the buffer here */
  1362. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1363. url_fclose(&rt->rtsp_gb);
  1364. }
  1365. #endif
  1366. snprintf(cmd, sizeof(cmd),
  1367. "TEARDOWN %s RTSP/1.0\r\n",
  1368. s->filename);
  1369. rtsp_send_cmd(s, cmd, reply, NULL);
  1370. rtsp_close_streams(rt);
  1371. url_close(rt->rtsp_hd);
  1372. return 0;
  1373. }
  1374. #ifdef CONFIG_RTSP_DEMUXER
  1375. AVInputFormat rtsp_demuxer = {
  1376. "rtsp",
  1377. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1378. sizeof(RTSPState),
  1379. rtsp_probe,
  1380. rtsp_read_header,
  1381. rtsp_read_packet,
  1382. rtsp_read_close,
  1383. rtsp_read_seek,
  1384. .flags = AVFMT_NOFILE,
  1385. .read_play = rtsp_read_play,
  1386. .read_pause = rtsp_read_pause,
  1387. };
  1388. #endif
  1389. static int sdp_probe(AVProbeData *p1)
  1390. {
  1391. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1392. /* we look for a line beginning "c=IN IP4" */
  1393. while (p < p_end && *p != '\0') {
  1394. if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
  1395. return AVPROBE_SCORE_MAX / 2;
  1396. while(p < p_end - 1 && *p != '\n') p++;
  1397. if (++p >= p_end)
  1398. break;
  1399. if (*p == '\r')
  1400. p++;
  1401. }
  1402. return 0;
  1403. }
  1404. #define SDP_MAX_SIZE 8192
  1405. static int sdp_read_header(AVFormatContext *s,
  1406. AVFormatParameters *ap)
  1407. {
  1408. RTSPState *rt = s->priv_data;
  1409. RTSPStream *rtsp_st;
  1410. int size, i, err;
  1411. char *content;
  1412. char url[1024];
  1413. /* read the whole sdp file */
  1414. /* XXX: better loading */
  1415. content = av_malloc(SDP_MAX_SIZE);
  1416. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1417. if (size <= 0) {
  1418. av_free(content);
  1419. return AVERROR_INVALIDDATA;
  1420. }
  1421. content[size] ='\0';
  1422. sdp_parse(s, content);
  1423. av_free(content);
  1424. /* open each RTP stream */
  1425. for(i=0;i<rt->nb_rtsp_streams;i++) {
  1426. rtsp_st = rt->rtsp_streams[i];
  1427. snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
  1428. inet_ntoa(rtsp_st->sdp_ip),
  1429. rtsp_st->sdp_port,
  1430. rtsp_st->sdp_port,
  1431. rtsp_st->sdp_ttl);
  1432. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1433. err = AVERROR_INVALIDDATA;
  1434. goto fail;
  1435. }
  1436. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1437. goto fail;
  1438. }
  1439. return 0;
  1440. fail:
  1441. rtsp_close_streams(rt);
  1442. return err;
  1443. }
  1444. static int sdp_read_packet(AVFormatContext *s,
  1445. AVPacket *pkt)
  1446. {
  1447. return rtsp_read_packet(s, pkt);
  1448. }
  1449. static int sdp_read_close(AVFormatContext *s)
  1450. {
  1451. RTSPState *rt = s->priv_data;
  1452. rtsp_close_streams(rt);
  1453. return 0;
  1454. }
  1455. #ifdef CONFIG_SDP_DEMUXER
  1456. AVInputFormat sdp_demuxer = {
  1457. "sdp",
  1458. NULL_IF_CONFIG_SMALL("SDP"),
  1459. sizeof(RTSPState),
  1460. sdp_probe,
  1461. sdp_read_header,
  1462. sdp_read_packet,
  1463. sdp_read_close,
  1464. };
  1465. #endif
  1466. #ifdef CONFIG_REDIR_DEMUXER
  1467. /* dummy redirector format (used directly in av_open_input_file now) */
  1468. static int redir_probe(AVProbeData *pd)
  1469. {
  1470. const char *p;
  1471. p = pd->buf;
  1472. while (redir_isspace(*p))
  1473. p++;
  1474. if (av_strstart(p, "http://", NULL) ||
  1475. av_strstart(p, "rtsp://", NULL))
  1476. return AVPROBE_SCORE_MAX;
  1477. return 0;
  1478. }
  1479. static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1480. {
  1481. char buf[4096], *q;
  1482. int c;
  1483. AVFormatContext *ic = NULL;
  1484. ByteIOContext *f = s->pb;
  1485. /* parse each URL and try to open it */
  1486. c = url_fgetc(f);
  1487. while (c != URL_EOF) {
  1488. /* skip spaces */
  1489. for(;;) {
  1490. if (!redir_isspace(c))
  1491. break;
  1492. c = url_fgetc(f);
  1493. }
  1494. if (c == URL_EOF)
  1495. break;
  1496. /* record url */
  1497. q = buf;
  1498. for(;;) {
  1499. if (c == URL_EOF || redir_isspace(c))
  1500. break;
  1501. if ((q - buf) < sizeof(buf) - 1)
  1502. *q++ = c;
  1503. c = url_fgetc(f);
  1504. }
  1505. *q = '\0';
  1506. //printf("URL='%s'\n", buf);
  1507. /* try to open the media file */
  1508. if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
  1509. break;
  1510. }
  1511. if (!ic)
  1512. return AVERROR(EIO);
  1513. *s = *ic;
  1514. url_fclose(f);
  1515. return 0;
  1516. }
  1517. AVInputFormat redir_demuxer = {
  1518. "redir",
  1519. NULL_IF_CONFIG_SMALL("Redirector format"),
  1520. 0,
  1521. redir_probe,
  1522. redir_read_header,
  1523. NULL,
  1524. NULL,
  1525. };
  1526. #endif