rtsp.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  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. /**
  399. * Parse the sdp description and allocate the rtp streams and the
  400. * pollfd array used for udp ones.
  401. */
  402. int ff_sdp_parse(AVFormatContext *s, const char *content)
  403. {
  404. RTSPState *rt = s->priv_data;
  405. const char *p;
  406. int letter;
  407. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  408. * contain long SDP lines containing complete ASF Headers (several
  409. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  410. * "rulebooks" describing their properties. Therefore, the SDP line
  411. * buffer is large.
  412. *
  413. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  414. * in rtpdec_xiph.c. */
  415. char buf[16384], *q;
  416. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  417. memset(s1, 0, sizeof(SDPParseState));
  418. p = content;
  419. for (;;) {
  420. p += strspn(p, SPACE_CHARS);
  421. letter = *p;
  422. if (letter == '\0')
  423. break;
  424. p++;
  425. if (*p != '=')
  426. goto next_line;
  427. p++;
  428. /* get the content */
  429. q = buf;
  430. while (*p != '\n' && *p != '\r' && *p != '\0') {
  431. if ((q - buf) < sizeof(buf) - 1)
  432. *q++ = *p;
  433. p++;
  434. }
  435. *q = '\0';
  436. sdp_parse_line(s, s1, letter, buf);
  437. next_line:
  438. while (*p != '\n' && *p != '\0')
  439. p++;
  440. if (*p == '\n')
  441. p++;
  442. }
  443. rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
  444. if (!rt->p) return AVERROR(ENOMEM);
  445. return 0;
  446. }
  447. #endif /* CONFIG_RTPDEC */
  448. void ff_rtsp_undo_setup(AVFormatContext *s)
  449. {
  450. RTSPState *rt = s->priv_data;
  451. int i;
  452. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  453. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  454. if (!rtsp_st)
  455. continue;
  456. if (rtsp_st->transport_priv) {
  457. if (s->oformat) {
  458. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  459. av_write_trailer(rtpctx);
  460. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  461. uint8_t *ptr;
  462. avio_close_dyn_buf(rtpctx->pb, &ptr);
  463. av_free(ptr);
  464. } else {
  465. avio_close(rtpctx->pb);
  466. }
  467. avformat_free_context(rtpctx);
  468. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  469. ff_rdt_parse_close(rtsp_st->transport_priv);
  470. else if (CONFIG_RTPDEC)
  471. rtp_parse_close(rtsp_st->transport_priv);
  472. }
  473. rtsp_st->transport_priv = NULL;
  474. if (rtsp_st->rtp_handle)
  475. ffurl_close(rtsp_st->rtp_handle);
  476. rtsp_st->rtp_handle = NULL;
  477. }
  478. }
  479. /* close and free RTSP streams */
  480. void ff_rtsp_close_streams(AVFormatContext *s)
  481. {
  482. RTSPState *rt = s->priv_data;
  483. int i;
  484. RTSPStream *rtsp_st;
  485. ff_rtsp_undo_setup(s);
  486. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  487. rtsp_st = rt->rtsp_streams[i];
  488. if (rtsp_st) {
  489. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  490. rtsp_st->dynamic_handler->free(
  491. rtsp_st->dynamic_protocol_context);
  492. av_free(rtsp_st);
  493. }
  494. }
  495. av_free(rt->rtsp_streams);
  496. if (rt->asf_ctx) {
  497. av_close_input_stream (rt->asf_ctx);
  498. rt->asf_ctx = NULL;
  499. }
  500. av_free(rt->p);
  501. av_free(rt->recvbuf);
  502. }
  503. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  504. {
  505. RTSPState *rt = s->priv_data;
  506. AVStream *st = NULL;
  507. /* open the RTP context */
  508. if (rtsp_st->stream_index >= 0)
  509. st = s->streams[rtsp_st->stream_index];
  510. if (!st)
  511. s->ctx_flags |= AVFMTCTX_NOHEADER;
  512. if (s->oformat && CONFIG_RTSP_MUXER) {
  513. rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
  514. rtsp_st->rtp_handle,
  515. RTSP_TCP_MAX_PACKET_SIZE);
  516. /* Ownership of rtp_handle is passed to the rtp mux context */
  517. rtsp_st->rtp_handle = NULL;
  518. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  519. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  520. rtsp_st->dynamic_protocol_context,
  521. rtsp_st->dynamic_handler);
  522. else if (CONFIG_RTPDEC)
  523. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  524. rtsp_st->sdp_payload_type,
  525. (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
  526. ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
  527. if (!rtsp_st->transport_priv) {
  528. return AVERROR(ENOMEM);
  529. } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
  530. if (rtsp_st->dynamic_handler) {
  531. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  532. rtsp_st->dynamic_protocol_context,
  533. rtsp_st->dynamic_handler);
  534. }
  535. }
  536. return 0;
  537. }
  538. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  539. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  540. {
  541. const char *p;
  542. int v;
  543. p = *pp;
  544. p += strspn(p, SPACE_CHARS);
  545. v = strtol(p, (char **)&p, 10);
  546. if (*p == '-') {
  547. p++;
  548. *min_ptr = v;
  549. v = strtol(p, (char **)&p, 10);
  550. *max_ptr = v;
  551. } else {
  552. *min_ptr = v;
  553. *max_ptr = v;
  554. }
  555. *pp = p;
  556. }
  557. /* XXX: only one transport specification is parsed */
  558. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  559. {
  560. char transport_protocol[16];
  561. char profile[16];
  562. char lower_transport[16];
  563. char parameter[16];
  564. RTSPTransportField *th;
  565. char buf[256];
  566. reply->nb_transports = 0;
  567. for (;;) {
  568. p += strspn(p, SPACE_CHARS);
  569. if (*p == '\0')
  570. break;
  571. th = &reply->transports[reply->nb_transports];
  572. get_word_sep(transport_protocol, sizeof(transport_protocol),
  573. "/", &p);
  574. if (!strcasecmp (transport_protocol, "rtp")) {
  575. get_word_sep(profile, sizeof(profile), "/;,", &p);
  576. lower_transport[0] = '\0';
  577. /* rtp/avp/<protocol> */
  578. if (*p == '/') {
  579. get_word_sep(lower_transport, sizeof(lower_transport),
  580. ";,", &p);
  581. }
  582. th->transport = RTSP_TRANSPORT_RTP;
  583. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  584. !strcasecmp (transport_protocol, "x-real-rdt")) {
  585. /* x-pn-tng/<protocol> */
  586. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  587. profile[0] = '\0';
  588. th->transport = RTSP_TRANSPORT_RDT;
  589. }
  590. if (!strcasecmp(lower_transport, "TCP"))
  591. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  592. else
  593. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  594. if (*p == ';')
  595. p++;
  596. /* get each parameter */
  597. while (*p != '\0' && *p != ',') {
  598. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  599. if (!strcmp(parameter, "port")) {
  600. if (*p == '=') {
  601. p++;
  602. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  603. }
  604. } else if (!strcmp(parameter, "client_port")) {
  605. if (*p == '=') {
  606. p++;
  607. rtsp_parse_range(&th->client_port_min,
  608. &th->client_port_max, &p);
  609. }
  610. } else if (!strcmp(parameter, "server_port")) {
  611. if (*p == '=') {
  612. p++;
  613. rtsp_parse_range(&th->server_port_min,
  614. &th->server_port_max, &p);
  615. }
  616. } else if (!strcmp(parameter, "interleaved")) {
  617. if (*p == '=') {
  618. p++;
  619. rtsp_parse_range(&th->interleaved_min,
  620. &th->interleaved_max, &p);
  621. }
  622. } else if (!strcmp(parameter, "multicast")) {
  623. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  624. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  625. } else if (!strcmp(parameter, "ttl")) {
  626. if (*p == '=') {
  627. p++;
  628. th->ttl = strtol(p, (char **)&p, 10);
  629. }
  630. } else if (!strcmp(parameter, "destination")) {
  631. if (*p == '=') {
  632. p++;
  633. get_word_sep(buf, sizeof(buf), ";,", &p);
  634. get_sockaddr(buf, &th->destination);
  635. }
  636. } else if (!strcmp(parameter, "source")) {
  637. if (*p == '=') {
  638. p++;
  639. get_word_sep(buf, sizeof(buf), ";,", &p);
  640. av_strlcpy(th->source, buf, sizeof(th->source));
  641. }
  642. }
  643. while (*p != ';' && *p != '\0' && *p != ',')
  644. p++;
  645. if (*p == ';')
  646. p++;
  647. }
  648. if (*p == ',')
  649. p++;
  650. reply->nb_transports++;
  651. }
  652. }
  653. static void handle_rtp_info(RTSPState *rt, const char *url,
  654. uint32_t seq, uint32_t rtptime)
  655. {
  656. int i;
  657. if (!rtptime || !url[0])
  658. return;
  659. if (rt->transport != RTSP_TRANSPORT_RTP)
  660. return;
  661. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  662. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  663. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  664. if (!rtpctx)
  665. continue;
  666. if (!strcmp(rtsp_st->control_url, url)) {
  667. rtpctx->base_timestamp = rtptime;
  668. break;
  669. }
  670. }
  671. }
  672. static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
  673. {
  674. int read = 0;
  675. char key[20], value[1024], url[1024] = "";
  676. uint32_t seq = 0, rtptime = 0;
  677. for (;;) {
  678. p += strspn(p, SPACE_CHARS);
  679. if (!*p)
  680. break;
  681. get_word_sep(key, sizeof(key), "=", &p);
  682. if (*p != '=')
  683. break;
  684. p++;
  685. get_word_sep(value, sizeof(value), ";, ", &p);
  686. read++;
  687. if (!strcmp(key, "url"))
  688. av_strlcpy(url, value, sizeof(url));
  689. else if (!strcmp(key, "seq"))
  690. seq = strtoul(value, NULL, 10);
  691. else if (!strcmp(key, "rtptime"))
  692. rtptime = strtoul(value, NULL, 10);
  693. if (*p == ',') {
  694. handle_rtp_info(rt, url, seq, rtptime);
  695. url[0] = '\0';
  696. seq = rtptime = 0;
  697. read = 0;
  698. }
  699. if (*p)
  700. p++;
  701. }
  702. if (read > 0)
  703. handle_rtp_info(rt, url, seq, rtptime);
  704. }
  705. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  706. RTSPState *rt, const char *method)
  707. {
  708. const char *p;
  709. /* NOTE: we do case independent match for broken servers */
  710. p = buf;
  711. if (av_stristart(p, "Session:", &p)) {
  712. int t;
  713. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  714. if (av_stristart(p, ";timeout=", &p) &&
  715. (t = strtol(p, NULL, 10)) > 0) {
  716. reply->timeout = t;
  717. }
  718. } else if (av_stristart(p, "Content-Length:", &p)) {
  719. reply->content_length = strtol(p, NULL, 10);
  720. } else if (av_stristart(p, "Transport:", &p)) {
  721. rtsp_parse_transport(reply, p);
  722. } else if (av_stristart(p, "CSeq:", &p)) {
  723. reply->seq = strtol(p, NULL, 10);
  724. } else if (av_stristart(p, "Range:", &p)) {
  725. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  726. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  727. p += strspn(p, SPACE_CHARS);
  728. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  729. } else if (av_stristart(p, "Server:", &p)) {
  730. p += strspn(p, SPACE_CHARS);
  731. av_strlcpy(reply->server, p, sizeof(reply->server));
  732. } else if (av_stristart(p, "Notice:", &p) ||
  733. av_stristart(p, "X-Notice:", &p)) {
  734. reply->notice = strtol(p, NULL, 10);
  735. } else if (av_stristart(p, "Location:", &p)) {
  736. p += strspn(p, SPACE_CHARS);
  737. av_strlcpy(reply->location, p , sizeof(reply->location));
  738. } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
  739. p += strspn(p, SPACE_CHARS);
  740. ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
  741. } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
  742. p += strspn(p, SPACE_CHARS);
  743. ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
  744. } else if (av_stristart(p, "Content-Base:", &p) && rt) {
  745. p += strspn(p, SPACE_CHARS);
  746. if (method && !strcmp(method, "DESCRIBE"))
  747. av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
  748. } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
  749. p += strspn(p, SPACE_CHARS);
  750. if (method && !strcmp(method, "PLAY"))
  751. rtsp_parse_rtp_info(rt, p);
  752. } else if (av_stristart(p, "Public:", &p) && rt) {
  753. if (strstr(p, "GET_PARAMETER") &&
  754. method && !strcmp(method, "OPTIONS"))
  755. rt->get_parameter_supported = 1;
  756. }
  757. }
  758. /* skip a RTP/TCP interleaved packet */
  759. void ff_rtsp_skip_packet(AVFormatContext *s)
  760. {
  761. RTSPState *rt = s->priv_data;
  762. int ret, len, len1;
  763. uint8_t buf[1024];
  764. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  765. if (ret != 3)
  766. return;
  767. len = AV_RB16(buf + 1);
  768. av_dlog(s, "skipping RTP packet len=%d\n", len);
  769. /* skip payload */
  770. while (len > 0) {
  771. len1 = len;
  772. if (len1 > sizeof(buf))
  773. len1 = sizeof(buf);
  774. ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
  775. if (ret != len1)
  776. return;
  777. len -= len1;
  778. }
  779. }
  780. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  781. unsigned char **content_ptr,
  782. int return_on_interleaved_data, const char *method)
  783. {
  784. RTSPState *rt = s->priv_data;
  785. char buf[4096], buf1[1024], *q;
  786. unsigned char ch;
  787. const char *p;
  788. int ret, content_length, line_count = 0;
  789. unsigned char *content = NULL;
  790. memset(reply, 0, sizeof(*reply));
  791. /* parse reply (XXX: use buffers) */
  792. rt->last_reply[0] = '\0';
  793. for (;;) {
  794. q = buf;
  795. for (;;) {
  796. ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
  797. av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  798. if (ret != 1)
  799. return AVERROR_EOF;
  800. if (ch == '\n')
  801. break;
  802. if (ch == '$') {
  803. /* XXX: only parse it if first char on line ? */
  804. if (return_on_interleaved_data) {
  805. return 1;
  806. } else
  807. ff_rtsp_skip_packet(s);
  808. } else if (ch != '\r') {
  809. if ((q - buf) < sizeof(buf) - 1)
  810. *q++ = ch;
  811. }
  812. }
  813. *q = '\0';
  814. av_dlog(s, "line='%s'\n", buf);
  815. /* test if last line */
  816. if (buf[0] == '\0')
  817. break;
  818. p = buf;
  819. if (line_count == 0) {
  820. /* get reply code */
  821. get_word(buf1, sizeof(buf1), &p);
  822. get_word(buf1, sizeof(buf1), &p);
  823. reply->status_code = atoi(buf1);
  824. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  825. } else {
  826. ff_rtsp_parse_line(reply, p, rt, method);
  827. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  828. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  829. }
  830. line_count++;
  831. }
  832. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  833. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  834. content_length = reply->content_length;
  835. if (content_length > 0) {
  836. /* leave some room for a trailing '\0' (useful for simple parsing) */
  837. content = av_malloc(content_length + 1);
  838. ffurl_read_complete(rt->rtsp_hd, content, content_length);
  839. content[content_length] = '\0';
  840. }
  841. if (content_ptr)
  842. *content_ptr = content;
  843. else
  844. av_free(content);
  845. if (rt->seq != reply->seq) {
  846. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  847. rt->seq, reply->seq);
  848. }
  849. /* EOS */
  850. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  851. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  852. reply->notice == 2306 /* Continuous Feed Terminated */) {
  853. rt->state = RTSP_STATE_IDLE;
  854. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  855. return AVERROR(EIO); /* data or server error */
  856. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  857. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  858. return AVERROR(EPERM);
  859. return 0;
  860. }
  861. /**
  862. * Send a command to the RTSP server without waiting for the reply.
  863. *
  864. * @param s RTSP (de)muxer context
  865. * @param method the method for the request
  866. * @param url the target url for the request
  867. * @param headers extra header lines to include in the request
  868. * @param send_content if non-null, the data to send as request body content
  869. * @param send_content_length the length of the send_content data, or 0 if
  870. * send_content is null
  871. *
  872. * @return zero if success, nonzero otherwise
  873. */
  874. static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  875. const char *method, const char *url,
  876. const char *headers,
  877. const unsigned char *send_content,
  878. int send_content_length)
  879. {
  880. RTSPState *rt = s->priv_data;
  881. char buf[4096], *out_buf;
  882. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  883. /* Add in RTSP headers */
  884. out_buf = buf;
  885. rt->seq++;
  886. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  887. if (headers)
  888. av_strlcat(buf, headers, sizeof(buf));
  889. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  890. if (rt->session_id[0] != '\0' && (!headers ||
  891. !strstr(headers, "\nIf-Match:"))) {
  892. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  893. }
  894. if (rt->auth[0]) {
  895. char *str = ff_http_auth_create_response(&rt->auth_state,
  896. rt->auth, url, method);
  897. if (str)
  898. av_strlcat(buf, str, sizeof(buf));
  899. av_free(str);
  900. }
  901. if (send_content_length > 0 && send_content)
  902. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  903. av_strlcat(buf, "\r\n", sizeof(buf));
  904. /* base64 encode rtsp if tunneling */
  905. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  906. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  907. out_buf = base64buf;
  908. }
  909. av_dlog(s, "Sending:\n%s--\n", buf);
  910. ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  911. if (send_content_length > 0 && send_content) {
  912. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  913. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  914. "with content data not supported\n");
  915. return AVERROR_PATCHWELCOME;
  916. }
  917. ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
  918. }
  919. rt->last_cmd_time = av_gettime();
  920. return 0;
  921. }
  922. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  923. const char *url, const char *headers)
  924. {
  925. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  926. }
  927. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  928. const char *headers, RTSPMessageHeader *reply,
  929. unsigned char **content_ptr)
  930. {
  931. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  932. content_ptr, NULL, 0);
  933. }
  934. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  935. const char *method, const char *url,
  936. const char *header,
  937. RTSPMessageHeader *reply,
  938. unsigned char **content_ptr,
  939. const unsigned char *send_content,
  940. int send_content_length)
  941. {
  942. RTSPState *rt = s->priv_data;
  943. HTTPAuthType cur_auth_type;
  944. int ret;
  945. retry:
  946. cur_auth_type = rt->auth_state.auth_type;
  947. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  948. send_content,
  949. send_content_length)))
  950. return ret;
  951. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
  952. return ret;
  953. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  954. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  955. goto retry;
  956. if (reply->status_code > 400){
  957. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  958. method,
  959. reply->status_code,
  960. reply->reason);
  961. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  962. }
  963. return 0;
  964. }
  965. /**
  966. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  967. */
  968. int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
  969. int lower_transport, const char *real_challenge)
  970. {
  971. RTSPState *rt = s->priv_data;
  972. int rtx, j, i, err, interleave = 0;
  973. RTSPStream *rtsp_st;
  974. RTSPMessageHeader reply1, *reply = &reply1;
  975. char cmd[2048];
  976. const char *trans_pref;
  977. if (rt->transport == RTSP_TRANSPORT_RDT)
  978. trans_pref = "x-pn-tng";
  979. else
  980. trans_pref = "RTP/AVP";
  981. /* default timeout: 1 minute */
  982. rt->timeout = 60;
  983. /* for each stream, make the setup request */
  984. /* XXX: we assume the same server is used for the control of each
  985. * RTSP stream */
  986. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  987. char transport[2048];
  988. /**
  989. * WMS serves all UDP data over a single connection, the RTX, which
  990. * isn't necessarily the first in the SDP but has to be the first
  991. * to be set up, else the second/third SETUP will fail with a 461.
  992. */
  993. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  994. rt->server_type == RTSP_SERVER_WMS) {
  995. if (i == 0) {
  996. /* rtx first */
  997. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  998. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  999. if (len >= 4 &&
  1000. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  1001. "/rtx"))
  1002. break;
  1003. }
  1004. if (rtx == rt->nb_rtsp_streams)
  1005. return -1; /* no RTX found */
  1006. rtsp_st = rt->rtsp_streams[rtx];
  1007. } else
  1008. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  1009. } else
  1010. rtsp_st = rt->rtsp_streams[i];
  1011. /* RTP/UDP */
  1012. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  1013. char buf[256];
  1014. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  1015. port = reply->transports[0].client_port_min;
  1016. goto have_port;
  1017. }
  1018. /* first try in specified port range */
  1019. if (RTSP_RTP_PORT_MIN != 0) {
  1020. while (j <= RTSP_RTP_PORT_MAX) {
  1021. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  1022. "?localport=%d", j);
  1023. /* we will use two ports per rtp stream (rtp and rtcp) */
  1024. j += 2;
  1025. if (ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE) == 0)
  1026. goto rtp_opened;
  1027. }
  1028. }
  1029. #if 0
  1030. /* then try on any port */
  1031. if (ffurl_open(&rtsp_st->rtp_handle, "rtp://", AVIO_FLAG_READ) < 0) {
  1032. err = AVERROR_INVALIDDATA;
  1033. goto fail;
  1034. }
  1035. #else
  1036. av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
  1037. err = AVERROR(EIO);
  1038. goto fail;
  1039. #endif
  1040. rtp_opened:
  1041. port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  1042. have_port:
  1043. snprintf(transport, sizeof(transport) - 1,
  1044. "%s/UDP;", trans_pref);
  1045. if (rt->server_type != RTSP_SERVER_REAL)
  1046. av_strlcat(transport, "unicast;", sizeof(transport));
  1047. av_strlcatf(transport, sizeof(transport),
  1048. "client_port=%d", port);
  1049. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1050. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1051. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1052. }
  1053. /* RTP/TCP */
  1054. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1055. /** For WMS streams, the application streams are only used for
  1056. * UDP. When trying to set it up for TCP streams, the server
  1057. * will return an error. Therefore, we skip those streams. */
  1058. if (rt->server_type == RTSP_SERVER_WMS &&
  1059. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1060. AVMEDIA_TYPE_DATA)
  1061. continue;
  1062. snprintf(transport, sizeof(transport) - 1,
  1063. "%s/TCP;", trans_pref);
  1064. if (rt->transport != RTSP_TRANSPORT_RDT)
  1065. av_strlcat(transport, "unicast;", sizeof(transport));
  1066. av_strlcatf(transport, sizeof(transport),
  1067. "interleaved=%d-%d",
  1068. interleave, interleave + 1);
  1069. interleave += 2;
  1070. }
  1071. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1072. snprintf(transport, sizeof(transport) - 1,
  1073. "%s/UDP;multicast", trans_pref);
  1074. }
  1075. if (s->oformat) {
  1076. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1077. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1078. rt->server_type == RTSP_SERVER_WMS)
  1079. av_strlcat(transport, ";mode=play", sizeof(transport));
  1080. snprintf(cmd, sizeof(cmd),
  1081. "Transport: %s\r\n",
  1082. transport);
  1083. if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
  1084. char real_res[41], real_csum[9];
  1085. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1086. real_challenge);
  1087. av_strlcatf(cmd, sizeof(cmd),
  1088. "If-Match: %s\r\n"
  1089. "RealChallenge2: %s, sd=%s\r\n",
  1090. rt->session_id, real_res, real_csum);
  1091. }
  1092. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1093. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1094. err = 1;
  1095. goto fail;
  1096. } else if (reply->status_code != RTSP_STATUS_OK ||
  1097. reply->nb_transports != 1) {
  1098. err = AVERROR_INVALIDDATA;
  1099. goto fail;
  1100. }
  1101. /* XXX: same protocol for all streams is required */
  1102. if (i > 0) {
  1103. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1104. reply->transports[0].transport != rt->transport) {
  1105. err = AVERROR_INVALIDDATA;
  1106. goto fail;
  1107. }
  1108. } else {
  1109. rt->lower_transport = reply->transports[0].lower_transport;
  1110. rt->transport = reply->transports[0].transport;
  1111. }
  1112. /* Fail if the server responded with another lower transport mode
  1113. * than what we requested. */
  1114. if (reply->transports[0].lower_transport != lower_transport) {
  1115. av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
  1116. err = AVERROR_INVALIDDATA;
  1117. goto fail;
  1118. }
  1119. switch(reply->transports[0].lower_transport) {
  1120. case RTSP_LOWER_TRANSPORT_TCP:
  1121. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1122. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1123. break;
  1124. case RTSP_LOWER_TRANSPORT_UDP: {
  1125. char url[1024], options[30] = "";
  1126. if (rt->filter_source)
  1127. av_strlcpy(options, "?connect=1", sizeof(options));
  1128. /* Use source address if specified */
  1129. if (reply->transports[0].source[0]) {
  1130. ff_url_join(url, sizeof(url), "rtp", NULL,
  1131. reply->transports[0].source,
  1132. reply->transports[0].server_port_min, "%s", options);
  1133. } else {
  1134. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1135. reply->transports[0].server_port_min, "%s", options);
  1136. }
  1137. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1138. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1139. err = AVERROR_INVALIDDATA;
  1140. goto fail;
  1141. }
  1142. /* Try to initialize the connection state in a
  1143. * potential NAT router by sending dummy packets.
  1144. * RTP/RTCP dummy packets are used for RDT, too.
  1145. */
  1146. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
  1147. CONFIG_RTPDEC)
  1148. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1149. break;
  1150. }
  1151. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1152. char url[1024], namebuf[50];
  1153. struct sockaddr_storage addr;
  1154. int port, ttl;
  1155. if (reply->transports[0].destination.ss_family) {
  1156. addr = reply->transports[0].destination;
  1157. port = reply->transports[0].port_min;
  1158. ttl = reply->transports[0].ttl;
  1159. } else {
  1160. addr = rtsp_st->sdp_ip;
  1161. port = rtsp_st->sdp_port;
  1162. ttl = rtsp_st->sdp_ttl;
  1163. }
  1164. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1165. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1166. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1167. port, "?ttl=%d", ttl);
  1168. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE) < 0) {
  1169. err = AVERROR_INVALIDDATA;
  1170. goto fail;
  1171. }
  1172. break;
  1173. }
  1174. }
  1175. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1176. goto fail;
  1177. }
  1178. if (reply->timeout > 0)
  1179. rt->timeout = reply->timeout;
  1180. if (rt->server_type == RTSP_SERVER_REAL)
  1181. rt->need_subscription = 1;
  1182. return 0;
  1183. fail:
  1184. ff_rtsp_undo_setup(s);
  1185. return err;
  1186. }
  1187. void ff_rtsp_close_connections(AVFormatContext *s)
  1188. {
  1189. RTSPState *rt = s->priv_data;
  1190. if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
  1191. ffurl_close(rt->rtsp_hd);
  1192. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1193. }
  1194. int ff_rtsp_connect(AVFormatContext *s)
  1195. {
  1196. RTSPState *rt = s->priv_data;
  1197. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1198. char *option_list, *option, *filename;
  1199. int port, err, tcp_fd;
  1200. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1201. int lower_transport_mask = 0;
  1202. char real_challenge[64] = "";
  1203. struct sockaddr_storage peer;
  1204. socklen_t peer_len = sizeof(peer);
  1205. if (!ff_network_init())
  1206. return AVERROR(EIO);
  1207. redirect:
  1208. rt->control_transport = RTSP_MODE_PLAIN;
  1209. /* extract hostname and port */
  1210. av_url_split(NULL, 0, auth, sizeof(auth),
  1211. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1212. if (*auth) {
  1213. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1214. }
  1215. if (port < 0)
  1216. port = RTSP_DEFAULT_PORT;
  1217. /* search for options */
  1218. option_list = strrchr(path, '?');
  1219. if (option_list) {
  1220. /* Strip out the RTSP specific options, write out the rest of
  1221. * the options back into the same string. */
  1222. filename = option_list;
  1223. while (option_list) {
  1224. /* move the option pointer */
  1225. option = ++option_list;
  1226. option_list = strchr(option_list, '&');
  1227. if (option_list)
  1228. *option_list = 0;
  1229. /* handle the options */
  1230. if (!strcmp(option, "udp")) {
  1231. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1232. } else if (!strcmp(option, "multicast")) {
  1233. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1234. } else if (!strcmp(option, "tcp")) {
  1235. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1236. } else if(!strcmp(option, "http")) {
  1237. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1238. rt->control_transport = RTSP_MODE_TUNNEL;
  1239. } else if (!strcmp(option, "filter_src")) {
  1240. rt->filter_source = 1;
  1241. } else {
  1242. /* Write options back into the buffer, using memmove instead
  1243. * of strcpy since the strings may overlap. */
  1244. int len = strlen(option);
  1245. memmove(++filename, option, len);
  1246. filename += len;
  1247. if (option_list) *filename = '&';
  1248. }
  1249. }
  1250. *filename = 0;
  1251. }
  1252. if (!lower_transport_mask)
  1253. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1254. if (s->oformat) {
  1255. /* Only UDP or TCP - UDP multicast isn't supported. */
  1256. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1257. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1258. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1259. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1260. "only UDP and TCP are supported for output.\n");
  1261. err = AVERROR(EINVAL);
  1262. goto fail;
  1263. }
  1264. }
  1265. /* Construct the URI used in request; this is similar to s->filename,
  1266. * but with authentication credentials removed and RTSP specific options
  1267. * stripped out. */
  1268. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1269. host, port, "%s", path);
  1270. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1271. /* set up initial handshake for tunneling */
  1272. char httpname[1024];
  1273. char sessioncookie[17];
  1274. char headers[1024];
  1275. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1276. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1277. av_get_random_seed(), av_get_random_seed());
  1278. /* GET requests */
  1279. if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ) < 0) {
  1280. err = AVERROR(EIO);
  1281. goto fail;
  1282. }
  1283. /* generate GET headers */
  1284. snprintf(headers, sizeof(headers),
  1285. "x-sessioncookie: %s\r\n"
  1286. "Accept: application/x-rtsp-tunnelled\r\n"
  1287. "Pragma: no-cache\r\n"
  1288. "Cache-Control: no-cache\r\n",
  1289. sessioncookie);
  1290. ff_http_set_headers(rt->rtsp_hd, headers);
  1291. /* complete the connection */
  1292. if (ffurl_connect(rt->rtsp_hd)) {
  1293. err = AVERROR(EIO);
  1294. goto fail;
  1295. }
  1296. /* POST requests */
  1297. if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE) < 0 ) {
  1298. err = AVERROR(EIO);
  1299. goto fail;
  1300. }
  1301. /* generate POST headers */
  1302. snprintf(headers, sizeof(headers),
  1303. "x-sessioncookie: %s\r\n"
  1304. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1305. "Pragma: no-cache\r\n"
  1306. "Cache-Control: no-cache\r\n"
  1307. "Content-Length: 32767\r\n"
  1308. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1309. sessioncookie);
  1310. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1311. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1312. /* Initialize the authentication state for the POST session. The HTTP
  1313. * protocol implementation doesn't properly handle multi-pass
  1314. * authentication for POST requests, since it would require one of
  1315. * the following:
  1316. * - implementing Expect: 100-continue, which many HTTP servers
  1317. * don't support anyway, even less the RTSP servers that do HTTP
  1318. * tunneling
  1319. * - sending the whole POST data until getting a 401 reply specifying
  1320. * what authentication method to use, then resending all that data
  1321. * - waiting for potential 401 replies directly after sending the
  1322. * POST header (waiting for some unspecified time)
  1323. * Therefore, we copy the full auth state, which works for both basic
  1324. * and digest. (For digest, we would have to synchronize the nonce
  1325. * count variable between the two sessions, if we'd do more requests
  1326. * with the original session, though.)
  1327. */
  1328. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1329. /* complete the connection */
  1330. if (ffurl_connect(rt->rtsp_hd_out)) {
  1331. err = AVERROR(EIO);
  1332. goto fail;
  1333. }
  1334. } else {
  1335. /* open the tcp connection */
  1336. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1337. if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE) < 0) {
  1338. err = AVERROR(EIO);
  1339. goto fail;
  1340. }
  1341. rt->rtsp_hd_out = rt->rtsp_hd;
  1342. }
  1343. rt->seq = 0;
  1344. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1345. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1346. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1347. NULL, 0, NI_NUMERICHOST);
  1348. }
  1349. /* request options supported by the server; this also detects server
  1350. * type */
  1351. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1352. cmd[0] = 0;
  1353. if (rt->server_type == RTSP_SERVER_REAL)
  1354. av_strlcat(cmd,
  1355. /**
  1356. * The following entries are required for proper
  1357. * streaming from a Realmedia server. They are
  1358. * interdependent in some way although we currently
  1359. * don't quite understand how. Values were copied
  1360. * from mplayer SVN r23589.
  1361. * @param CompanyID is a 16-byte ID in base64
  1362. * @param ClientChallenge is a 16-byte ID in hex
  1363. */
  1364. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1365. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1366. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1367. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1368. sizeof(cmd));
  1369. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1370. if (reply->status_code != RTSP_STATUS_OK) {
  1371. err = AVERROR_INVALIDDATA;
  1372. goto fail;
  1373. }
  1374. /* detect server type if not standard-compliant RTP */
  1375. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1376. rt->server_type = RTSP_SERVER_REAL;
  1377. continue;
  1378. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1379. rt->server_type = RTSP_SERVER_WMS;
  1380. } else if (rt->server_type == RTSP_SERVER_REAL)
  1381. strcpy(real_challenge, reply->real_challenge);
  1382. break;
  1383. }
  1384. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1385. err = ff_rtsp_setup_input_streams(s, reply);
  1386. else if (CONFIG_RTSP_MUXER)
  1387. err = ff_rtsp_setup_output_streams(s, host);
  1388. if (err)
  1389. goto fail;
  1390. do {
  1391. int lower_transport = ff_log2_tab[lower_transport_mask &
  1392. ~(lower_transport_mask - 1)];
  1393. err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
  1394. rt->server_type == RTSP_SERVER_REAL ?
  1395. real_challenge : NULL);
  1396. if (err < 0)
  1397. goto fail;
  1398. lower_transport_mask &= ~(1 << lower_transport);
  1399. if (lower_transport_mask == 0 && err == 1) {
  1400. err = AVERROR(EPROTONOSUPPORT);
  1401. goto fail;
  1402. }
  1403. } while (err);
  1404. rt->lower_transport_mask = lower_transport_mask;
  1405. av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
  1406. rt->state = RTSP_STATE_IDLE;
  1407. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1408. return 0;
  1409. fail:
  1410. ff_rtsp_close_streams(s);
  1411. ff_rtsp_close_connections(s);
  1412. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1413. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1414. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1415. reply->status_code,
  1416. s->filename);
  1417. goto redirect;
  1418. }
  1419. ff_network_close();
  1420. return err;
  1421. }
  1422. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1423. #if CONFIG_RTPDEC
  1424. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1425. uint8_t *buf, int buf_size, int64_t wait_end)
  1426. {
  1427. RTSPState *rt = s->priv_data;
  1428. RTSPStream *rtsp_st;
  1429. int n, i, ret, tcp_fd, timeout_cnt = 0;
  1430. int max_p = 0;
  1431. struct pollfd *p = rt->p;
  1432. for (;;) {
  1433. if (url_interrupt_cb())
  1434. return AVERROR_EXIT;
  1435. if (wait_end && wait_end - av_gettime() < 0)
  1436. return AVERROR(EAGAIN);
  1437. max_p = 0;
  1438. if (rt->rtsp_hd) {
  1439. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1440. p[max_p].fd = tcp_fd;
  1441. p[max_p++].events = POLLIN;
  1442. } else {
  1443. tcp_fd = -1;
  1444. }
  1445. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1446. rtsp_st = rt->rtsp_streams[i];
  1447. if (rtsp_st->rtp_handle) {
  1448. p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
  1449. p[max_p++].events = POLLIN;
  1450. p[max_p].fd = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1451. p[max_p++].events = POLLIN;
  1452. }
  1453. }
  1454. n = poll(p, max_p, POLL_TIMEOUT_MS);
  1455. if (n > 0) {
  1456. int j = 1 - (tcp_fd == -1);
  1457. timeout_cnt = 0;
  1458. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1459. rtsp_st = rt->rtsp_streams[i];
  1460. if (rtsp_st->rtp_handle) {
  1461. if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
  1462. ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
  1463. if (ret > 0) {
  1464. *prtsp_st = rtsp_st;
  1465. return ret;
  1466. }
  1467. }
  1468. j+=2;
  1469. }
  1470. }
  1471. #if CONFIG_RTSP_DEMUXER
  1472. if (tcp_fd != -1 && p[0].revents & POLLIN) {
  1473. RTSPMessageHeader reply;
  1474. ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
  1475. if (ret < 0)
  1476. return ret;
  1477. /* XXX: parse message */
  1478. if (rt->state != RTSP_STATE_STREAMING)
  1479. return 0;
  1480. }
  1481. #endif
  1482. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1483. return AVERROR(ETIMEDOUT);
  1484. } else if (n < 0 && errno != EINTR)
  1485. return AVERROR(errno);
  1486. }
  1487. }
  1488. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1489. {
  1490. RTSPState *rt = s->priv_data;
  1491. int ret, len;
  1492. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1493. int64_t wait_end = 0;
  1494. if (rt->nb_byes == rt->nb_rtsp_streams)
  1495. return AVERROR_EOF;
  1496. /* get next frames from the same RTP packet */
  1497. if (rt->cur_transport_priv) {
  1498. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1499. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1500. } else
  1501. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1502. if (ret == 0) {
  1503. rt->cur_transport_priv = NULL;
  1504. return 0;
  1505. } else if (ret == 1) {
  1506. return 0;
  1507. } else
  1508. rt->cur_transport_priv = NULL;
  1509. }
  1510. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1511. int i;
  1512. int64_t first_queue_time = 0;
  1513. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1514. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1515. int64_t queue_time;
  1516. if (!rtpctx)
  1517. continue;
  1518. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1519. if (queue_time && (queue_time - first_queue_time < 0 ||
  1520. !first_queue_time)) {
  1521. first_queue_time = queue_time;
  1522. first_queue_st = rt->rtsp_streams[i];
  1523. }
  1524. }
  1525. if (first_queue_time)
  1526. wait_end = first_queue_time + s->max_delay;
  1527. }
  1528. /* read next RTP packet */
  1529. redo:
  1530. if (!rt->recvbuf) {
  1531. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1532. if (!rt->recvbuf)
  1533. return AVERROR(ENOMEM);
  1534. }
  1535. switch(rt->lower_transport) {
  1536. default:
  1537. #if CONFIG_RTSP_DEMUXER
  1538. case RTSP_LOWER_TRANSPORT_TCP:
  1539. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1540. break;
  1541. #endif
  1542. case RTSP_LOWER_TRANSPORT_UDP:
  1543. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1544. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1545. if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1546. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1547. break;
  1548. }
  1549. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1550. rt->transport == RTSP_TRANSPORT_RTP) {
  1551. rtsp_st = first_queue_st;
  1552. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1553. goto end;
  1554. }
  1555. if (len < 0)
  1556. return len;
  1557. if (len == 0)
  1558. return AVERROR_EOF;
  1559. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1560. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1561. } else {
  1562. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1563. if (ret < 0) {
  1564. /* Either bad packet, or a RTCP packet. Check if the
  1565. * first_rtcp_ntp_time field was initialized. */
  1566. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1567. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1568. /* first_rtcp_ntp_time has been initialized for this stream,
  1569. * copy the same value to all other uninitialized streams,
  1570. * in order to map their timestamp origin to the same ntp time
  1571. * as this one. */
  1572. int i;
  1573. AVStream *st = NULL;
  1574. if (rtsp_st->stream_index >= 0)
  1575. st = s->streams[rtsp_st->stream_index];
  1576. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1577. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1578. AVStream *st2 = NULL;
  1579. if (rt->rtsp_streams[i]->stream_index >= 0)
  1580. st2 = s->streams[rt->rtsp_streams[i]->stream_index];
  1581. if (rtpctx2 && st && st2 &&
  1582. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  1583. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1584. rtpctx2->rtcp_ts_offset = av_rescale_q(
  1585. rtpctx->rtcp_ts_offset, st->time_base,
  1586. st2->time_base);
  1587. }
  1588. }
  1589. }
  1590. if (ret == -RTCP_BYE) {
  1591. rt->nb_byes++;
  1592. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1593. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1594. if (rt->nb_byes == rt->nb_rtsp_streams)
  1595. return AVERROR_EOF;
  1596. }
  1597. }
  1598. }
  1599. end:
  1600. if (ret < 0)
  1601. goto redo;
  1602. if (ret == 1)
  1603. /* more packets may follow, so we save the RTP context */
  1604. rt->cur_transport_priv = rtsp_st->transport_priv;
  1605. return ret;
  1606. }
  1607. #endif /* CONFIG_RTPDEC */
  1608. #if CONFIG_SDP_DEMUXER
  1609. static int sdp_probe(AVProbeData *p1)
  1610. {
  1611. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1612. /* we look for a line beginning "c=IN IP" */
  1613. while (p < p_end && *p != '\0') {
  1614. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1615. av_strstart(p, "c=IN IP", NULL))
  1616. return AVPROBE_SCORE_MAX / 2;
  1617. while (p < p_end - 1 && *p != '\n') p++;
  1618. if (++p >= p_end)
  1619. break;
  1620. if (*p == '\r')
  1621. p++;
  1622. }
  1623. return 0;
  1624. }
  1625. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1626. {
  1627. RTSPState *rt = s->priv_data;
  1628. RTSPStream *rtsp_st;
  1629. int size, i, err;
  1630. char *content;
  1631. char url[1024];
  1632. if (!ff_network_init())
  1633. return AVERROR(EIO);
  1634. /* read the whole sdp file */
  1635. /* XXX: better loading */
  1636. content = av_malloc(SDP_MAX_SIZE);
  1637. size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
  1638. if (size <= 0) {
  1639. av_free(content);
  1640. return AVERROR_INVALIDDATA;
  1641. }
  1642. content[size] ='\0';
  1643. err = ff_sdp_parse(s, content);
  1644. av_free(content);
  1645. if (err) goto fail;
  1646. /* open each RTP stream */
  1647. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1648. char namebuf[50];
  1649. rtsp_st = rt->rtsp_streams[i];
  1650. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1651. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1652. ff_url_join(url, sizeof(url), "rtp", NULL,
  1653. namebuf, rtsp_st->sdp_port,
  1654. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1655. rtsp_st->sdp_ttl);
  1656. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE) < 0) {
  1657. err = AVERROR_INVALIDDATA;
  1658. goto fail;
  1659. }
  1660. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1661. goto fail;
  1662. }
  1663. return 0;
  1664. fail:
  1665. ff_rtsp_close_streams(s);
  1666. ff_network_close();
  1667. return err;
  1668. }
  1669. static int sdp_read_close(AVFormatContext *s)
  1670. {
  1671. ff_rtsp_close_streams(s);
  1672. ff_network_close();
  1673. return 0;
  1674. }
  1675. AVInputFormat ff_sdp_demuxer = {
  1676. "sdp",
  1677. NULL_IF_CONFIG_SMALL("SDP"),
  1678. sizeof(RTSPState),
  1679. sdp_probe,
  1680. sdp_read_header,
  1681. ff_rtsp_fetch_packet,
  1682. sdp_read_close,
  1683. };
  1684. #endif /* CONFIG_SDP_DEMUXER */
  1685. #if CONFIG_RTP_DEMUXER
  1686. static int rtp_probe(AVProbeData *p)
  1687. {
  1688. if (av_strstart(p->filename, "rtp:", NULL))
  1689. return AVPROBE_SCORE_MAX;
  1690. return 0;
  1691. }
  1692. static int rtp_read_header(AVFormatContext *s,
  1693. AVFormatParameters *ap)
  1694. {
  1695. uint8_t recvbuf[1500];
  1696. char host[500], sdp[500];
  1697. int ret, port;
  1698. URLContext* in = NULL;
  1699. int payload_type;
  1700. AVCodecContext codec;
  1701. struct sockaddr_storage addr;
  1702. AVIOContext pb;
  1703. socklen_t addrlen = sizeof(addr);
  1704. if (!ff_network_init())
  1705. return AVERROR(EIO);
  1706. ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ);
  1707. if (ret)
  1708. goto fail;
  1709. while (1) {
  1710. ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
  1711. if (ret == AVERROR(EAGAIN))
  1712. continue;
  1713. if (ret < 0)
  1714. goto fail;
  1715. if (ret < 12) {
  1716. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  1717. continue;
  1718. }
  1719. if ((recvbuf[0] & 0xc0) != 0x80) {
  1720. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  1721. "received\n");
  1722. continue;
  1723. }
  1724. payload_type = recvbuf[1] & 0x7f;
  1725. break;
  1726. }
  1727. getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  1728. ffurl_close(in);
  1729. in = NULL;
  1730. memset(&codec, 0, sizeof(codec));
  1731. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  1732. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  1733. "without an SDP file describing it\n",
  1734. payload_type);
  1735. goto fail;
  1736. }
  1737. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  1738. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  1739. "properly you need an SDP file "
  1740. "describing it\n");
  1741. }
  1742. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  1743. NULL, 0, s->filename);
  1744. snprintf(sdp, sizeof(sdp),
  1745. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  1746. addr.ss_family == AF_INET ? 4 : 6, host,
  1747. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  1748. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  1749. port, payload_type);
  1750. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1751. ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  1752. s->pb = &pb;
  1753. /* sdp_read_header initializes this again */
  1754. ff_network_close();
  1755. ret = sdp_read_header(s, ap);
  1756. s->pb = NULL;
  1757. return ret;
  1758. fail:
  1759. if (in)
  1760. ffurl_close(in);
  1761. ff_network_close();
  1762. return ret;
  1763. }
  1764. AVInputFormat ff_rtp_demuxer = {
  1765. "rtp",
  1766. NULL_IF_CONFIG_SMALL("RTP input format"),
  1767. sizeof(RTSPState),
  1768. rtp_probe,
  1769. rtp_read_header,
  1770. ff_rtsp_fetch_packet,
  1771. sdp_read_close,
  1772. .flags = AVFMT_NOFILE,
  1773. };
  1774. #endif /* CONFIG_RTP_DEMUXER */