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.

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