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.

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