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.

1603 lines
48KB

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