rtsp.c 68 KB

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